Full Code of slash-hq/slash for AI

master 01e55ce89b90 cached
42 files
206.2 KB
54.1k tokens
2 symbols
1 requests
Download .txt
Showing preview only (222K chars total). Download the full file or copy to clipboard to get everything.
Repository: slash-hq/slash
Branch: master
Commit: 01e55ce89b90
Files: 42
Total size: 206.2 KB

Directory structure:
gitextract_itntp5kx/

├── .gitignore
├── GitHub/
│   ├── scr.pxm
│   ├── slash_logo.pxm
│   └── slash_logo_small.pxm
├── LICENSE
├── Package.swift
├── README.md
├── Sources/
│   ├── Application.swift
│   ├── ChannelsListView.swift
│   ├── CrashReporter.swift
│   ├── MessagesListView.swift
│   ├── R.swift
│   ├── Server.swift
│   ├── SlackAdapter.swift
│   ├── SlackChannel.swift
│   ├── SlackContext.swift
│   ├── SlackEmojiDecoder.swift
│   ├── SlackEvent.swift
│   ├── SlackGroup.swift
│   ├── SlackIM.swift
│   ├── SlackMessage.swift
│   ├── SlackMessageReaction.swift
│   ├── SlackOAuth2.swift
│   ├── SlackRealTimeClient.swift
│   ├── SlackTeam.swift
│   ├── SlackUser.swift
│   ├── SlackWebClient.swift
│   ├── Socket.swift
│   ├── TLSSocket.swift
│   ├── TerminalCanvas.swift
│   ├── TerminalDevice.swift
│   ├── TextLayout.swift
│   ├── URLSession.swift
│   ├── UserInputView.swift
│   ├── Utils.swift
│   ├── WebSocketClient.swift
│   └── main.swift
├── slash.rb
├── slash.sublime-project
└── slash.xcodeproj/
    ├── project.pbxproj
    ├── project.xcworkspace/
    │   └── contents.xcworkspacedata
    └── xcshareddata/
        └── xcschemes/
            └── slash.xcscheme

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
## Build generated
build/
DerivedData/

## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata/

## Other
*.moved-aside
*.xcuserstate

## Obj-C/Swift specific
*.hmap
*.ipa
*.dSYM.zip
*.dSYM

## Playgrounds
timeline.xctimeline
playground.xcworkspace

# Swift Package Manager
#
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
# Packages/
.build/


================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright {yyyy} {name of copyright owner}

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: Package.swift
================================================
// swift-tools-version:4.2
import PackageDescription

let package = Package(
    name: "slash",
    products: [.executable(name: "slash", targets: ["slash"])],
    targets: [.target(name:  "slash", path: "Sources")]
)


================================================
FILE: README.md
================================================
<img src="GitHub/slash_logo_small.png" alt="logo" width="200px;"/>

Slack terminal client.

</br>

![screenshot](GitHub/scr.png)

## Getting started

To use `slash` install it via:

`brew install https://raw.githubusercontent.com/slash-hq/slash/master/slash.rb` 

and start it by running:

```
slash
```

Slash can be used with the [development token](https://api.slack.com/docs/oauth-test-tokens) too:

```
slash <token>
```

## Keys

```
Enter  : Send a message
Tab    : Switch channel
Up/Down: Scroll messages
Ctrl-C : Quit
```

## Commands

```
/openurl <number> : open url with <number>
```

<img src="GitHub/openurl_example.png" alt="logo" width="800px;"/>

## Retro mode

Thanks too [cool-retro-term](https://github.com/Swordfish90/cool-retro-term) project slash can run in retro mode

![screenshot](GitHub/scr_retro.png)

## Issues

Please make sure to read the Issue Reporting Checklist before opening an issue. Issues not conforming to the guidelines may be closed immediately.

## How to contribute?

1. Fork this repository and clone to your Mac.
1. Open `slash.xcodeproj` in Xcode
1. Build
1. Open `Terminal` and run `<DerivedData>/Build/Products/Debug/slash`
1. Make your changes, test and submit pull request!

## FAQ

1. Can I connect to multiple Slack teams?

  Yes, simply start multiple `slash` instances and login to a different team in each of them.

## License

Apache License, Version 2.0


================================================
FILE: Sources/Application.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

class Application {
    
    private let terminalDevice                  : TerminalDevice
    private let messagesListView                : MessagesListView
    private let userInputView                   : UserInputView
    private let channelsListView                : ChannelsListView
    private let webClient                       : SlackWebClient
    private let context                         : SlackContext
    private let rtmClient                       : SlackRealTimeClient
    
    private var messages                        = Array<MessagesListRow>()
    private var links                           = [String]()
    private var selectedChannel: String?        = nil
    private var replyIdCounter                  = 0
    private var unreadChannelsIds               = Set<String>()
    private let adapter                         = SlackAdapter()

    init(usingDevice device: TerminalDevice, authenticatedBy token: String) throws {
        
        self.terminalDevice = device
        
        self.messagesListView = MessagesListView(self.terminalDevice)
        self.channelsListView = ChannelsListView(self.terminalDevice)
        self.userInputView = UserInputView(self.terminalDevice)
        
        self.webClient = SlackWebClient(authenticatedBy: token)
        
        self.terminalDevice.flush(
            TerminalCanvas()
                .hideCursor()
                .color(R.color.connectingTextColor)
                .cursor(1, 1)
                .text(R.string.connecting).buffer)
        
        let team = try self.webClient.rtm()
        
        self.rtmClient = try SlackRealTimeClient(team.wssUrl)
        self.context = SlackContext(withTeam: team)
        
        if let defaultChannel = self.context.defaultChannel {
            self.selectedChannel = defaultChannel
            let defaultChannelName = self.context.name(forId: defaultChannel) ?? ""
            self.userInputView.placeholder = String(format: R.string.inputPlaceholder, defaultChannelName)
            self.userInputView.draw()
            self.reloadChannel(defaultChannel, clearChat: false)
        }
        
        DispatchQueue.global(qos: .background).async { [unowned self] in
            while true {
                do {
                    while true {
                        if let event = try self.rtmClient.waitForEvent() {
                            self.handleRealTimeSessionEvent(event)
                        }
                    }
                } catch {
                    self.appendRow(MessagesListRow(spans: [TextSpan(String(format: R.string.connectionError, "\(error)"))]))
                }
            }
        }
    }
    
    func handleRealTimeSessionEvent(_ event: SlackEvent) {
        
        switch event {
            
        case .hello:
            
            self.appendRow(MessagesListRow(spans: [TextSpan(String(format: R.string.hello, self.context.teamName), withColor: R.color.helloTextColor)]))
            
        case .reply(let replyId, let ts):
            
            if let index = self.messages.index(where: { $0.id == "pending\(replyId)" }) {
                let old = self.messages.remove(at: index)
                var newSpans = [TextSpan]()
                newSpans.append(TextSpan(adapter.formatSlackTimestamp("\(Date().timeIntervalSince1970)") + " ", withColor: R.color.messageTimeTextColor))
                newSpans.append(contentsOf: old.spans)
                self.messages.insert(MessagesListRow(channel: old.channel, id: ts, spans: newSpans), at: index)
                self.messagesListView.draw(self.messages)
            }
            
        case .message(let message):
            
            if let selectedChannel = self.selectedChannel {
                if message.channel == selectedChannel {
                    self.appendRow(self.messageListRowFor(message: message))
                } else {
                    self.unreadChannelsIds.insert(message.channel)
                    self.channelsListView.draw(self.context, selectionId: self.selectedChannel, unreadIds: self.unreadChannelsIds)
                }
            }
            
        case .messageChanged(let message):
            
            if let index = self.messages.index(where: { $0.id == message.ts && $0.channel == message.channel }) {
                self.messages[index] = self.messageListRowFor(message: message)
                self.messagesListView.draw(messages)
            }
            
        case .messageDeleted(let ts, let channel):
            
            if let index = self.messages.index(where: { $0.id == ts && $0.channel == channel }) {
                self.messages.remove(at: index)
                self.messagesListView.draw(self.messages)
            }
            
        case .presenceChange(let user, let presence):

            if let index = self.context.users.index(where: { $0.id == user }) {
                let old = self.context.users.remove(at: index)
                self.context.users.insert(SlackUser(id: old.id, name: old.name, color: old.color, presence: presence), at: index)
                self.channelsListView.draw(self.context, selectionId: self.selectedChannel, unreadIds: self.unreadChannelsIds)
            }
            
        case .teamRename(let newName):
            
            self.context.teamName = newName
            
            self.channelsListView.draw(self.context, selectionId: self.selectedChannel, unreadIds: self.unreadChannelsIds)
            
        case .desktopNotification(let title, let message):

            #if os(Linux)
                // Linux notifications not implemented yet
            #else
                Process.launchedProcess(launchPath: "/usr/bin/osascript", arguments: ["-e", "display notification \"\(message)\" with title \"slash: \(title)\""])
            #endif
            return

        case .messageReactionAdded(let reaction, let channel, let ts):

            if channel == self.selectedChannel {
                
                self.messagesListView.draw(self.messages)
            }

        case .unknown(let message):
            
            return self.appendRow(MessagesListRow(spans: ["?", " : ", TextSpan(message)]))
            
        default:
            
            break
        }
    }
    
    func notifyTerminalSizeHasChanged() {
        self.messagesListView.draw(self.messages)
        self.channelsListView.draw(self.context, selectionId: self.selectedChannel)
        self.userInputView.draw()
    }
    
    private func messageListRowFor(message: SlackMessage) -> MessagesListRow {
        let spans = self.adapter.textSpansFor(message: message, withContext: self.context, andLinks: &self.links)
        return MessagesListRow(channel: message.channel, id: message.ts, spans: spans)
    }
    
    func appendRow(_ row: MessagesListRow) {
        self.messages.insert(row, at: 0)
        self.messagesListView.draw(messages)
    }

    func reloadChannel(_ channelId: String, clearChat: Bool = true) {
        let loadingRow = MessagesListRow(spans: [TextSpan(R.string.loading, withColor: R.color.loadingTextColor)])
        if clearChat {
            self.messagesListView.draw([loadingRow])
        } else {
            self.messages.append(loadingRow)
            self.messagesListView.draw(self.messages)
        }
        DispatchQueue.global(qos: .background).async { [unowned self] in
            do {
                let rows = try self.webClient.history(for: channelId).map {
                    self.messageListRowFor(message: $0)
                }
                //TODO notify about the results in a common queue for all the background tasks.
                self.messages.removeAll(keepingCapacity: true)
                self.messages.append(contentsOf: rows)
                self.messagesListView.draw(self.messages)
                self.channelsListView.draw(self.context, selectionId: self.selectedChannel, unreadIds: self.unreadChannelsIds)
                self.userInputView.draw()
            } catch {
                //TODO handle error case.
            }
        }
    }
    
    func run() {
        
        self.messagesListView.draw(self.messages)
        
        while true {
            
            let key = self.terminalDevice.key()
        
            switch key {
                
            case .ctrlC:
                
                try? self.terminalDevice.reset()
                exit(1)
                
            case .enter:
                
                guard !self.userInputView.input.isEmpty, let targetChannel = self.selectedChannel, let me = self.context.me else {
                    continue
                }

                let message = self.userInputView.input
                
                if !self.executeLocalCommand(message) {
                    try? self.rtmClient.send(targetChannel, message: message, replyId: replyIdCounter)
                    
                    let pendingMessage = MessagesListRow(channel: targetChannel, id: "pending\(replyIdCounter)", spans: [
                        TextSpan(me.name, withColor: Utils.xterm256Color(forUser: me)),
                        TextSpan(": ", withColor: R.color.messagePrefixTextColor),
                        TextSpan(message, withColor: R.color.messageTextColor)], pending: true)
                    
                    self.messages.insert(pendingMessage, at: 0)
                    
                    self.replyIdCounter = self.replyIdCounter + 1
                    
                    self.messagesListView.draw(self.messages)
                }
                                
                self.userInputView.input = ""
                self.userInputView.cursor = 0
                self.userInputView.draw()

            case .backspace:
                
                if self.userInputView.input.isEmpty || self.userInputView.cursor <= 0 {
                    continue
                }
                self.userInputView.input.remove(at:
                    userInputView.input.index(self.userInputView.input.startIndex, offsetBy: self.userInputView.cursor-1))
                self.userInputView.cursor = max(0, self.userInputView.cursor - 1)
                self.userInputView.draw()
                
            case .arrowLeft:
                
                self.userInputView.cursor = max(0, userInputView.cursor - 1)
                self.userInputView.draw()
                
            case .arrowRight:
                
                self.userInputView.cursor = min(userInputView.input.count, userInputView.cursor + 1)
                self.userInputView.draw()
                
            case .arrowUp:
                
                self.messagesListView.scroll = self.messagesListView.scroll + 1
                self.messagesListView.draw(self.messages)
                
            case .arrowDown:
                
                guard self.messagesListView.scroll > 0 else {
                    break
                }
                
                self.messagesListView.scroll = self.messagesListView.scroll - 1
                self.messagesListView.draw(self.messages)
    
            case .tab(let withShift):
            
                guard let suggestion = self.context.suggestRecipient(for: self.selectedChannel, unreadIds: self.unreadChannelsIds, backwardSearch: withShift) else {
                    continue
                }
                
                self.userInputView.input = ""
                self.userInputView.cursor = 0
                self.messagesListView.scroll = 0
                
                self.unreadChannelsIds.remove(suggestion.id)
                
                self.selectedChannel = suggestion.id
                self.userInputView.placeholder = String(format: R.string.inputPlaceholder, suggestion.name)
                self.channelsListView.draw(self.context, selectionId: suggestion.id, unreadIds: self.unreadChannelsIds)
            
                self.reloadChannel(suggestion.id)
                self.links.removeAll()
                self.userInputView.draw()
                
            case .other(let character):
                
                self.userInputView.input.insert(character,
                    at: self.userInputView.input.index(self.userInputView.input.startIndex,
                       offsetBy: self.userInputView.cursor))
                
                self.userInputView.cursor = userInputView.cursor + 1
                self.userInputView.draw()

            default: break
                
            }
        }
    }
    
    /// Execute a local "slash" command.
    ///
    /// The currently supported list of local commands are;
    ///
    /// - /openurl {space separated list of numbers}: opens numbered link in default browser
    ///
    func executeLocalCommand(_ command: String) -> Bool {
        if (command.hasPrefix("/openurl")) {
            let pieces = command.components(separatedBy: [",", " "])
            let linkNumbers = pieces.compactMap { Int($0) }
            for linkNumber in linkNumbers {
                let url = self.links[linkNumber - 1]
                Utils.shell("open", url)
            }
            return true
        }
        
        return false
    }
}


================================================
FILE: Sources/ChannelsListView.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//


import Foundation

struct ChannelListRow {
    
    let id: String
    let name: String
}

class ChannelsListView {
    
    private let canvas = TerminalCanvas()
    
    private let terminalDevice: TerminalDevice
    
    init(_ device: TerminalDevice) {
        self.terminalDevice = device
    }

    func drawRow(_ text: String, row: Int, highlight: Bool = false, blink: Bool = false) {
        
        let availableWidth = R.dimen.channelsListWidth
        
        let paddedName = text.count > availableWidth ? String(text[..<text.index(text.startIndex, offsetBy: availableWidth)]) :
            text.padding(toLength: availableWidth, withPad: " ", startingAt: 0)
        
        self.canvas
            .cursor(1, row)
            .blink(blink)
            .background(highlight ? R.color.channelListBgColorSelected : R.color.channelListBgColor)
            .text(paddedName)
    }
    
    func draw(_ context: SlackContext, selectionId: String? = nil, unreadIds: Set<String> = []) {
        
        let size = self.terminalDevice.size
        
        let avaibleHeight = size.height
        
        guard size.width > 0 && avaibleHeight > 0 else { return }
        
        var offset = 1
        
        self.canvas
            .clear()
            .hideCursor()
        
        // Draw team name.
        
        self.canvas
            .color(R.color.teamNameTextColor)
            .background(R.color.teamNameBackgroundColor)
            .cursor(1, 1)
            .text(context.teamName.padding(toLength: R.dimen.channelsListWidth, withPad: " ", startingAt: 0))
        
        offset = offset + 1
        
        // Draw channels.
        
        self.canvas.color(R.color.channelNameTextColor);
        
        for channel in context.channels {
            if (!channel.isMember) {
                continue
            }
        
            self.drawRow("#" + channel.name, row: offset, highlight: channel.id == selectionId, blink: unreadIds.contains(channel.id))
            
            offset = offset + 1
            if offset > avaibleHeight {
                break
            }
        }
        
        // Draw groups.
        
        self.canvas.color(R.color.groupNameTextColor);
        
        if offset < avaibleHeight {
            for group in context.groups {
                
                self.drawRow("#" + group.name, row: offset, highlight: group.id == selectionId, blink: unreadIds.contains(group.id))
                
                offset = offset + 1
                if offset > avaibleHeight {
                    break
                }
            }
        }
        
        // Draw members.
        
        if offset < avaibleHeight {
            for im in context.ims {
                let slackUser = context.user(forId: im.user) ?? SlackUser(id: "", name: "", color: "", presence: .away)
                if slackUser.presence == .active {
                    self.canvas.color(Utils.xterm256Color(forUser: slackUser))
                } else {
                    self.canvas.color(R.color.channelListTextColorAway)
                }
                self.drawRow("@" + (context.user(forId: im.user)?.name ?? ""), row: offset, highlight: im.id == selectionId, blink: unreadIds.contains(im.id))
                offset = offset + 1
                if offset > avaibleHeight {
                    break
                }
            }
        }
        
        self.canvas
            .color(R.color.channelNameTextColor)
            .background(R.color.channelListBgColor)
        
        while offset <= avaibleHeight {
            self.canvas
                .cursor(1, offset)
                .text(String(repeating: " ", count: R.dimen.channelsListWidth))
            offset = offset + 1
        }
        
        self.canvas.reset()
        
        terminalDevice.flush(self.canvas.buffer)
    }
}


================================================
FILE: Sources/CrashReporter.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation


struct CrashReporter {
    
    private static var terminalDevice: TerminalDevice? = nil
    
    static func watch(usingDevice device: TerminalDevice) {
        
        CrashReporter.terminalDevice = device
        
        NSSetUncaughtExceptionHandler { _ in
            CrashReporter.report()
        }
        
        signal(SIGABRT) { _ in
            CrashReporter.report()
        }
        
        signal(SIGILL) { _ in
            CrashReporter.report()
        }
        
        signal(SIGSEGV) { _ in
            CrashReporter.report()
        }
        
        signal(SIGFPE) { _ in
            CrashReporter.report()
        }
        
        signal(SIGBUS) { _ in
            CrashReporter.report()
        }
        
        signal(SIGPIPE) { _ in
            CrashReporter.report()
        }
    }
    
    private static func report() {
        
        try? CrashReporter.terminalDevice?.reset()
        
        let stacktrace = Thread.callStackSymbols.joined(separator: "\n")
        
        let title = "Crash detected".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        
        let body =  ("I found the following crash in the app:\n```" + stacktrace + "```")
            .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        
        CrashReporter.terminalDevice?.flush(TerminalCanvas()
            .reset()
            .clear()
            .text("Oooops.... we are really sorry but slash has crashed ☠️ :\n\nSTACKTRACE:\n\n")
            .text(stacktrace)
            .text("\n\n")
            .text("Please copy this very long link to the browser, to help us with fixing the crash 🙇 \n\nhttps://github.com/slash-hq/slash/issues/new?title=\(title)&body=\(body))\n\n")
            .text("Thank you, \nslash Team\n\n")
        .buffer)
        
        exit(1)
    }
}


================================================
FILE: Sources/MessagesListView.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

struct MessagesListRow {
    
    let channel: String?
    let id: String?
    let spans: [TextSpan]
    let pending: Bool
    
    init(channel: String? = nil, id: String? = nil, spans: [TextSpan], pending: Bool = false) {
        self.channel = channel
        self.id = id
        self.spans = spans
        self.pending = pending
    }
}

class MessagesListView {
    
    private let canvas = TerminalCanvas()
    private let textLayout = TextLayout()
    
    private let terminalDevice: TerminalDevice
    
    init(_ device: TerminalDevice) {
        self.terminalDevice = device
    }
    
    var scroll = 0
    
    func draw(_ rows: Array<MessagesListRow>) {
        
        let size = self.terminalDevice.size
        let bottomPadding = 2
        
        guard size.width > 0 && size.height > bottomPadding else {
            return
        }
        
        let avaibleHeight = size.height - bottomPadding
        
        self.canvas
            .clear()
            .hideCursor()
        
        let column = R.dimen.channelsListWidth + 2
        
        var rayOffset = avaibleHeight
        var scrollOffset = self.scroll
        
        // Draw from the bottom to the top.
        
        lines: for row in rows {
            
            let lines = self.textLayout.layout(row.spans, alignToWidth: size.width - column - 1)
            
            for line in lines.reversed() {
                
                if scrollOffset > 0 {
                    scrollOffset = scrollOffset - 1
                    continue
                }
                
                self.canvas
                    .cursor(column-1, rayOffset)
                    .background(R.color.messagesListBgColor)
                    .text(" ")
                    .buffer.append(contentsOf: line)
                
                rayOffset = rayOffset - 1
                if rayOffset < 1 {
                    break lines
                }
            }
        }
        
        // Clear the top if needed.
    
        if rayOffset > 0 {
            for i in 1...rayOffset {
                self.canvas
                    .cursor(R.dimen.channelsListWidth + 1, i)
                    .color(R.color.defaulTextColor)
                    .background(R.color.messagesListBgColor)
                    .text(String(repeating: " ", count: size.width - R.dimen.channelsListWidth))
            }
        }
        
        self.canvas.reset()
        
        terminalDevice.flush(self.canvas.buffer)
    }
}


================================================
FILE: Sources/R.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

class R {
    
    class string {
        
        // Cool emojis: 🚫❕❗️📢📣🚀🐌🌊💦🌪❄️💥💡🗑⏱🔪💉🌡🚿🎈🎁🏷🔖🔐🔒🔓🔏⚠️💩
    
        static let inputPlaceholder = "Message #%@..."
        
        static let unknownMessageAuthor = "(unknown)"
        
        static let directMessageAuthor = "private"
        
        static let hello = "Connected to %@ team."
        
        static let unknownMessageChannel = "??"
        
        static let connecting = "Connecting 💤 ..."
        
        static let loading = "Loading 💤 ..."
        
        static let connectionError = "⚠️  Connection error occured (%@)"
        
        static let me = "me"
        
        static let authHelpMessage = "🔒  Visit ( %@ ) to login using OAuth2..."
        
        static let authConfirmation =
            "<html><body><center>" +
                "<br><br><img width=\"200\" src=\"https://github.com/slash-hq/slash/blob/master/GitHub/slash_logo_small.png?raw=true\" /><br>" +
                "<h4><span style=\"font-family: Verdana; color: #CCC;\">You can close this window now and continue in the terminal.</span></h4><br>" +
                "<img width=\"600\"src=\"https://github.com/slash-hq/slash/blob/master/GitHub/scr.png?raw=true\"/>" +
            "</center></body></html>"
    }
    
    class color {
        
        // XTERM-256 palette: https://jonasjacek.github.io/colors/
        
        static let defaultBgColor = -1
        
        static let defaulTextColor = -1
        
        static let connectingTextColor = 255
        
        static let helloTextColor = 255
        
        static let commandTextColor = 201
        
        static let userInputTextColor = 231
        
        static let userInputBackgorundColor = 16
        
        static let userInputPlaceholderTextColor = 242
        
        static let userInputSeparatorTextColor = 255
        
        static let messageAuthorTextColor = 158
        
        static let messagePrefixTextColor = 104
        
        static let messageTextColor = 252
        
        static let messageTimeTextColor = 24
        
        static let messageHighlightedBgColor = 154
        
        static let teamNameTextColor = 15
        
        static let teamNameBackgroundColor = 234
        
        static let channelNameTextColor = 38
        
        static let groupNameTextColor = 190
        
        static let directMessageTextColor = 240
        
        static let channelListTextColorAway = 239
        
        static let channelListBgColor = 232
        
        static let channelListBgColorSelected = 15
        
        static let channelListBgColorNotRead = 148
        
        static let messagesListBgColor = 0
        
        static let loadingTextColor = 11
        
        static let linkTextColor = 11
        
        static let mentionTextColor = 37
        
        static let reactionTextColor = 15
    }
    
    class dimen {
        
        static let channelsListWidth = 17
    }
}


================================================
FILE: Sources/Server.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

class Request {
    
    enum HttpVersion { case http10, http11 }
    
    var httpVersion = HttpVersion.http10
    
    var method = ""
    
    var path = ""
    
    var query = [(String, String)]()
    
    var headers = [(String, String)]()
    
    var body = [UInt8]()
    
    var contentLength = 0
    
    func hasToken(_ token: String, forHeader headerName: String) -> Bool {
        guard let (_, value) = headers.filter({ $0.0 == headerName }).first else {
            return false
        }
        return value
            .components(separatedBy: ",")
            .filter({ $0.trimmingCharacters(in: .whitespaces).lowercased() == token })
            .count > 0
    }
}

class Response {
    
    init() { }
    
    init(_ status: Status = Status.ok) {
        self.status = status.rawValue
    }
    
    init(_ status: Int = Status.ok.rawValue) {
        self.status = status
    }
    
    init(_ body: Array<UInt8>) {
        self.body.append(contentsOf: body)
    }
    
    init(_ body: ArraySlice<UInt8>) {
        self.body.append(contentsOf: body)
    }
    
    var status = Status.ok.rawValue
    
    var headers = [(String, String)]()
    
    var body = [UInt8]()
    
    var processingSuccesor: IncomingDataProcessor? = nil
}

class TextResponse: Response {
    
    init(_ status: Int = Status.ok.rawValue, _ text: String) {
        super.init(status)
        self.headers.append(("Content-Type", "text/plain"))
        self.body = [UInt8](text.utf8)
    }
}

class HtmlResponse: Response {
    
    init(_ status: Int = Status.ok.rawValue, _ text: String) {
        super.init(status)
        self.headers.append(("Content-Type", "text/html"))
        self.body = [UInt8](text.utf8)
    }
}

enum Status: Int {
    case `continue` = 100
    case switchingProtocols = 101
    case ok = 200
    case created = 201
    case accepted = 202
    case noContent = 204
    case resetContent = 205
    case partialContent = 206
    case movedPerm = 301
    case notModified = 304
    case badRequest = 400
    case unauthorized = 401
    case forbidden = 403
    case notFound = 404
}

extension UInt8 {
    
    static var
    lf: UInt8 = 10,
    cr: UInt8 = 13,
    space: UInt8 = 32,
    colon: UInt8 = 58,
    ampersand: UInt8 = 38,
    lessThan: UInt8 = 60,
    greaterThan: UInt8 = 62,
    slash: UInt8 = 47,
    equal: UInt8 = 61,
    doubleQuotes: UInt8 = 34,
    openingParenthesis: UInt8 = 40,
    closingParenthesis: UInt8 = 41,
    comma: UInt8 = 44
}

enum AsyncError: Error {
    case parse(String)
    case async(String)
    case socketCreation(String)
    case setReUseAddr(String)
    case setNoSigPipeFailed(String)
    case setNonBlockFailed(String)
    case setReuseAddrFailed(String)
    case bindFailed(String)
    case listenFailed(String)
    case writeFailed(String)
    case getPeerNameFailed(String)
    case convertingPeerNameFailed
    case getNameInfoFailed(String)
    case acceptFailed(String)
    case readFailed(String)
    case httpError(String)
}

protocol TcpServer {
    
    init(_ port: in_port_t) throws
    
    func wait(_ callback: ((TcpServerEvent) -> Void)) throws
    
    func write(_ socket: Int32, _ data: Array<UInt8>, _ done: @escaping (() -> TcpWriteDoneAction)) throws
    
    func finish(_ socket: Int32)
}

enum TcpWriteDoneAction {
    
    case `continue`
    
    case terminate
}

enum TcpServerEvent {
    
    case connect(String, Int32)
    
    case disconnect(String, Int32)
    
    case data(String, Int32, ArraySlice<UInt8>)
}

class HttpIncomingDataPorcessor: Hashable, IncomingDataProcessor {
    
    private enum State {
        case waitingForHeaders
        case waitingForBody
    }
    
    private var state = State.waitingForHeaders
    
    private let socket: Int32
    private var buffer = Array<UInt8>()
    private var request = Request()
    private let callback: ((Request) throws -> Void)
    
    init(_ socket: Int32, _ closure: @escaping ((Request) throws -> Void)) {
        self.socket = socket
        self.callback = closure
    }
    
    static func == (lhs: HttpIncomingDataPorcessor, rhs: HttpIncomingDataPorcessor) -> Bool {
        return lhs.socket == rhs.socket
    }
    
    var hashValue: Int { return Int(self.socket) }
    
    func process(_ chunk: ArraySlice<UInt8>) throws {
        
        switch self.state {
            
        case .waitingForHeaders:
            
            guard self.buffer.count + chunk.count < 4096 else {
                throw AsyncError.parse("Headers size exceeds that limit.")
            }
            
            var iterator = chunk.makeIterator()
            
            while let byte = iterator.next() {
                if byte != UInt8.cr {
                    buffer.append(byte)
                }
                if buffer.count >= 2 && buffer[buffer.count-1] == UInt8.lf && buffer[buffer.count-2] == UInt8.lf {
                    self.buffer.removeLast(2)
                    self.request = try self.consumeHeader(buffer)
                    self.buffer.removeAll(keepingCapacity: true)
                    let left = [UInt8](iterator)
                    self.state = .waitingForBody
                    try self.process(left[0..<left.count])
                    break
                }
            }
            
        case .waitingForBody:
            
            guard self.request.body.count + chunk.count <= request.contentLength else {
                throw AsyncError.parse("Peer sent more data then required ('Content-Length' = \(request.contentLength).")
            }
            
            request.body.append(contentsOf: chunk)
            
            if request.body.count == request.contentLength {
                self.state = .waitingForHeaders
                try self.callback(request)
            }
        }
    }
    
    private func consumeHeader(_ data: [UInt8]) throws -> Request {
        
        let lines = data.split(separator: UInt8.lf)
        
        guard let requestLine = lines.first else {
            throw AsyncError.httpError("No status line.")
        }
        
        let requestLineTokens = requestLine.split(separator: UInt8.space)
        
        guard requestLineTokens.count >= 3 else {
            throw AsyncError.httpError("Invalid status line.")
        }
        
        let request = Request()
        
        if requestLineTokens[2] == [0x48, 0x54,  0x54,  0x50, 0x2f, 0x31, 0x2e, 0x30] {
            request.httpVersion = .http10
        } else if requestLineTokens[2] == [0x48, 0x54,  0x54,  0x50, 0x2f, 0x31, 0x2e, 0x31] {
            request.httpVersion = .http11
        } else {
            throw AsyncError.parse("Invalid http version: \(requestLineTokens[2])")
        }
        
        request.headers = lines
            .dropFirst()
            .map { line in
                let headerTokens = line.split(separator: UInt8.colon, maxSplits: 1)
                if let name = headerTokens.first, let value = headerTokens.last {
                    if let nameString = String(bytes: name, encoding: .ascii),
                        let valueString = String(bytes: value, encoding: .ascii) {
                        return (nameString.lowercased(), valueString.trimmingCharacters(in: .whitespaces))
                    }
                }
                return ("", "")
        }
        
        if let (_, value) = request.headers
            .filter({ $0.0 == "content-length" })
            .first {
            guard let contentLength = Int(value) else {
                throw AsyncError.parse("Invalid 'Content-Length' header value \(value).")
            }
            request.contentLength = contentLength
        }
        
        guard let method = String(bytes: requestLineTokens[0], encoding: .ascii) else {
            throw AsyncError.parse("Invalid 'method' value \(requestLineTokens[0]).")
        }
        
        request.method = method
        
        guard let path = String(bytes: requestLineTokens[1], encoding: .ascii) else {
            throw AsyncError.parse("Invalid 'path' value \(requestLineTokens[1]).")
        }
        
        let queryComponents = path.components(separatedBy: "?")
        
        if queryComponents.count > 1, let first = queryComponents.first, let last = queryComponents.last {
            request.path = first
            request.query = last
                .components(separatedBy: "&")
                .reduce([(String, String)]()) { (c, s) -> [(String, String)] in
                    let tokens = s.components(separatedBy: "=")
                    if let name = tokens.first, let value = tokens.last {
                        if let nameDecoded = name.removingPercentEncoding, let valueDecoded = value.removingPercentEncoding {
                            return c + [(nameDecoded, tokens.count > 1 ? valueDecoded : "")]
                        }
                    }
                    return c
            }
        } else {
            request.path = path
        }
        
        return request
    }
}

class Server {
    
    private var processors = [Int32 : IncomingDataProcessor]()
    
    private let server: TcpServer
    
    init(_ port: in_port_t = 8080) throws {
        #if os(Linux)
            self.server = try LinuxAsyncServer(port)
        #else
            self.server = try MacOSAsyncTCPServer(port)
        #endif
    }
    
    func serve(_ callback: @escaping ((request: Request, responder: ((Response) -> Void))) -> Void) throws {
        
        try self.server.wait { event in
            
            switch event {
                
            case .connect(_, let socket):
                
                self.processors[socket] = HttpIncomingDataPorcessor(socket) { request in
                    callback((request, { response in
                        let keepIOSession = self.supportsKeepAlive(request.headers) || request.httpVersion == .http11
                        var data = [UInt8]()
                        data.reserveCapacity(1024)
                        data.append(contentsOf: [UInt8]("HTTP/\(request.httpVersion == .http10 ? "1.0" : "1.1") \(response.status) OK\r\n".utf8))
                        for (name, value) in response.headers {
                            data.append(contentsOf: [UInt8]("\(name): \(value)\r\n".utf8))
                        }
                        if (keepIOSession) {
                            data.append(contentsOf: [UInt8]("Connection: keep-alive\r\n".utf8))
                        }
                        data.append(contentsOf: [UInt8]("Content-Length: \(response.body.count)\r\n".utf8))
                        data.append(contentsOf: [13, 10])
                        data.append(contentsOf: response.body)
                        do {
                            try self.server.write(socket, data) {
                                if let sucessor = response.processingSuccesor {
                                    self.processors[socket] = sucessor
                                    return .continue
                                }
                                return keepIOSession ? .continue : .terminate
                            }
                        } catch {
                            self.processors.removeValue(forKey: socket)
                        }
                    }))
                }
                
            case .disconnect(_, let socket):
                
                self.processors.removeValue(forKey: socket)
                
            case .data(_, let socket, let chunk):
                
                do {
                    try self.processors[socket]?.process(chunk)
                } catch {
                    self.processors.removeValue(forKey: socket)
                    self.server.finish(socket)
                }
            }
        }
    }
    
    private func supportsKeepAlive(_ headers: Array<(String, String)>) -> Bool {
        if let (_, value) = headers.filter({ $0.0 == "connection" }).first {
            return "keep-alive" == value.trimmingCharacters(in: CharacterSet.whitespaces)
        }
        return false
    }
    
    private func closeConnection(_ headers: Array<(String, String)>) -> Bool {
        if let (_, value) = headers.filter({ $0.0 == "connection" }).first {
            return "close" == value.trimmingCharacters(in: CharacterSet.whitespaces)
        }
        return false
    }
}

protocol IncomingDataProcessor {
    
    func process(_ chunk: ArraySlice<UInt8>) throws
}

extension Process {
    
    static var pid: Int {
        return Int(getpid())
    }
    
    static var tid: UInt64 {
        #if os(Linux)
            return UInt64(pthread_self())
        #else
            var tid: __uint64_t = 0
            pthread_threadid_np(nil, &tid);
            return UInt64(tid)
        #endif
    }
    
    static var error: String {
        return String(cString: UnsafePointer(strerror(errno)))
    }
}

class MacOSAsyncTCPServer: TcpServer {
    
    private var backlog = Dictionary<Int32, Array<(chunk: [UInt8], done: (() -> TcpWriteDoneAction))>>()
    private var peers = Set<Int32>()
    
    private let kernelQueue: KernelQueue
    private let server: UInt
    
    required init(_ port: in_port_t = 8080) throws {
        
        self.kernelQueue = try KernelQueue()
        
        self.server = UInt(try MacOSAsyncTCPServer.nonBlockingSocketForListenening(port))
        
        self.kernelQueue.subscribe(server, .read)
    }
    
    func write(_ socket: Int32, _ data: Array<UInt8>, _ done: @escaping (() -> TcpWriteDoneAction)) throws {
        
        let result = Socket.write(socket, data, data.count)
        
        if result == -1 {
            defer { self.finish(socket) }
            throw AsyncError.writeFailed(Process.error)
        }
        
        if result == data.count {
            if done() == .terminate {
                self.finish(socket)
            }
            return
        }
        
        self.backlog[socket]?.append(([UInt8](data[result..<data.count]), done))
        self.kernelQueue.resume(UInt(socket), .write)
    }
    
    func wait(_ callback: ((TcpServerEvent) -> Void)) throws {
        try self.kernelQueue.wait { signal in
            switch signal.event {
            case .read:
                if signal.ident == self.server {
                    let client = try MacOSAsyncTCPServer.acceptAndConfigureClientSocket(Int32(signal.ident))
                    self.peers.insert(client)
                    self.backlog[Int32(client)] = []
                    kernelQueue.subscribe(UInt(client), .read)
                    kernelQueue.subscribe(UInt(client), .write)
                    kernelQueue.pause(UInt(client), .write)
                    callback(.connect("", Int32(client)))
                } else {
                    var chunk = [UInt8](repeating: 0, count: signal.data)
                    let result = Socket.read(Int32(signal.ident), &chunk, signal.data)
                    if result <= 0 {
                        finish(Int32(signal.ident))
                        callback(.disconnect("", Int32(signal.ident)))
                    } else {
                        callback(.data("", Int32(signal.ident), chunk[0..<result]))
                    }
                }
            case .write:
                while let backlogElement = self.backlog[Int32(signal.ident)]?.first {
                    var chunk = backlogElement.chunk
                    let result = Socket.write(Int32(signal.ident), chunk, min(chunk.count, signal.data))
                    if result == -1 {
                        finish(Int32(signal.ident))
                        callback(.disconnect("", Int32(signal.ident)))
                        return
                    }
                    if result < chunk.count {
                        let leftData = [UInt8](chunk[result..<chunk.count])
                        self.backlog[Int32(signal.ident)]?.remove(at: 0)
                        self.backlog[Int32(signal.ident)]?.insert((chunk: leftData, done: backlogElement.done), at: 0)
                        return
                    }
                    self.backlog[Int32(signal.ident)]?.removeFirst()
                    if backlogElement.done() == .terminate {
                        self.finish(Int32(signal.ident))
                        callback(.disconnect("", Int32(signal.ident)))
                        return
                    }
                }
                self.kernelQueue.pause(signal.ident, .write)
            case .error:
                if signal.ident == self.server {
                    throw AsyncError.async(Process.error)
                } else {
                    self.finish(Int32(signal.ident))
                    callback(.disconnect("", Int32(signal.ident)))
                }
            }
        }
    }
    
    deinit {
        closeAllOpenedSockets()
    }
    
    func finish(_ socket: Int32) {
        self.backlog[socket] = []
        self.peers.remove(socket)
        let _ = Socket.close(socket)
    }
    
    func closeAllOpenedSockets() {
        for client in self.peers {
            let _ = Socket.close(client)
        }
        self.peers.removeAll(keepingCapacity: true)
        let _ = Socket.close(Int32(server))
    }
    
    static func nonBlockingSocketForListenening(_ port: in_port_t = 8080) throws -> Int32 {
        
        let server = Darwin.socket(AF_INET, SOCK_STREAM, 0)
        
        guard server != -1 else {
            throw AsyncError.socketCreation(Process.error)
        }
        
        var value: Int32 = 1
        if Darwin.setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &value, socklen_t(MemoryLayout<Int32>.size)) == -1 {
            defer { let _ = Socket.close(server) }
            throw AsyncError.setReuseAddrFailed(Process.error)
        }
        
        try setSocketNonBlocking(server)
        try setSocketNoSigPipe(server)
        
        var addr = anyAddrForPort(port)
        
        if withUnsafePointer(to: &addr, { Darwin.bind(server, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in>.size)) }) == -1 {
            defer { let _ = Socket.close(server) }
            throw AsyncError.bindFailed(Process.error)
        }
        
        if Darwin.listen(server, SOMAXCONN) == -1 {
            defer { let _ = Socket.close(server) }
            throw AsyncError.listenFailed(Process.error)
        }
        
        return server
    }
    
    static func acceptAndConfigureClientSocket(_ socket: Int32) throws -> Int32 {
        
        guard case let client = Darwin.accept(socket, nil, nil), client != -1 else {
            throw AsyncError.acceptFailed(Process.error)
        }
        
        try self.setSocketNonBlocking(client)
        try self.setSocketNoSigPipe(client)
        
        return client
    }
    
    static func anyAddrForPort(_ port: in_port_t) -> sockaddr_in {
        var addr = sockaddr_in()
        addr.sin_len = __uint8_t(MemoryLayout<sockaddr_in>.size)
        addr.sin_family = sa_family_t(AF_INET)
        addr.sin_port = port.bigEndian
        addr.sin_addr = in_addr(s_addr: in_addr_t(0))
        addr.sin_zero = (0, 0, 0, 0, 0, 0, 0, 0)
        return addr
    }
    
    static func setSocketNonBlocking(_ socket: Int32) throws {
        if Darwin.fcntl(socket, F_SETFL, Darwin.fcntl(socket, F_GETFL, 0) | O_NONBLOCK) == -1 {
            throw AsyncError.setNonBlockFailed(Process.error)
        }
    }
    
    static func setSocketNoSigPipe(_ socket: Int32) throws {
        var value = 1
        if Darwin.setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &value, socklen_t(MemoryLayout<Int32>.size)) == -1 {
            throw AsyncError.setNoSigPipeFailed(Process.error)
        }
    }
}

class KernelQueue {
    
    private var events = Array<kevent>(repeating: kevent(), count: 256)
    private var changes = Array<kevent>()
    
    private let queue: Int32
    
    enum Subscription { case read, write }
    enum Event { case read, write, error }
    
    init() throws {
        guard case let queue = kqueue(), queue != -1 else {
            throw AsyncError.async(Process.error)
        }
        self.queue = queue
    }
    
    func subscribe(_ ident: UInt, _ event: Subscription) {
        switch event {
        case .read  : changes.append(self.event(UInt(ident), Int16(EVFILT_READ), UInt16(EV_ADD) | UInt16(EV_ENABLE)))
        case .write : changes.append(self.event(UInt(ident), Int16(EVFILT_WRITE), UInt16(EV_ADD) | UInt16(EV_ENABLE)))
        }
    }
    
    func unsubscribe(_ ident: UInt, _ event: Subscription) {
        switch event {
        case .read  : changes.append(self.event(UInt(ident), Int16(EVFILT_READ), UInt16(EV_DELETE)))
        case .write : changes.append(self.event(UInt(ident), Int16(EVFILT_WRITE), UInt16(EV_DELETE)))
        }
    }
    
    func pause(_ ident: UInt, _ event: Subscription) {
        switch event {
        case .read  : changes.append(self.event(UInt(ident), Int16(EVFILT_READ), UInt16(EV_DISABLE)))
        case .write : changes.append(self.event(UInt(ident), Int16(EVFILT_WRITE), UInt16(EV_DISABLE)))
        }
    }
    
    func resume(_ ident: UInt, _ event: Subscription) {
        switch event {
        case .read  : changes.append(self.event(UInt(ident), Int16(EVFILT_READ), UInt16(EV_ENABLE)))
        case .write : changes.append(self.event(UInt(ident), Int16(EVFILT_WRITE), UInt16(EV_ENABLE)))
        }
    }
    
    private func event(_ ident: UInt, _ filter: Int16, _ flags: UInt16) -> kevent {
        return kevent(ident: ident, filter: filter, flags: flags, fflags: 0, data: 0, udata: nil)
    }
    
    func wait(_ callback: (_ tuple: (event: Event, ident: UInt, data: Int)) throws -> (Void)) throws {
        
        if !changes.isEmpty {
            if kevent(self.queue, &changes, Int32(changes.count), nil, 0, nil) == -1 {
                throw AsyncError.async(Process.error)
            }
        }
        
        self.changes.removeAll(keepingCapacity: true)
        
        guard case let count = kevent(self.queue, nil, 0, &events, Int32(events.count), nil), count != -1 else {
            throw AsyncError.async(Process.error)
        }
        
        for event in events[0..<Int(count)] {
            
            if Int32(event.flags) & EV_EOF != 0 || Int32(event.flags) & EV_ERROR != 0 {
                try callback((.error, event.ident, 0))
                continue
            }
            if Int32(event.filter) == EVFILT_READ {
                try callback((.read, event.ident, event.data))
                continue
            }
            if Int32(event.filter) == EVFILT_WRITE {
                try callback((.write, event.ident, event.data))
                continue
            }
        }
    }
}




================================================
FILE: Sources/SlackAdapter.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//


import Foundation

class SlackAdapter {
    
    private let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        return formatter
    }()
    
    private let emojiDecoder = SlackEmojiDecoder()
    
    func formatSlackTimestamp(_ slackTs: String) -> String {
        if let timestamp = Double(slackTs) {
            let date = Date(timeIntervalSince1970: timestamp)
            return self.dateFormatter.string(from: date)
        } else {
            return slackTs
        }
    }
    
    func textSpansFor(message: SlackMessage, withContext context: SlackContext, andLinks links: inout [String]) -> [TextSpan] {
        
        let slackUser = context.user(forId: message.user) ?? SlackUser(id: "", name: "unknown", color: "", presence: .away)
        
        var spans = [TextSpan]()
        
        spans.append(TextSpan(self.formatSlackTimestamp(message.ts), withColor: R.color.messageTimeTextColor))
        spans.append(TextSpan(" \(slackUser.name)", withColor: Utils.xterm256Color(forUser: slackUser)))
        spans.append(TextSpan(": ", withColor: R.color.messagePrefixTextColor))
        spans.append(contentsOf: self.spansFor(message: message.text, withContext: context, andLinks: &links))
        
        if !message.reactions.isEmpty {
            let content = "\n      " + message.reactions.map({ emojiDecoder.decode( ":" + $0.name + ":" ) + reactionCounter(forCount: $0.count) } ).joined(separator: " ")
            
            spans.append(TextSpan(content, withColor: R.color.reactionTextColor, withBackground: R.color.defaultBgColor))
        }
        
        return spans
    }
    
    func reactionCounter(forCount count: Int) -> String {
        if count <= 1 {
            return ""
        }
        return String(String(describing: count).map({ c in //TODO - Do it better with 'U+2080 + x' formula.
            switch c {
            case "0": return "₀"
            case "1": return "₁"
            case "2": return "₂"
            case "3": return "₃"
            case "4": return "₄"
            case "5": return "₅"
            case "6": return "₆"
            case "7": return "₇"
            case "8": return "₈"
            case "9": return "₉"
            default : return " "
            }
        }))
    }
    
    func spansFor(message: String, withContext context: SlackContext, andLinks links: inout [String]) -> [TextSpan] {
        
        var spans = [TextSpan]()
        
        for token in self.lex(for: message) {
            switch token {
            case .plain(let text):
                let presentableText = self.emojiDecoder.decode(self.decodeEscapedHTMLEntities(text))
                spans.append(TextSpan(presentableText, withColor: R.color.messageTextColor))
            case .escaped(let encodedText):
                guard let first = encodedText.first else {
                    continue
                }
                switch first {
                    case "#":
                        fallthrough
                    case "@":
                        let idStartIndex = encodedText.index(encodedText.startIndex, offsetBy: 1)
                        if idStartIndex < encodedText.endIndex {
                            let id = encodedText[idStartIndex..<(encodedText.index(of: "|") ?? encodedText.endIndex)]
                            if let name = context.name(forId: String(id)) {
                                spans.append(TextSpan(name, withColor: R.color.mentionTextColor))
                            }
                        }
                    case "!":
                        let escapedTokens = encodedText.components(separatedBy: "|")
                        if let command = escapedTokens.first {
                            let commandName = escapedTokens.count > 1 ? escapedTokens[1] : command
                            spans.append(TextSpan(commandName, withColor: R.color.commandTextColor))
                        }
                    default /* link */:
                        let escapedTokens = encodedText.components(separatedBy: "|")
                        if let url = escapedTokens.first {
                            links.append(url)
                            if let name = escapedTokens.last, escapedTokens.count > 1 {
                                 spans.append(TextSpan(self.decodeEscapedHTMLEntities(name), withColor: R.color.linkTextColor))
                            } else {
                                 spans.append(TextSpan(url, withColor: R.color.linkTextColor))
                            }
                            spans.append(TextSpan("[" + String(links.count) + "]", withColor: R.color.messageTextColor))
                        }
                }
            }
        }
        return spans
    }
    
    enum Token { case plain(String), escaped(String) }
    
    private func lex(for message: String) -> [Token] {

        var tokens = [Token]()
        
        var buffer = [Character]()
        buffer.reserveCapacity(message.count)
        
        var plainFlag = true
        
        for (index, character) in message.enumerated() {
            switch character {
                case "<":
                    if !buffer.isEmpty {
                        tokens.append(.plain(String(buffer)))
                    }
                    buffer.removeAll(keepingCapacity: true)
                    plainFlag = false
                case ">":
                    if !buffer.isEmpty {
                        tokens.append(.escaped(String(buffer)))
                    }
                    buffer.removeAll(keepingCapacity: true)
                    plainFlag = true
                default:
                    buffer.append(character)
                    if index == message.count - 1 {
                        tokens.append(plainFlag ? .plain(String(buffer)) : .escaped(String(buffer)))
                    }
            }
        }
        
        return tokens
    }
    
    private func decodeEscapedHTMLEntities(_ text: String) -> String {
        return text
            .replacingOccurrences(of: "&amp;", with: "&")
            .replacingOccurrences(of: "&lt;", with: "<")
            .replacingOccurrences(of: "&gt;", with: ">")
    }
}


================================================
FILE: Sources/SlackChannel.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

struct SlackChannel {
    
    let id: String
    let name: String
    let members: [String]
    let topic: String
    let general: Bool
    let isMember: Bool
}


================================================
FILE: Sources/SlackContext.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation


class SlackContext {
    
    var teamName : String
    var selfId   : String
    
    var users    = [SlackUser]()
    var channels = [SlackChannel]()
    var groups   = [SlackGroup]()
    var ims      = [SlackIM]()
    
    init(withTeam team: SlackTeam) {
        self.teamName = team.name
        self.selfId = team.selfId
        self.users.append(contentsOf: team.users)
        self.channels.append(contentsOf: team.channels)
        self.groups.append(contentsOf: team.groups)
        self.ims.append(contentsOf: team.ims)
    }
    
    func suggestRecipient(for selection: String?, unreadIds: Set<String> = [], backwardSearch: Bool) -> (id: String, name: String)? {
        
        let channels = self.channels.filter({ $0.isMember }).map { ($0.id, $0.name) }
        let groups = self.groups.map { ($0.id, $0.name) }
        let ims = self.ims.map { im in
            (im.id, (self.users.filter({ $0.id == im.user }).first?.name) ?? "")
        }
        
        let candidates = (channels + groups + ims).filter { unreadIds.isEmpty ? true : (unreadIds.contains($0.0) || $0.0 == selection) }
        
        var suggestion: (id: String, name: String)? = nil
        
        if let current = candidates.index(where: { $0.0 == selection }) {
            if backwardSearch {
                let next = current - 1
                if next < 0 {
                    suggestion = candidates.last
                } else {
                    suggestion = candidates[next]
                }
            } else {
                let next = current + 1
                if next >= candidates.count {
                    suggestion = candidates.first
                } else {
                    suggestion = candidates[next]
                }
            }
        }
        
        return suggestion
    }
    
    func name(forId id: String) -> String? {
        
        var name = self.channels.filter({ $0.id == id }).first?.name
        
        if name == nil {
            name = self.groups.filter({ $0.id == id }).first?.name
        }
        
        if name == nil {
            if let im = self.ims.filter({ $0.id == id }).first {
                if let user = self.users.filter({ $0.id == im.user }).first {
                    name = user.name
                }
            }
        }
        
        if name == nil {
            if let user = self.users.filter({ $0.id == id }).first {
                return user.name
            }
        }
        
        return name
    }
    
    func user(forId id: String) -> SlackUser? {
        return self.users.filter({ $0.id == id }).first
    }
    
    var me: SlackUser? {
        return self.users.filter({ $0.id == self.selfId }).first
    }
    
    var defaultChannel: String? {
        return self.channels.filter({ $0.general }).first?.id
    }

}


================================================
FILE: Sources/SlackEmojiDecoder.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

class SlackEmojiDecoder {
    
    func decode(_ text: String) -> String {
        //TODO - improve this by iterating only once over the text.
        return text
            .replacingOccurrences(of: ":skin-tone-1:", with: "🏻")
            .replacingOccurrences(of: ":skin-tone-2:", with: "🏻")
            .replacingOccurrences(of: ":skin-tone-3:", with: "🏼")
            .replacingOccurrences(of: ":skin-tone-4:", with: "🏽")
            .replacingOccurrences(of: ":skin-tone-5:", with: "🏾")
            .replacingOccurrences(of: ":skin-tone-6:", with: "🏿")
            .replacingOccurrences(of: ":100:", with: "💯")
            .replacingOccurrences(of: "<3", with: "❤️")
            .replacingOccurrences(of: "</3", with: "💔")
            .replacingOccurrences(of: ":)", with: "😄")
            .replacingOccurrences(of: "8)", with: "😎")
            .replacingOccurrences(of: ":1234:", with: "🔢")
            .replacingOccurrences(of: ":grinning:", with: "😀")
            .replacingOccurrences(of: ":grimacing:", with: "😬")
            .replacingOccurrences(of: ":grin:", with: "😁")
            .replacingOccurrences(of: ":joy:", with: "😂")
            .replacingOccurrences(of: ":smiley:", with: "😃")
            .replacingOccurrences(of: ":smile:", with: "😄")
            .replacingOccurrences(of: ":simple_smile:", with: "🙂")
            .replacingOccurrences(of: ":slightly_smiling_face:", with: "🙂")
            .replacingOccurrences(of: ":sweat_smile:", with: "😅")
            .replacingOccurrences(of: ":laughing:", with: "😆")
            .replacingOccurrences(of: ":innocent:", with: "😇")
            .replacingOccurrences(of: ":wink:", with: "😉")
            .replacingOccurrences(of: ":blush:", with: "😊")
            .replacingOccurrences(of: ":slightly_smiling:", with: "🙂")
            .replacingOccurrences(of: ":upside_down:", with: "🙃")
            .replacingOccurrences(of: ":relaxed:", with: "☺️")
            .replacingOccurrences(of: ":yum:", with: "😋")
            .replacingOccurrences(of: ":relieved:", with: "😌")
            .replacingOccurrences(of: ":heart_eyes:", with: "😍")
            .replacingOccurrences(of: ":kissing_heart:", with: "😘")
            .replacingOccurrences(of: ":kissing:", with: "😗")
            .replacingOccurrences(of: ":kissing_smiling_eyes:", with: "😙")
            .replacingOccurrences(of: ":kissing_closed_eyes:", with: "😚")
            .replacingOccurrences(of: ":stuck_out_tongue_winking_eye:", with: "😜")
            .replacingOccurrences(of: ":stuck_out_tongue_closed_eyes:", with: "😝")
            .replacingOccurrences(of: ":stuck_out_tongue:", with: "😛")
            .replacingOccurrences(of: ":money_mouth:", with: "🤑")
            .replacingOccurrences(of: ":nerd:", with: "🤓")
            .replacingOccurrences(of: ":sunglasses:", with: "😎")
            .replacingOccurrences(of: ":hugging:", with: "🤗")
            .replacingOccurrences(of: ":smirk:", with: "😏")
            .replacingOccurrences(of: ":no_mouth:", with: "😶")
            .replacingOccurrences(of: ":neutral_face:", with: "😐")
            .replacingOccurrences(of: ":expressionless:", with: "😑")
            .replacingOccurrences(of: ":unamused:", with: "😒")
            .replacingOccurrences(of: ":rolling_eyes:", with: "🙄")
            .replacingOccurrences(of: ":thinking:", with: "🤔")
            .replacingOccurrences(of: ":flushed:", with: "😳")
            .replacingOccurrences(of: ":disappointed:", with: "😞")
            .replacingOccurrences(of: ":worried:", with: "😟")
            .replacingOccurrences(of: ":angry:", with: "😠")
            .replacingOccurrences(of: ":rage:", with: "😡")
            .replacingOccurrences(of: ":pensive:", with: "😔")
            .replacingOccurrences(of: ":confused:", with: "😕")
            .replacingOccurrences(of: ":slightly_sad:", with: "🙁")
            .replacingOccurrences(of: ":white_frowning:", with: "☹")
            .replacingOccurrences(of: ":persevere:", with: "😣")
            .replacingOccurrences(of: ":confounded:", with: "😖")
            .replacingOccurrences(of: ":tired_face:", with: "😫")
            .replacingOccurrences(of: ":weary:", with: "😩")
            .replacingOccurrences(of: ":triumph:", with: "😤")
            .replacingOccurrences(of: ":open_mouth:", with: "😮")
            .replacingOccurrences(of: ":scream:", with: "😱")
            .replacingOccurrences(of: ":fearful:", with: "😨")
            .replacingOccurrences(of: ":cold_sweat:", with: "😰")
            .replacingOccurrences(of: ":hushed:", with: "😯")
            .replacingOccurrences(of: ":frowning:", with: "😦")
            .replacingOccurrences(of: ":anguished:", with: "😧")
            .replacingOccurrences(of: ":cry:", with: "😢")
            .replacingOccurrences(of: ":disappointed_relieved:", with: "😥")
            .replacingOccurrences(of: ":sleepy:", with: "😪")
            .replacingOccurrences(of: ":sweat:", with: "😓")
            .replacingOccurrences(of: ":sob:", with: "😭")
            .replacingOccurrences(of: ":dizzy_face:", with: "😵")
            .replacingOccurrences(of: ":astonished:", with: "😲")
            .replacingOccurrences(of: ":zipper_mouth:", with: "🤐")
            .replacingOccurrences(of: ":mask:", with: "😷")
            .replacingOccurrences(of: ":thermometer_face:", with: "🤒")
            .replacingOccurrences(of: ":bandage_face:", with: "🤕")
            .replacingOccurrences(of: ":sleeping:", with: "😴")
            .replacingOccurrences(of: ":zzz:", with: "💤")
            .replacingOccurrences(of: ":hankey:", with: "💩")
            .replacingOccurrences(of: ":smiling_imp:", with: "😈")
            .replacingOccurrences(of: ":imp:", with: "👿")
            .replacingOccurrences(of: ":japanese_ogre:", with: "👹")
            .replacingOccurrences(of: ":japanese_goblin:", with: "👺")
            .replacingOccurrences(of: ":skull:", with: "💀")
            .replacingOccurrences(of: ":ghost:", with: "👻")
            .replacingOccurrences(of: ":alien:", with: "👽")
            .replacingOccurrences(of: ":robot:", with: "🤖")
            .replacingOccurrences(of: ":smiley_cat:", with: "😺")
            .replacingOccurrences(of: ":smile_cat:", with: "😸")
            .replacingOccurrences(of: ":joy_cat:", with: "😹")
            .replacingOccurrences(of: ":heart_eyes_cat:", with: "😻")
            .replacingOccurrences(of: ":smirk_cat:", with: "😼")
            .replacingOccurrences(of: ":kissing_cat:", with: "😽")
            .replacingOccurrences(of: ":scream_cat:", with: "🙀")
            .replacingOccurrences(of: ":crying_cat_face:", with: "😿")
            .replacingOccurrences(of: ":pouting_cat:", with: "😾")
            .replacingOccurrences(of: ":raised_hands:", with: "🙌")
            .replacingOccurrences(of: ":clap:", with: "👏")
            .replacingOccurrences(of: ":wave:", with: "👋")
            .replacingOccurrences(of: ":+1:", with: "👍")
            .replacingOccurrences(of: ":-1:", with: "👎")
            .replacingOccurrences(of: ":facepunch:", with: "👊")
            .replacingOccurrences(of: ":fist:", with: "✊")
            .replacingOccurrences(of: ":v:", with: "✌️")
            .replacingOccurrences(of: ":ok_hand:", with: "👌")
            .replacingOccurrences(of: ":hand:", with: "✋")
            .replacingOccurrences(of: ":open_hands:", with: "👐")
            .replacingOccurrences(of: ":muscle:", with: "💪")
            .replacingOccurrences(of: ":pray:", with: "🙏")
            .replacingOccurrences(of: ":point_up:", with: "☝️")
            .replacingOccurrences(of: ":point_up_2:", with: "👆")
            .replacingOccurrences(of: ":point_down:", with: "👇")
            .replacingOccurrences(of: ":point_left:", with: "👈")
            .replacingOccurrences(of: ":point_right:", with: "👉")
            .replacingOccurrences(of: ":middle_finger:", with: "🖕")
            .replacingOccurrences(of: ":splayed_fingers:", with: "🖐")
            .replacingOccurrences(of: ":sign_of_horns:", with: "🤘")
            .replacingOccurrences(of: ":vulcan_salute:", with: "🖖")
            .replacingOccurrences(of: ":writing_hand:", with: "✍")
            .replacingOccurrences(of: ":nail_care:", with: "💅")
            .replacingOccurrences(of: ":lips:", with: "👄")
            .replacingOccurrences(of: ":tongue:", with: "👅")
            .replacingOccurrences(of: ":ear:", with: "👂")
            .replacingOccurrences(of: ":nose:", with: "👃")
            .replacingOccurrences(of: ":eye:", with: "👁")
            .replacingOccurrences(of: ":eyes:", with: "👀")
            .replacingOccurrences(of: ":bust_in_silhouette:", with: "👤")
            .replacingOccurrences(of: ":busts_in_silhouette:", with: "👥")
            .replacingOccurrences(of: ":speaking_head:", with: "🗣")
            .replacingOccurrences(of: ":baby:", with: "👶")
            .replacingOccurrences(of: ":boy:", with: "👦")
            .replacingOccurrences(of: ":girl:", with: "👧")
            .replacingOccurrences(of: ":man:", with: "👨")
            .replacingOccurrences(of: ":woman:", with: "👩")
            .replacingOccurrences(of: ":person_with_blond_hair:", with: "👱")
            .replacingOccurrences(of: ":older_man:", with: "👴")
            .replacingOccurrences(of: ":older_woman:", with: "👵")
            .replacingOccurrences(of: ":man_with_gua_pi_mao:", with: "👲")
            .replacingOccurrences(of: ":man_with_turban:", with: "👳")
            .replacingOccurrences(of: ":cop:", with: "👮")
            .replacingOccurrences(of: ":construction_worker:", with: "👷")
            .replacingOccurrences(of: ":guardsman:", with: "💂")
            .replacingOccurrences(of: ":sleuth:", with: "🕵")
            .replacingOccurrences(of: ":santa:", with: "🎅")
            .replacingOccurrences(of: ":angel:", with: "👼")
            .replacingOccurrences(of: ":princess:", with: "👸")
            .replacingOccurrences(of: ":bride_with_veil:", with: "👰")
            .replacingOccurrences(of: ":runner:", with: "🏃")
            .replacingOccurrences(of: ":walking:", with: "🚶")
            .replacingOccurrences(of: ":dancer:", with: "💃")
            .replacingOccurrences(of: ":dancers:", with: "👯")
            .replacingOccurrences(of: ":couple:", with: "👫")
            .replacingOccurrences(of: ":two_men_holding_hands:", with: "👬")
            .replacingOccurrences(of: ":two_women_holding_hands:", with: "👭")
            .replacingOccurrences(of: ":bow:", with: "🙇")
            .replacingOccurrences(of: ":information_desk_person:", with: "💁")
            .replacingOccurrences(of: ":no_good:", with: "🙅")
            .replacingOccurrences(of: ":ok_woman:", with: "🙆")
            .replacingOccurrences(of: ":raising_hand:", with: "🙋")
            .replacingOccurrences(of: ":person_with_pouting_face:", with: "🙎")
            .replacingOccurrences(of: ":person_frowning:", with: "🙍")
            .replacingOccurrences(of: ":haircut:", with: "💇")
            .replacingOccurrences(of: ":massage:", with: "💆")
            .replacingOccurrences(of: ":couple_with_heart:", with: "💑")
            .replacingOccurrences(of: ":female_couple_with_heart:", with: "👩‍❤️‍👩")
            .replacingOccurrences(of: ":male_couple_with_heart:", with: "👨‍❤️‍👨")
            .replacingOccurrences(of: ":couplekiss:", with: "💏")
            .replacingOccurrences(of: ":female_couplekiss:", with: "👩‍❤️‍💋‍👩")
            .replacingOccurrences(of: ":male_couplekiss:", with: "👨‍❤️‍💋‍👨")
            .replacingOccurrences(of: ":family:", with: "👪")
            .replacingOccurrences(of: ":family_man_woman_girl:", with: "👨‍👩‍👧")
            .replacingOccurrences(of: ":family_man_woman_girl_boy:", with: "👨‍👩‍👧‍👦")
            .replacingOccurrences(of: ":family_man_woman_boys:", with: "👨‍👩‍👦‍👦")
            .replacingOccurrences(of: ":family_man_woman_girls:", with: "👨‍👩‍👧‍👧")
            .replacingOccurrences(of: ":family_women_boy:", with: "👩‍👩‍👦")
            .replacingOccurrences(of: ":family_women_girl:", with: "👩‍👩‍👧")
            .replacingOccurrences(of: ":family_women_girl_boy:", with: "👩‍👩‍👧‍👦")
            .replacingOccurrences(of: ":family_women_boys:", with: "👩‍👩‍👦‍👦")
            .replacingOccurrences(of: ":family_women_girls:", with: "👩‍👩‍👧‍👧")
            .replacingOccurrences(of: ":family_men_boy:", with: "👨‍👨‍👦")
            .replacingOccurrences(of: ":family_men_girl:", with: "👨‍👨‍👧")
            .replacingOccurrences(of: ":family_men_girl_boy:", with: "👨‍👨‍👧‍👦")
            .replacingOccurrences(of: ":family_men_boys:", with: "👨‍👨‍👦‍👦")
            .replacingOccurrences(of: ":family_men_girls:", with: "👨‍👨‍👧‍👧")
            .replacingOccurrences(of: ":womans_clothes:", with: "👚")
            .replacingOccurrences(of: ":shirt:", with: "👕")
            .replacingOccurrences(of: ":jeans:", with: "👖")
            .replacingOccurrences(of: ":necktie:", with: "👔")
            .replacingOccurrences(of: ":dress:", with: "👗")
            .replacingOccurrences(of: ":bikini:", with: "👙")
            .replacingOccurrences(of: ":kimono:", with: "👘")
            .replacingOccurrences(of: ":lipstick:", with: "💄")
            .replacingOccurrences(of: ":kiss:", with: "💋")
            .replacingOccurrences(of: ":footprints:", with: "👣")
            .replacingOccurrences(of: ":high_heel:", with: "👠")
            .replacingOccurrences(of: ":sandal:", with: "👡")
            .replacingOccurrences(of: ":boot:", with: "👢")
            .replacingOccurrences(of: ":mans_shoe:", with: "👞")
            .replacingOccurrences(of: ":athletic_shoe:", with: "👟")
            .replacingOccurrences(of: ":womans_hat:", with: "👒")
            .replacingOccurrences(of: ":tophat:", with: "🎩")
            .replacingOccurrences(of: ":helmet:", with: "⛑")
            .replacingOccurrences(of: ":mortar_board:", with: "🎓")
            .replacingOccurrences(of: ":crown:", with: "👑")
            .replacingOccurrences(of: ":school_satchel:", with: "🎒")
            .replacingOccurrences(of: ":pouch:", with: "👝")
            .replacingOccurrences(of: ":purse:", with: "👛")
            .replacingOccurrences(of: ":handbag:", with: "👜")
            .replacingOccurrences(of: ":briefcase:", with: "💼")
            .replacingOccurrences(of: ":eyeglasses:", with: "👓")
            .replacingOccurrences(of: ":dark_sunglasses:", with: "🕶")
            .replacingOccurrences(of: ":ring:", with: "💍")
            .replacingOccurrences(of: ":closed_umbrella:", with: "🌂")
            .replacingOccurrences(of: ":dog:", with: "🐶")
            .replacingOccurrences(of: ":cat:", with: "🐱")
            .replacingOccurrences(of: ":mouse:", with: "🐭")
            .replacingOccurrences(of: ":hamster:", with: "🐹")
            .replacingOccurrences(of: ":rabbit:", with: "🐰")
            .replacingOccurrences(of: ":bear:", with: "🐻")
            .replacingOccurrences(of: ":panda_face:", with: "🐼")
            .replacingOccurrences(of: ":koala:", with: "🐨")
            .replacingOccurrences(of: ":tiger:", with: "🐯")
            .replacingOccurrences(of: ":lion_face:", with: "🦁")
            .replacingOccurrences(of: ":cow:", with: "🐮")
            .replacingOccurrences(of: ":pig:", with: "🐷")
            .replacingOccurrences(of: ":pig_nose:", with: "🐽")
            .replacingOccurrences(of: ":frog:", with: "🐸")
            .replacingOccurrences(of: ":octopus:", with: "🐙")
            .replacingOccurrences(of: ":monkey_face:", with: "🐵")
            .replacingOccurrences(of: ":see_no_evil:", with: "🙈")
            .replacingOccurrences(of: ":hear_no_evil:", with: "🙉")
            .replacingOccurrences(of: ":speak_no_evil:", with: "🙊")
            .replacingOccurrences(of: ":monkey:", with: "🐒")
            .replacingOccurrences(of: ":chicken:", with: "🐔")
            .replacingOccurrences(of: ":penguin:", with: "🐧")
            .replacingOccurrences(of: ":bird:", with: "🐦")
            .replacingOccurrences(of: ":baby_chick:", with: "🐤")
            .replacingOccurrences(of: ":hatching_chick:", with: "🐣")
            .replacingOccurrences(of: ":hatched_chick:", with: "🐥")
            .replacingOccurrences(of: ":wolf:", with: "🐺")
            .replacingOccurrences(of: ":boar:", with: "🐗")
            .replacingOccurrences(of: ":horse:", with: "🐴")
            .replacingOccurrences(of: ":unicorn_face:", with: "🦄")
            .replacingOccurrences(of: ":bee:", with: "🐝")
            .replacingOccurrences(of: ":bug:", with: "🐛")
            .replacingOccurrences(of: ":snail:", with: "🐌")
            .replacingOccurrences(of: ":beetle:", with: "🐞")
            .replacingOccurrences(of: ":ant:", with: "🐜")
            .replacingOccurrences(of: ":spider:", with: "🕷")
            .replacingOccurrences(of: ":scorpion:", with: "🦂")
            .replacingOccurrences(of: ":crab:", with: "🦀")
            .replacingOccurrences(of: ":snake:", with: "🐍")
            .replacingOccurrences(of: ":turtle:", with: "🐢")
            .replacingOccurrences(of: ":tropical_fish:", with: "🐠")
            .replacingOccurrences(of: ":fish:", with: "🐟")
            .replacingOccurrences(of: ":blowfish:", with: "🐡")
            .replacingOccurrences(of: ":dolphin:", with: "🐬")
            .replacingOccurrences(of: ":whale:", with: "🐳")
            .replacingOccurrences(of: ":whale2:", with: "🐋")
            .replacingOccurrences(of: ":crocodile:", with: "🐊")
            .replacingOccurrences(of: ":leopard:", with: "🐆")
            .replacingOccurrences(of: ":tiger2:", with: "🐅")
            .replacingOccurrences(of: ":water_buffalo:", with: "🐃")
            .replacingOccurrences(of: ":ox:", with: "🐂")
            .replacingOccurrences(of: ":cow2:", with: "🐄")
            .replacingOccurrences(of: ":dromedary_camel:", with: "🐪")
            .replacingOccurrences(of: ":camel:", with: "🐫")
            .replacingOccurrences(of: ":elephant:", with: "🐘")
            .replacingOccurrences(of: ":goat:", with: "🐐")
            .replacingOccurrences(of: ":ram:", with: "🐏")
            .replacingOccurrences(of: ":sheep:", with: "🐑")
            .replacingOccurrences(of: ":racehorse:", with: "🐎")
            .replacingOccurrences(of: ":pig2:", with: "🐖")
            .replacingOccurrences(of: ":rat:", with: "🐀")
            .replacingOccurrences(of: ":mouse2:", with: "🐁")
            .replacingOccurrences(of: ":rooster:", with: "🐓")
            .replacingOccurrences(of: ":turkey:", with: "🦃")
            .replacingOccurrences(of: ":dove_of_peace:", with: "🕊")
            .replacingOccurrences(of: ":dog2:", with: "🐕")
            .replacingOccurrences(of: ":poodle:", with: "🐩")
            .replacingOccurrences(of: ":cat2:", with: "🐈")
            .replacingOccurrences(of: ":rabbit2:", with: "🐇")
            .replacingOccurrences(of: ":chipmunk:", with: "🐿")
            .replacingOccurrences(of: ":feet:", with: "🐾")
            .replacingOccurrences(of: ":dragon:", with: "🐉")
            .replacingOccurrences(of: ":dragon_face:", with: "🐲")
            .replacingOccurrences(of: ":cactus:", with: "🌵")
            .replacingOccurrences(of: ":christmas_tree:", with: "🎄")
            .replacingOccurrences(of: ":evergreen_tree:", with: "🌲")
            .replacingOccurrences(of: ":deciduous_tree:", with: "🌳")
            .replacingOccurrences(of: ":palm_tree:", with: "🌴")
            .replacingOccurrences(of: ":seedling:", with: "🌱")
            .replacingOccurrences(of: ":herb:", with: "🌿")
            .replacingOccurrences(of: ":shamrock:", with: "☘")
            .replacingOccurrences(of: ":four_leaf_clover:", with: "🍀")
            .replacingOccurrences(of: ":bamboo:", with: "🎍")
            .replacingOccurrences(of: ":tanabata_tree:", with: "🎋")
            .replacingOccurrences(of: ":leaves:", with: "🍃")
            .replacingOccurrences(of: ":fallen_leaf:", with: "🍂")
            .replacingOccurrences(of: ":maple_leaf:", with: "🍁")
            .replacingOccurrences(of: ":ear_of_rice:", with: "🌾")
            .replacingOccurrences(of: ":hibiscus:", with: "🌺")
            .replacingOccurrences(of: ":sunflower:", with: "🌻")
            .replacingOccurrences(of: ":rose:", with: "🌹")
            .replacingOccurrences(of: ":tulip:", with: "🌷")
            .replacingOccurrences(of: ":blossom:", with: "🌼")
            .replacingOccurrences(of: ":cherry_blossom:", with: "🌸")
            .replacingOccurrences(of: ":bouquet:", with: "💐")
            .replacingOccurrences(of: ":mushroom:", with: "🍄")
            .replacingOccurrences(of: ":chestnut:", with: "🌰")
            .replacingOccurrences(of: ":jack_o_lantern:", with: "🎃")
            .replacingOccurrences(of: ":shell:", with: "🐚")
            .replacingOccurrences(of: ":spider_web:", with: "🕸")
            .replacingOccurrences(of: ":earth_americas:", with: "🌎")
            .replacingOccurrences(of: ":earth_africa:", with: "🌍")
            .replacingOccurrences(of: ":earth_asia:", with: "🌏")
            .replacingOccurrences(of: ":full_moon:", with: "🌕")
            .replacingOccurrences(of: ":waning_gibbous_moon:", with: "🌖")
            .replacingOccurrences(of: ":last_quarter_moon:", with: "🌗")
            .replacingOccurrences(of: ":waning_crescent_moon:", with: "🌘")
            .replacingOccurrences(of: ":new_moon:", with: "🌑")
            .replacingOccurrences(of: ":waxing_crescent_moon:", with: "🌒")
            .replacingOccurrences(of: ":first_quarter_moon:", with: "🌓")
            .replacingOccurrences(of: ":moon:", with: "🌔")
            .replacingOccurrences(of: ":new_moon_with_face:", with: "🌚")
            .replacingOccurrences(of: ":full_moon_with_face:", with: "🌝")
            .replacingOccurrences(of: ":first_quarter_moon_with_face:", with: "🌛")
            .replacingOccurrences(of: ":last_quarter_moon_with_face:", with: "🌜")
            .replacingOccurrences(of: ":sun_with_face:", with: "🌞")
            .replacingOccurrences(of: ":crescent_moon:", with: "🌙")
            .replacingOccurrences(of: ":star:", with: "⭐")
            .replacingOccurrences(of: ":star2:", with: "🌟")
            .replacingOccurrences(of: ":dizzy:", with: "💫")
            .replacingOccurrences(of: ":sparkles:", with: "✨")
            .replacingOccurrences(of: ":comet:", with: "☄")
            .replacingOccurrences(of: ":sunny:", with: "☀️")
            .replacingOccurrences(of: ":white_sun_with_small_cloud:", with: "🌤")
            .replacingOccurrences(of: ":partly_sunny:", with: "⛅")
            .replacingOccurrences(of: ":white_sun_behind_cloud:", with: "🌥")
            .replacingOccurrences(of: ":white_sun_behind_cloud_with_rain:", with: "🌦")
            .replacingOccurrences(of: ":cloud:", with: "☁️")
            .replacingOccurrences(of: ":cloud_with_rain:", with: "🌧")
            .replacingOccurrences(of: ":thunder_cloud_and_rain:", with: "⛈")
            .replacingOccurrences(of: ":cloud_with_lightning:", with: "🌩")
            .replacingOccurrences(of: ":zap:", with: "⚡")
            .replacingOccurrences(of: ":fire:", with: "🔥")
            .replacingOccurrences(of: ":boom:", with: "💥")
            .replacingOccurrences(of: ":snowflake:", with: "❄️")
            .replacingOccurrences(of: ":cloud_with_snow:", with: "🌨")
            .replacingOccurrences(of: ":snowman:", with: "⛄")
            .replacingOccurrences(of: ":snowman_with_snow:", with: "☃")
            .replacingOccurrences(of: ":wind_blowing_face:", with: "🌬")
            .replacingOccurrences(of: ":dash:", with: "💨")
            .replacingOccurrences(of: ":cloud_with_tornado:", with: "🌪")
            .replacingOccurrences(of: ":fog:", with: "🌫")
            .replacingOccurrences(of: ":umbrella_without_rain:", with: "☂")
            .replacingOccurrences(of: ":umbrella:", with: "☔")
            .replacingOccurrences(of: ":droplet:", with: "💧")
            .replacingOccurrences(of: ":sweat_drops:", with: "💦")
            .replacingOccurrences(of: ":ocean:", with: "🌊")
            .replacingOccurrences(of: ":green_apple:", with: "🍏")
            .replacingOccurrences(of: ":apple:", with: "🍎")
            .replacingOccurrences(of: ":pear:", with: "🍐")
            .replacingOccurrences(of: ":tangerine:", with: "🍊")
            .replacingOccurrences(of: ":lemon:", with: "🍋")
            .replacingOccurrences(of: ":banana:", with: "🍌")
            .replacingOccurrences(of: ":watermelon:", with: "🍉")
            .replacingOccurrences(of: ":grapes:", with: "🍇")
            .replacingOccurrences(of: ":strawberry:", with: "🍓")
            .replacingOccurrences(of: ":melon:", with: "🍈")
            .replacingOccurrences(of: ":cherries:", with: "🍒")
            .replacingOccurrences(of: ":peach:", with: "🍑")
            .replacingOccurrences(of: ":pineapple:", with: "🍍")
            .replacingOccurrences(of: ":tomato:", with: "🍅")
            .replacingOccurrences(of: ":eggplant:", with: "🍆")
            .replacingOccurrences(of: ":hot_pepper:", with: "🌶")
            .replacingOccurrences(of: ":corn:", with: "🌽")
            .replacingOccurrences(of: ":sweet_potato:", with: "🍠")
            .replacingOccurrences(of: ":honey_pot:", with: "🍯")
            .replacingOccurrences(of: ":bread:", with: "🍞")
            .replacingOccurrences(of: ":cheese_wedge:", with: "🧀")
            .replacingOccurrences(of: ":poultry_leg:", with: "🍗")
            .replacingOccurrences(of: ":meat_on_bone:", with: "🍖")
            .replacingOccurrences(of: ":fried_shrimp:", with: "🍤")
            .replacingOccurrences(of: ":egg:", with: "🍳")
            .replacingOccurrences(of: ":hamburger:", with: "🍔")
            .replacingOccurrences(of: ":fries:", with: "🍟")
            .replacingOccurrences(of: ":hot_dog:", with: "🌭")
            .replacingOccurrences(of: ":pizza:", with: "🍕")
            .replacingOccurrences(of: ":spaghetti:", with: "🍝")
            .replacingOccurrences(of: ":taco:", with: "🌮")
            .replacingOccurrences(of: ":burrito:", with: "🌯")
            .replacingOccurrences(of: ":ramen:", with: "🍜")
            .replacingOccurrences(of: ":stew:", with: "🍲")
            .replacingOccurrences(of: ":fish_cake:", with: "🍥")
            .replacingOccurrences(of: ":sushi:", with: "🍣")
            .replacingOccurrences(of: ":bento:", with: "🍱")
            .replacingOccurrences(of: ":curry:", with: "🍛")
            .replacingOccurrences(of: ":rice_ball:", with: "🍙")
            .replacingOccurrences(of: ":rice:", with: "🍚")
            .replacingOccurrences(of: ":rice_cracker:", with: "🍘")
            .replacingOccurrences(of: ":oden:", with: "🍢")
            .replacingOccurrences(of: ":dango:", with: "🍡")
            .replacingOccurrences(of: ":shaved_ice:", with: "🍧")
            .replacingOccurrences(of: ":ice_cream:", with: "🍨")
            .replacingOccurrences(of: ":icecream:", with: "🍦")
            .replacingOccurrences(of: ":cake:", with: "🍰")
            .replacingOccurrences(of: ":birthday:", with: "🎂")
            .replacingOccurrences(of: ":custard:", with: "🍮")
            .replacingOccurrences(of: ":candy:", with: "🍬")
            .replacingOccurrences(of: ":lollipop:", with: "🍭")
            .replacingOccurrences(of: ":chocolate_bar:", with: "🍫")
            .replacingOccurrences(of: ":popcorn:", with: "🍿")
            .replacingOccurrences(of: ":doughnut:", with: "🍩")
            .replacingOccurrences(of: ":cookie:", with: "🍪")
            .replacingOccurrences(of: ":beer:", with: "🍺")
            .replacingOccurrences(of: ":beers:", with: "🍻")
            .replacingOccurrences(of: ":wine_glass:", with: "🍷")
            .replacingOccurrences(of: ":cocktail:", with: "🍸")
            .replacingOccurrences(of: ":tropical_drink:", with: "🍹")
            .replacingOccurrences(of: ":bottle:", with: "🍾")
            .replacingOccurrences(of: ":sake:", with: "🍶")
            .replacingOccurrences(of: ":tea:", with: "🍵")
            .replacingOccurrences(of: ":coffee:", with: "☕")
            .replacingOccurrences(of: ":baby_bottle:", with: "🍼")
            .replacingOccurrences(of: ":fork_and_knife:", with: "🍴")
            .replacingOccurrences(of: ":fork_and_knife_with_plate:", with: "🍽")
            .replacingOccurrences(of: ":soccer:", with: "⚽")
            .replacingOccurrences(of: ":basketball:", with: "🏀")
            .replacingOccurrences(of: ":football:", with: "🏈")
            .replacingOccurrences(of: ":baseball:", with: "⚾")
            .replacingOccurrences(of: ":tennis:", with: "🎾")
            .replacingOccurrences(of: ":volleyball:", with: "🏐")
            .replacingOccurrences(of: ":rugby_football:", with: "🏉")
            .replacingOccurrences(of: ":8ball:", with: "🎱")
            .replacingOccurrences(of: ":golf:", with: "⛳")
            .replacingOccurrences(of: ":golfer:", with: "🏌")
            .replacingOccurrences(of: ":table_tennis:", with: "🏓")
            .replacingOccurrences(of: ":badminton:", with: "🏸")
            .replacingOccurrences(of: ":ice_hockey:", with: "🏒")
            .replacingOccurrences(of: ":field_hockey:", with: "🏑")
            .replacingOccurrences(of: ":cricket:", with: "🏏")
            .replacingOccurrences(of: ":ski:", with: "🎿")
            .replacingOccurrences(of: ":skier:", with: "⛷")
            .replacingOccurrences(of: ":snowboarder:", with: "🏂")
            .replacingOccurrences(of: ":ice_skate:", with: "⛸")
            .replacingOccurrences(of: ":bow_and_arrow:", with: "🏹")
            .replacingOccurrences(of: ":fishing_pole_and_fish:", with: "🎣")
            .replacingOccurrences(of: ":rowboat:", with: "🚣")
            .replacingOccurrences(of: ":swimmer:", with: "🏊")
            .replacingOccurrences(of: ":surfer:", with: "🏄")
            .replacingOccurrences(of: ":bath:", with: "🛀")
            .replacingOccurrences(of: ":person_with_ball:", with: "⛹")
            .replacingOccurrences(of: ":weight_lifter:", with: "🏋")
            .replacingOccurrences(of: ":bicyclist:", with: "🚴")
            .replacingOccurrences(of: ":mountain_bicyclist:", with: "🚵")
            .replacingOccurrences(of: ":horse_racing:", with: "🏇")
            .replacingOccurrences(of: ":man_levitating:", with: "🕴")
            .replacingOccurrences(of: ":trophy:", with: "🏆")
            .replacingOccurrences(of: ":running_shirt_with_sash:", with: "🎽")
            .replacingOccurrences(of: ":sports_medal:", with: "🏅")
            .replacingOccurrences(of: ":military_medal:", with: "🎖")
            .replacingOccurrences(of: ":reminder_ribbon:", with: "🎗")
            .replacingOccurrences(of: ":rosette:", with: "🏵")
            .replacingOccurrences(of: ":ticket:", with: "🎫")
            .replacingOccurrences(of: ":admission_ticket:", with: "🎟")
            .replacingOccurrences(of: ":performing_arts:", with: "🎭")
            .replacingOccurrences(of: ":art:", with: "🎨")
            .replacingOccurrences(of: ":circus_tent:", with: "🎪")
            .replacingOccurrences(of: ":microphone:", with: "🎤")
            .replacingOccurrences(of: ":headphones:", with: "🎧")
            .replacingOccurrences(of: ":musical_score:", with: "🎼")
            .replacingOccurrences(of: ":musical_keyboard:", with: "🎹")
            .replacingOccurrences(of: ":saxophone:", with: "🎷")
            .replacingOccurrences(of: ":trumpet:", with: "🎺")
            .replacingOccurrences(of: ":guitar:", with: "🎸")
            .replacingOccurrences(of: ":violin:", with: "🎻")
            .replacingOccurrences(of: ":clapper:", with: "🎬")
            .replacingOccurrences(of: ":video_game:", with: "🎮")
            .replacingOccurrences(of: ":space_invader:", with: "👾")
            .replacingOccurrences(of: ":dart:", with: "🎯")
            .replacingOccurrences(of: ":game_die:", with: "🎲")
            .replacingOccurrences(of: ":slot_machine:", with: "🎰")
            .replacingOccurrences(of: ":bowling:", with: "🎳")
            .replacingOccurrences(of: ":car:", with: "🚗")
            .replacingOccurrences(of: ":taxi:", with: "🚕")
            .replacingOccurrences(of: ":blue_car:", with: "🚙")
            .replacingOccurrences(of: ":bus:", with: "🚌")
            .replacingOccurrences(of: ":trolleybus:", with: "🚎")
            .replacingOccurrences(of: ":racing_car:", with: "🏎")
            .replacingOccurrences(of: ":police_car:", with: "🚓")
            .replacingOccurrences(of: ":ambulance:", with: "🚑")
            .replacingOccurrences(of: ":fire_engine:", with: "🚒")
            .replacingOccurrences(of: ":minibus:", with: "🚐")
            .replacingOccurrences(of: ":truck:", with: "🚚")
            .replacingOccurrences(of: ":articulated_lorry:", with: "🚛")
            .replacingOccurrences(of: ":tractor:", with: "🚜")
            .replacingOccurrences(of: ":racing_motorcycle:", with: "🏍")
            .replacingOccurrences(of: ":bike:", with: "🚲")
            .replacingOccurrences(of: ":rotating_light:", with: "🚨")
            .replacingOccurrences(of: ":oncoming_police_car:", with: "🚔")
            .replacingOccurrences(of: ":oncoming_bus:", with: "🚍")
            .replacingOccurrences(of: ":oncoming_automobile:", with: "🚘")
            .replacingOccurrences(of: ":oncoming_taxi:", with: "🚖")
            .replacingOccurrences(of: ":aerial_tramway:", with: "🚡")
            .replacingOccurrences(of: ":mountain_cableway:", with: "🚠")
            .replacingOccurrences(of: ":suspension_railway:", with: "🚟")
            .replacingOccurrences(of: ":railway_car:", with: "🚃")
            .replacingOccurrences(of: ":train:", with: "🚋")
            .replacingOccurrences(of: ":monorail:", with: "🚝")
            .replacingOccurrences(of: ":bullettrain_side:", with: "🚄")
            .replacingOccurrences(of: ":bullettrain_front:", with: "🚅")
            .replacingOccurrences(of: ":light_rail:", with: "🚈")
            .replacingOccurrences(of: ":mountain_railway:", with: "🚞")
            .replacingOccurrences(of: ":steam_locomotive:", with: "🚂")
            .replacingOccurrences(of: ":train2:", with: "🚆")
            .replacingOccurrences(of: ":metro:", with: "🚇")
            .replacingOccurrences(of: ":tram:", with: "🚊")
            .replacingOccurrences(of: ":station:", with: "🚉")
            .replacingOccurrences(of: ":helicopter:", with: "🚁")
            .replacingOccurrences(of: ":small_airplane:", with: "🛩")
            .replacingOccurrences(of: ":airplane:", with: "✈️")
            .replacingOccurrences(of: ":airplane_departure:", with: "🛫")
            .replacingOccurrences(of: ":airplane_arrival:", with: "🛬")
            .replacingOccurrences(of: ":boat:", with: "⛵")
            .replacingOccurrences(of: ":motor_boat:", with: "🛥")
            .replacingOccurrences(of: ":speedboat:", with: "🚤")
            .replacingOccurrences(of: ":ferry:", with: "⛴")
            .replacingOccurrences(of: ":passenger_ship:", with: "🛳")
            .replacingOccurrences(of: ":rocket:", with: "🚀")
            .replacingOccurrences(of: ":artificial_satellite:", with: "🛰")
            .replacingOccurrences(of: ":seat:", with: "💺")
            .replacingOccurrences(of: ":anchor:", with: "⚓")
            .replacingOccurrences(of: ":construction:", with: "🚧")
            .replacingOccurrences(of: ":fuelpump:", with: "⛽")
            .replacingOccurrences(of: ":busstop:", with: "🚏")
            .replacingOccurrences(of: ":vertical_traffic_light:", with: "🚦")
            .replacingOccurrences(of: ":traffic_light:", with: "🚥")
            .replacingOccurrences(of: ":checkered_flag:", with: "🏁")
            .replacingOccurrences(of: ":ship:", with: "🚢")
            .replacingOccurrences(of: ":ferris_wheel:", with: "🎡")
            .replacingOccurrences(of: ":roller_coaster:", with: "🎢")
            .replacingOccurrences(of: ":carousel_horse:", with: "🎠")
            .replacingOccurrences(of: ":building_construction:", with: "🏗")
            .replacingOccurrences(of: ":foggy:", with: "🌁")
            .replacingOccurrences(of: ":tokyo_tower:", with: "🗼")
            .replacingOccurrences(of: ":factory:", with: "🏭")
            .replacingOccurrences(of: ":fountain:", with: "⛲")
            .replacingOccurrences(of: ":rice_scene:", with: "🎑")
            .replacingOccurrences(of: ":mountain:", with: "⛰")
            .replacingOccurrences(of: ":snow_capped_mountain:", with: "🏔")
            .replacingOccurrences(of: ":mount_fuji:", with: "🗻")
            .replacingOccurrences(of: ":volcano:", with: "🌋")
            .replacingOccurrences(of: ":japan:", with: "🗾")
            .replacingOccurrences(of: ":camping:", with: "🏕")
            .replacingOccurrences(of: ":tent:", with: "⛺")
            .replacingOccurrences(of: ":national_park:", with: "🏞")
            .replacingOccurrences(of: ":motorway:", with: "🛣")
            .replacingOccurrences(of: ":railway_track:", with: "🛤")
            .replacingOccurrences(of: ":sunrise:", with: "🌅")
            .replacingOccurrences(of: ":sunrise_over_mountains:", with: "🌄")
            .replacingOccurrences(of: ":desert:", with: "🏜")
            .replacingOccurrences(of: ":beach_with_umbrella:", with: "🏖")
            .replacingOccurrences(of: ":desert_island:", with: "🏝")
            .replacingOccurrences(of: ":city_sunrise:", with: "🌇")
            .replacingOccurrences(of: ":city_sunset:", with: "🌆")
            .replacingOccurrences(of: ":cityscape:", with: "🏙")
            .replacingOccurrences(of: ":night_with_stars:", with: "🌃")
            .replacingOccurrences(of: ":bridge_at_night:", with: "🌉")
            .replacingOccurrences(of: ":milky_way:", with: "🌌")
            .replacingOccurrences(of: ":stars:", with: "🌠")
            .replacingOccurrences(of: ":sparkler:", with: "🎇")
            .replacingOccurrences(of: ":fireworks:", with: "🎆")
            .replacingOccurrences(of: ":rainbow:", with: "🌈")
            .replacingOccurrences(of: ":buildings:", with: "🏘")
            .replacingOccurrences(of: ":european_castle:", with: "🏰")
            .replacingOccurrences(of: ":japanese_castle:", with: "🏯")
            .replacingOccurrences(of: ":stadium:", with: "🏟")
            .replacingOccurrences(of: ":statue_of_liberty:", with: "🗽")
            .replacingOccurrences(of: ":house:", with: "🏠")
            .replacingOccurrences(of: ":house_with_garden:", with: "🏡")
            .replacingOccurrences(of: ":derelict_house:", with: "🏚")
            .replacingOccurrences(of: ":office:", with: "🏢")
            .replacingOccurrences(of: ":department_store:", with: "🏬")
            .replacingOccurrences(of: ":post_office:", with: "🏣")
            .replacingOccurrences(of: ":european_post_office:", with: "🏤")
            .replacingOccurrences(of: ":hospital:", with: "🏥")
            .replacingOccurrences(of: ":bank:", with: "🏦")
            .replacingOccurrences(of: ":hotel:", with: "🏨")
            .replacingOccurrences(of: ":convenience_store:", with: "🏪")
            .replacingOccurrences(of: ":school:", with: "🏫")
            .replacingOccurrences(of: ":love_hotel:", with: "🏩")
            .replacingOccurrences(of: ":wedding:", with: "💒")
            .replacingOccurrences(of: ":museum:", with: "🏛")
            .replacingOccurrences(of: ":church:", with: "⛪")
            .replacingOccurrences(of: ":mosque:", with: "🕌")
            .replacingOccurrences(of: ":synagogue:", with: "🕍")
            .replacingOccurrences(of: ":kaaba:", with: "🕋")
            .replacingOccurrences(of: ":shinto_shrine:", with: "⛩")
            .replacingOccurrences(of: ":watch:", with: "⌚")
            .replacingOccurrences(of: ":iphone:", with: "📱")
            .replacingOccurrences(of: ":calling:", with: "📲")
            .replacingOccurrences(of: ":computer:", with: "💻")
            .replacingOccurrences(of: ":keyboard:", with: "⌨")
            .replacingOccurrences(of: ":desktop_computer:", with: "🖥")
            .replacingOccurrences(of: ":printer:", with: "🖨")
            .replacingOccurrences(of: ":three_button_mouse:", with: "🖱")
            .replacingOccurrences(of: ":trackball:", with: "🖲")
            .replacingOccurrences(of: ":joystick:", with: "🕹")
            .replacingOccurrences(of: ":compression:", with: "🗜")
            .replacingOccurrences(of: ":minidisc:", with: "💽")
            .replacingOccurrences(of: ":floppy_disk:", with: "💾")
            .replacingOccurrences(of: ":cd:", with: "💿")
            .replacingOccurrences(of: ":dvd:", with: "📀")
            .replacingOccurrences(of: ":vhs:", with: "📼")
            .replacingOccurrences(of: ":camera:", with: "📷")
            .replacingOccurrences(of: ":camera_with_flash:", with: "📸")
            .replacingOccurrences(of: ":video_camera:", with: "📹")
            .replacingOccurrences(of: ":movie_camera:", with: "🎥")
            .replacingOccurrences(of: ":film_projector:", with: "📽")
            .replacingOccurrences(of: ":film_frames:", with: "🎞")
            .replacingOccurrences(of: ":telephone_receiver:", with: "📞")
            .replacingOccurrences(of: ":phone:", with: "☎️")
            .replacingOccurrences(of: ":pager:", with: "📟")
            .replacingOccurrences(of: ":fax:", with: "📠")
            .replacingOccurrences(of: ":tv:", with: "📺")
            .replacingOccurrences(of: ":radio:", with: "📻")
            .replacingOccurrences(of: ":studio_microphone:", with: "🎙")
            .replacingOccurrences(of: ":level_slider:", with: "🎚")
            .replacingOccurrences(of: ":control_knobs:", with: "🎛")
            .replacingOccurrences(of: ":stopwatch:", with: "⏱")
            .replacingOccurrences(of: ":timer_clock:", with: "⏲")
            .replacingOccurrences(of: ":alarm_clock:", with: "⏰")
            .replacingOccurrences(of: ":mantelpiece_clock:", with: "🕰")
            .replacingOccurrences(of: ":hourglass_flowing_sand:", with: "⏳")
            .replacingOccurrences(of: ":hourglass:", with: "⌛")
            .replacingOccurrences(of: ":satellite:", with: "📡")
            .replacingOccurrences(of: ":battery:", with: "🔋")
            .replacingOccurrences(of: ":electric_plug:", with: "🔌")
            .replacingOccurrences(of: ":bulb:", with: "💡")
            .replacingOccurrences(of: ":flashlight:", with: "🔦")
            .replacingOccurrences(of: ":candle:", with: "🕯")
            .replacingOccurrences(of: ":wastebasket:", with: "🗑")
            .replacingOccurrences(of: ":oil_drum:", with: "🛢")
            .replacingOccurrences(of: ":money_with_wings:", with: "💸")
            .replacingOccurrences(of: ":dollar:", with: "💵")
            .replacingOccurrences(of: ":yen:", with: "💴")
            .replacingOccurrences(of: ":euro:", with: "💶")
            .replacingOccurrences(of: ":pound:", with: "💷")
            .replacingOccurrences(of: ":moneybag:", with: "💰")
            .replacingOccurrences(of: ":credit_card:", with: "💳")
            .replacingOccurrences(of: ":gem:", with: "💎")
            .replacingOccurrences(of: ":scales:", with: "⚖")
            .replacingOccurrences(of: ":wrench:", with: "🔧")
            .replacingOccurrences(of: ":hammer:", with: "🔨")
            .replacingOccurrences(of: ":hammer_and_pick:", with: "⚒")
            .replacingOccurrences(of: ":hammer_and_wrench:", with: "🛠")
            .replacingOccurrences(of: ":pick:", with: "⛏")
            .replacingOccurrences(of: ":nut_and_bolt:", with: "🔩")
            .replacingOccurrences(of: ":gear:", with: "⚙")
            .replacingOccurrences(of: ":chains:", with: "⛓")
            .replacingOccurrences(of: ":gun:", with: "🔫")
            .replacingOccurrences(of: ":bomb:", with: "💣")
            .replacingOccurrences(of: ":hocho:", with: "🔪")
            .replacingOccurrences(of: ":dagger_knife:", with: "🗡")
            .replacingOccurrences(of: ":crossed_swords:", with: "⚔")
            .replacingOccurrences(of: ":shield:", with: "🛡")
            .replacingOccurrences(of: ":smoking:", with: "🚬")
            .replacingOccurrences(of: ":skull_and_crossbones:", with: "☠")
            .replacingOccurrences(of: ":coffin:", with: "⚰")
            .replacingOccurrences(of: ":funeral_urn:", with: "⚱")
            .replacingOccurrences(of: ":amphora:", with: "🏺")
            .replacingOccurrences(of: ":crystal_ball:", with: "🔮")
            .replacingOccurrences(of: ":prayer_beads:", with: "📿")
            .replacingOccurrences(of: ":barber:", with: "💈")
            .replacingOccurrences(of: ":alembic:", with: "⚗")
            .replacingOccurrences(of: ":telescope:", with: "🔭")
            .replacingOccurrences(of: ":microscope:", with: "🔬")
            .replacingOccurrences(of: ":hole:", with: "🕳")
            .replacingOccurrences(of: ":pill:", with: "💊")
            .replacingOccurrences(of: ":syringe:", with: "💉")
            .replacingOccurrences(of: ":thermometer:", with: "🌡")
            .replacingOccurrences(of: ":label:", with: "🏷")
            .replacingOccurrences(of: ":bookmark:", with: "🔖")
            .replacingOccurrences(of: ":toilet:", with: "🚽")
            .replacingOccurrences(of: ":shower:", with: "🚿")
            .replacingOccurrences(of: ":bathtub:", with: "🛁")
            .replacingOccurrences(of: ":key:", with: "🔑")
            .replacingOccurrences(of: ":old_key:", with: "🗝")
            .replacingOccurrences(of: ":couch_and_lamp:", with: "🛋")
            .replacingOccurrences(of: ":sleeping_accommodation:", with: "🛌")
            .replacingOccurrences(of: ":bed:", with: "🛏")
            .replacingOccurrences(of: ":door:", with: "🚪")
            .replacingOccurrences(of: ":bellhop_bell:", with: "🛎")
            .replacingOccurrences(of: ":frame_with_picture:", with: "🖼")
            .replacingOccurrences(of: ":world_map:", with: "🗺")
            .replacingOccurrences(of: ":umbrella_on_ground:", with: "⛱")
            .replacingOccurrences(of: ":moyai:", with: "🗿")
            .replacingOccurrences(of: ":shopping_bags:", with: "🛍")
            .replacingOccurrences(of: ":balloon:", with: "🎈")
            .replacingOccurrences(of: ":flags:", with: "🎏")
            .replacingOccurrences(of: ":ribbon:", with: "🎀")
            .replacingOccurrences(of: ":gift:", with: "🎁")
            .replacingOccurrences(of: ":confetti_ball:", with: "🎊")
            .replacingOccurrences(of: ":tada:", with: "🎉")
            .replacingOccurrences(of: ":dolls:", with: "🎎")
            .replacingOccurrences(of: ":wind_chime:", with: "🎐")
            .replacingOccurrences(of: ":crossed_flags:", with: "🎌")
            .replacingOccurrences(of: ":izakaya_lantern:", with: "🏮")
            .replacingOccurrences(of: ":envelope:", with: "✉️")
            .replacingOccurrences(of: ":envelope_with_arrow:", with: "📩")
            .replacingOccurrences(of: ":incoming_envelope:", with: "📨")
            .replacingOccurrences(of: ":email:", with: "📧")
            .replacingOccurrences(of: ":love_letter:", with: "💌")
            .replacingOccurrences(of: ":postbox:", with: "📮")
            .replacingOccurrences(of: ":mailbox_closed:", with: "📪")
            .replacingOccurrences(of: ":mailbox:", with: "📫")
            .replacingOccurrences(of: ":mailbox_with_mail:", with: "📬")
            .replacingOccurrences(of: ":mailbox_with_no_mail:", with: "📭")
            .replacingOccurrences(of: ":package:", with: "📦")
            .replacingOccurrences(of: ":postal_horn:", with: "📯")
            .replacingOccurrences(of: ":inbox_tray:", with: "📥")
            .replacingOccurrences(of: ":outbox_tray:", with: "📤")
            .replacingOccurrences(of: ":scroll:", with: "📜")
            .replacingOccurrences(of: ":page_with_curl:", with: "📃")
            .replacingOccurrences(of: ":bookmark_tabs:", with: "📑")
            .replacingOccurrences(of: ":bar_chart:", with: "📊")
            .replacingOccurrences(of: ":chart_with_upwards_trend:", with: "📈")
            .replacingOccurrences(of: ":chart_with_downwards_trend:", with: "📉")
            .replacingOccurrences(of: ":page_facing_up:", with: "📄")
            .replacingOccurrences(of: ":date:", with: "📅")
            .replacingOccurrences(of: ":calendar:", with: "📆")
            .replacingOccurrences(of: ":spiral_calendar_pad:", with: "🗓")
            .replacingOccurrences(of: ":card_index:", with: "📇")
            .replacingOccurrences(of: ":card_file_box:", with: "🗃")
            .replacingOccurrences(of: ":ballot_box_with_ballot:", with: "🗳")
            .replacingOccurrences(of: ":file_cabinet:", with: "🗄")
            .replacingOccurrences(of: ":clipboard:", with: "📋")
            .replacingOccurrences(of: ":spiral_note_pad:", with: "🗒")
            .replacingOccurrences(of: ":file_folder:", with: "📁")
            .replacingOccurrences(of: ":open_file_folder:", with: "📂")
            .replacingOccurrences(of: ":card_index_dividers:", with: "🗂")
            .replacingOccurrences(of: ":rolled_up_newspaper:", with: "🗞")
            .replacingOccurrences(of: ":newspaper:", with: "📰")
            .replacingOccurrences(of: ":notebook:", with: "📓")
            .replacingOccurrences(of: ":closed_book:", with: "📕")
            .replacingOccurrences(of: ":green_book:", with: "📗")
            .replacingOccurrences(of: ":blue_book:", with: "📘")
            .replacingOccurrences(of: ":orange_book:", with: "📙")
            .replacingOccurrences(of: ":notebook_with_decorative_cover:", with: "📔")
            .replacingOccurrences(of: ":ledger:", with: "📒")
            .replacingOccurrences(of: ":books:", with: "📚")
            .replacingOccurrences(of: ":book:", with: "📖")
            .replacingOccurrences(of: ":link:", with: "🔗")
            .replacingOccurrences(of: ":paperclip:", with: "📎")
            .replacingOccurrences(of: ":linked_paperclips:", with: "🖇")
            .replacingOccurrences(of: ":scissors:", with: "✂️")
            .replacingOccurrences(of: ":triangular_ruler:", with: "📐")
            .replacingOccurrences(of: ":straight_ruler:", with: "📏")
            .replacingOccurrences(of: ":pushpin:", with: "📌")
            .replacingOccurrences(of: ":round_pushpin:", with: "📍")
            .replacingOccurrences(of: ":triangular_flag_on_post:", with: "🚩")
            .replacingOccurrences(of: ":waving_white_flag:", with: "🏳")
            .replacingOccurrences(of: ":waving_black_flag:", with: "🏴")
            .replacingOccurrences(of: ":closed_lock_with_key:", with: "🔐")
            .replacingOccurrences(of: ":lock:", with: "🔒")
            .replacingOccurrences(of: ":unlock:", with: "🔓")
            .replacingOccurrences(of: ":lock_with_ink_pen:", with: "🔏")
            .replacingOccurrences(of: ":lower_left_ballpoint_pen:", with: "🖊")
            .replacingOccurrences(of: ":lower_left_fountain_pen:", with: "🖋")
            .replacingOccurrences(of: ":black_nib:", with: "✒️")
            .replacingOccurrences(of: ":memo:", with: "📝")
            .replacingOccurrences(of: ":pencil2:", with: "✏️")
            .replacingOccurrences(of: ":lower_left_crayon:", with: "🖍")
            .replacingOccurrences(of: ":lower_left_paintbrush:", with: "🖌")
            .replacingOccurrences(of: ":mag:", with: "🔍")
            .replacingOccurrences(of: ":mag_right:", with: "🔎")
            .replacingOccurrences(of: ":heart:", with: "❤️")
            .replacingOccurrences(of: ":yellow_heart:", with: "💛")
            .replacingOccurrences(of: ":green_heart:", with: "💚")
            .replacingOccurrences(of: ":blue_heart:", with: "💙")
            .replacingOccurrences(of: ":purple_heart:", with: "💜")
            .replacingOccurrences(of: ":broken_heart:", with: "💔")
            .replacingOccurrences(of: ":heavy_heart_exclamation_mark_ornament:", with: "❣")
            .replacingOccurrences(of: ":two_hearts:", with: "💕")
            .replacingOccurrences(of: ":revolving_hearts:", with: "💞")
            .replacingOccurrences(of: ":heartbeat:", with: "💓")
            .replacingOccurrences(of: ":heartpulse:", with: "💗")
            .replacingOccurrences(of: ":sparkling_heart:", with: "💖")
            .replacingOccurrences(of: ":cupid:", with: "💘")
            .replacingOccurrences(of: ":gift_heart:", with: "💝")
            .replacingOccurrences(of: ":heart_decoration:", with: "💟")
            .replacingOccurrences(of: ":peace_symbol:", with: "☮")
            .replacingOccurrences(of: ":latin_cross:", with: "✝")
            .replacingOccurrences(of: ":star_and_crescent:", with: "☪")
            .replacingOccurrences(of: ":om_symbol:", with: "🕉")
            .replacingOccurrences(of: ":wheel_of_dharma:", with: "☸")
            .replacingOccurrences(of: ":star_of_david:", with: "✡")
            .replacingOccurrences(of: ":six_pointed_star:", with: "🔯")
            .replacingOccurrences(of: ":menorah_with_nine_branches:", with: "🕎")
            .replacingOccurrences(of: ":yin_yang:", with: "☯")
            .replacingOccurrences(of: ":orthodox_cross:", with: "☦")
            .replacingOccurrences(of: ":place_of_worship:", with: "🛐")
            .replacingOccurrences(of: ":ophiuchus:", with: "⛎")
            .replacingOccurrences(of: ":aries:", with: "♈")
            .replacingOccurrences(of: ":taurus:", with: "♉")
            .replacingOccurrences(of: ":gemini:", with: "♊")
            .replacingOccurrences(of: ":cancer:", with: "♋")
            .replacingOccurrences(of: ":leo:", with: "♌")
            .replacingOccurrences(of: ":virgo:", with: "♍")
            .replacingOccurrences(of: ":libra:", with: "♎")
            .replacingOccurrences(of: ":scorpius:", with: "♏")
            .replacingOccurrences(of: ":sagittarius:", with: "♐")
            .replacingOccurrences(of: ":capricorn:", with: "♑")
            .replacingOccurrences(of: ":aquarius:", with: "♒")
            .replacingOccurrences(of: ":pisces:", with: "♓")
            .replacingOccurrences(of: ":id:", with: "🆔")
            .replacingOccurrences(of: ":atom_symbol:", with: "⚛")
            .replacingOccurrences(of: ":u7a7a:", with: "🈳")
            .replacingOccurrences(of: ":u5272:", with: "🈹")
            .replacingOccurrences(of: ":radioactive_sign:", with: "☢")
            .replacingOccurrences(of: ":biohazard_sign:", with: "☣")
            .replacingOccurrences(of: ":mobile_phone_off:", with: "📴")
            .replacingOccurrences(of: ":vibration_mode:", with: "📳")
            .replacingOccurrences(of: ":u6709:", with: "🈶")
            .replacingOccurrences(of: ":u7121:", with: "🈚")
            .replacingOccurrences(of: ":u7533:", with: "🈸")
            .replacingOccurrences(of: ":u55b6:", with: "🈺")
            .replacingOccurrences(of: ":u6708:", with: "🈷️")
            .replacingOccurrences(of: ":eight_pointed_black_star:", with: "✴️")
            .replacingOccurrences(of: ":vs:", with: "🆚")
            .replacingOccurrences(of: ":accept:", with: "🉑")
            .replacingOccurrences(of: ":white_flower:", with: "💮")
            .replacingOccurrences(of: ":ideograph_advantage:", with: "🉐")
            .replacingOccurrences(of: ":secret:", with: "㊙️")
            .replacingOccurrences(of: ":congratulations:", with: "㊗️")
            .replacingOccurrences(of: ":u5408:", with: "🈴")
            .replacingOccurrences(of: ":u6e80:", with: "🈵")
            .replacingOccurrences(of: ":u7981:", with: "🈲")
            .replacingOccurrences(of: ":a:", with: "🅰️")
            .replacingOccurrences(of: ":b:", with: "🅱️")
            .replacingOccurrences(of: ":ab:", with: "🆎")
            .replacingOccurrences(of: ":cl:", with: "🆑")
            .replacingOccurrences(of: ":o2:", with: "🅾️")
            .replacingOccurrences(of: ":sos:", with: "🆘")
            .replacingOccurrences(of: ":no_entry:", with: "⛔")
            .replacingOccurrences(of: ":name_badge:", with: "📛")
            .replacingOccurrences(of: ":no_entry_sign:", with: "🚫")
            .replacingOccurrences(of: ":x:", with: "❌")
            .replacingOccurrences(of: ":o:", with: "⭕")
            .replacingOccurrences(of: ":anger:", with: "💢")
            .replacingOccurrences(of: ":hotsprings:", with: "♨️")
            .replacingOccurrences(of: ":no_pedestrians:", with: "🚷")
            .replacingOccurrences(of: ":do_not_litter:", with: "🚯")
            .replacingOccurrences(of: ":no_bicycles:", with: "🚳")
            .replacingOccurrences(of: ":non-potable_water:", with: "🚱")
            .replacingOccurrences(of: ":underage:", with: "🔞")
            .replacingOccurrences(of: ":no_mobile_phones:", with: "📵")
            .replacingOccurrences(of: ":exclamation:", with: "❗")
            .replacingOccurrences(of: ":grey_exclamation:", with: "❕")
            .replacingOccurrences(of: ":question:", with: "❓")
            .replacingOccurrences(of: ":grey_question:", with: "❔")
            .replacingOccurrences(of: ":bangbang:", with: "‼️")
            .replacingOccurrences(of: ":interrobang:", with: "⁉️")
            .replacingOccurrences(of: ":low_brightness:", with: "🔅")
            .replacingOccurrences(of: ":high_brightness:", with: "🔆")
            .replacingOccurrences(of: ":trident:", with: "🔱")
            .replacingOccurrences(of: ":fleur_de_lis:", with: "⚜")
            .replacingOccurrences(of: ":part_alternation_mark:", with: "〽️")
            .replacingOccurrences(of: ":warning:", with: "⚠️")
            .replacingOccurrences(of: ":children_crossing:", with: "🚸")
            .replacingOccurrences(of: ":beginner:", with: "🔰")
            .replacingOccurrences(of: ":recycle:", with: "♻️")
            .replacingOccurrences(of: ":u6307:", with: "🈯")
            .replacingOccurrences(of: ":chart:", with: "💹")
            .replacingOccurrences(of: ":sparkle:", with: "❇️")
            .replacingOccurrences(of: ":eight_spoked_asterisk:", with: "✳️")
            .replacingOccurrences(of: ":negative_squared_cross_mark:", with: "❎")
            .replacingOccurrences(of: ":white_check_mark:", with: "✅")
            .replacingOccurrences(of: ":diamond_shape_with_a_dot_inside:", with: "💠")
            .replacingOccurrences(of: ":cyclone:", with: "🌀")
            .replacingOccurrences(of: ":loop:", with: "➿")
            .replacingOccurrences(of: ":globe_with_meridians:", with: "🌐")
            .replacingOccurrences(of: ":m:", with: "Ⓜ️")
            .replacingOccurrences(of: ":atm:", with: "🏧")
            .replacingOccurrences(of: ":sa:", with: "🈂️")
            .replacingOccurrences(of: ":passport_control:", with: "🛂")
            .replacingOccurrences(of: ":customs:", with: "🛃")
            .replacingOccurrences(of: ":baggage_claim:", with: "🛄")
            .replacingOccurrences(of: ":left_luggage:", with: "🛅")
            .replacingOccurrences(of: ":wheelchair:", with: "♿")
            .replacingOccurrences(of: ":no_smoking:", with: "🚭")
            .replacingOccurrences(of: ":wc:", with: "🚾")
            .replacingOccurrences(of: ":parking:", with: "🅿️")
            .replacingOccurrences(of: ":potable_water:", with: "🚰")
            .replacingOccurrences(of: ":mens:", with: "🚹")
            .replacingOccurrences(of: ":womens:", with: "🚺")
            .replacingOccurrences(of: ":baby_symbol:", with: "🚼")
            .replacingOccurrences(of: ":restroom:", with: "🚻")
            .replacingOccurrences(of: ":put_litter_in_its_place:", with: "🚮")
            .replacingOccurrences(of: ":cinema:", with: "🎦")
            .replacingOccurrences(of: ":signal_strength:", with: "📶")
            .replacingOccurrences(of: ":koko:", with: "🈁")
            .replacingOccurrences(of: ":ng:", with: "🆖")
            .replacingOccurrences(of: ":ok:", with: "🆗")
            .replacingOccurrences(of: ":up:", with: "🆙")
            .replacingOccurrences(of: ":cool:", with: "🆒")
            .replacingOccurrences(of: ":new:", with: "🆕")
            .replacingOccurrences(of: ":free:", with: "🆓")
            .replacingOccurrences(of: ":zero:", with: "0️⃣")
            .replacingOccurrences(of: ":one:", with: "1️⃣")
            .replacingOccurrences(of: ":two:", with: "2️⃣")
            .replacingOccurrences(of: ":three:", with: "3️⃣")
            .replacingOccurrences(of: ":four:", with: "4️⃣")
            .replacingOccurrences(of: ":five:", with: "5️⃣")
            .replacingOccurrences(of: ":six:", with: "6️⃣")
            .replacingOccurrences(of: ":seven:", with: "7️⃣")
            .replacingOccurrences(of: ":eight:", with: "8️⃣")
            .replacingOccurrences(of: ":nine:", with: "9️⃣")
            .replacingOccurrences(of: ":keycap_ten:", with: "🔟")
            .replacingOccurrences(of: ":keycap_star:", with: "*⃣")
            .replacingOccurrences(of: ":arrow_forward:", with: "▶️")
            .replacingOccurrences(of: ":double_vertical_bar:", with: "⏸")
            .replacingOccurrences(of: ":black_right_pointing_triangle_with_double_vertical_bar:", with: "⏭")
            .replacingOccurrences(of: ":black_square_for_stop:", with: "⏹")
            .replacingOccurrences(of: ":black_circle_for_record:", with: "⏺")
            .replacingOccurrences(of: ":black_right_pointing_double_triangle_with_vertical_bar:", with: "⏯")
            .replacingOccurrences(of: ":black_left_pointing_double_triangle_with_vertical_bar:", with: "⏮")
            .replacingOccurrences(of: ":fast_forward:", with: "⏩")
            .replacingOccurrences(of: ":rewind:", with: "⏪")
            .replacingOccurrences(of: ":twisted_rightwards_arrows:", with: "🔀")
            .replacingOccurrences(of: ":repeat:", with: "🔁")
            .replacingOccurrences(of: ":repeat_one:", with: "🔂")
            .replacingOccurrences(of: ":arrow_backward:", with: "◀️")
            .replacingOccurrences(of: ":arrow_up_small:", with: "🔼")
            .replacingOccurrences(of: ":arrow_down_small:", with: "🔽")
            .replacingOccurrences(of: ":arrow_double_up:", with: "⏫")
            .replacingOccurrences(of: ":arrow_double_down:", with: "⏬")
            .replacingOccurrences(of: ":arrow_right:", with: "➡️")
            .replacingOccurrences(of: ":arrow_left:", with: "⬅️")
            .replacingOccurrences(of: ":arrow_up:", with: "⬆️")
            .replacingOccurrences(of: ":arrow_down:", with: "⬇️")
            .replacingOccurrences(of: ":arrow_upper_right:", with: "↗️")
            .replacingOccurrences(of: ":arrow_lower_right:", with: "↘️")
            .replacingOccurrences(of: ":arrow_lower_left:", with: "↙️")
            .replacingOccurrences(of: ":arrow_upper_left:", with: "↖️")
            .replacingOccurrences(of: ":arrow_up_down:", with: "↕️")
            .replacingOccurrences(of: ":left_right_arrow:", with: "↔️")
            .replacingOccurrences(of: ":arrows_counterclockwise:", with: "🔄")
            .replacingOccurrences(of: ":arrow_right_hook:", with: "↪️")
            .replacingOccurrences(of: ":leftwards_arrow_with_hook:", with: "↩️")
            .replacingOccurrences(of: ":arrow_heading_up:", with: "⤴️")
            .replacingOccurrences(of: ":arrow_heading_down:", with: "⤵️")
            .replacingOccurrences(of: ":hash:", with: "#️⃣")
            .replacingOccurrences(of: ":information_source:", with: "ℹ️")
            .replacingOccurrences(of: ":abc:", with: "🔤")
            .replacingOccurrences(of: ":abcd:", with: "🔡")
            .replacingOccurrences(of: ":capital_abcd:", with: "🔠")
            .replacingOccurrences(of: ":symbols:", with: "🔣")
            .replacingOccurrences(of: ":musical_note:", with: "🎵")
            .replacingOccurrences(of: ":notes:", with: "🎶")
            .replacingOccurrences(of: ":wavy_dash:", with: "〰️")
            .replacingOccurrences(of: ":curly_loop:", with: "➰")
            .replacingOccurrences(of: ":heavy_check_mark:", with: "✔️")
            .replacingOccurrences(of: ":arrows_clockwise:", with: "🔃")
            .replacingOccurrences(of: ":heavy_plus_sign:", with: "➕")
            .replacingOccurrences(of: ":heavy_minus_sign:", with: "➖")
            .replacingOccurrences(of: ":heavy_division_sign:", with: "➗")
            .replacingOccurrences(of: ":heavy_multiplication_x:", with: "✖️")
            .replacingOccurrences(of: ":heavy_dollar_sign:", with: "💲")
            .replacingOccurrences(of: ":currency_exchange:", with: "💱")
            .replacingOccurrences(of: ":copyright:", with: "©️")
            .replacingOccurrences(of: ":registered:", with: "®️")
            .replacingOccurrences(of: ":tm:", with: "™️")
            .replacingOccurrences(of: ":end:", with: "🔚")
            .replacingOccurrences(of: ":back:", with: "🔙")
            .replacingOccurrences(of: ":on:", with: "🔛")
            .replacingOccurrences(of: ":top:", with: "🔝")
            .replacingOccurrences(of: ":soon:", with: "🔜")
            .replacingOccurrences(of: ":ballot_box_with_check:", with: "☑️")
            .replacingOccurrences(of: ":radio_button:", with: "🔘")
            .replacingOccurrences(of: ":white_circle:", with: "⚪")
            .replacingOccurrences(of: ":black_circle:", with: "⚫")
            .replacingOccurrences(of: ":red_circle:", with: "🔴")
            .replacingOccurrences(of: ":large_blue_circle:", with: "🔵")
            .replacingOccurrences(of: ":small_orange_diamond:", with: "🔸")
            .replacingOccurrences(of: ":small_blue_diamond:", with: "🔹")
            .replacingOccurrences(of: ":large_orange_diamond:", with: "🔶")
            .replacingOccurrences(of: ":large_blue_diamond:", with: "🔷")
            .replacingOccurrences(of: ":small_red_triangle:", with: "🔺")
            .replacingOccurrences(of: ":black_small_square:", with: "▪️")
            .replacingOccurrences(of: ":white_small_square:", with: "▫️")
            .replacingOccurrences(of: ":black_large_square:", with: "⬛")
            .replacingOccurrences(of: ":white_large_square:", with: "⬜")
            .replacingOccurrences(of: ":small_red_triangle_down:", with: "🔻")
            .replacingOccurrences(of: ":black_medium_square:", with: "◼️")
            .replacingOccurrences(of: ":white_medium_square:", with: "◻️")
            .replacingOccurrences(of: ":black_medium_small_square:", with: "◾")
            .replacingOccurrences(of: ":white_medium_small_square:", with: "◽")
            .replacingOccurrences(of: ":black_square_button:", with: "🔲")
            .replacingOccurrences(of: ":white_square_button:", with: "🔳")
            .replacingOccurrences(of: ":speaker:", with: "🔈")
            .replacingOccurrences(of: ":sound:", with: "🔉")
            .replacingOccurrences(of: ":loud_sound:", with: "🔊")
            .replacingOccurrences(of: ":mute:", with: "🔇")
            .replacingOccurrences(of: ":mega:", with: "📣")
            .replacingOccurrences(of: ":loudspeaker:", with: "📢")
            .replacingOccurrences(of: ":bell:", with: "🔔")
            .replacingOccurrences(of: ":no_bell:", with: "🔕")
            .replacingOccurrences(of: ":black_joker:", with: "🃏")
            .replacingOccurrences(of: ":mahjong:", with: "🀄")
            .replacingOccurrences(of: ":spades:", with: "♠️")
            .replacingOccurrences(of: ":clubs:", with: "♣️")
            .replacingOccurrences(of: ":hearts:", with: "♥️")
            .replacingOccurrences(of: ":diamonds:", with: "♦️")
            .replacingOccurrences(of: ":flower_playing_cards:", with: "🎴")
            .replacingOccurrences(of: ":thought_balloon:", with: "💭")
            .replacingOccurrences(of: ":right_anger_bubble:", with: "🗯")
            .replacingOccurrences(of: ":speech_balloon:", with: "💬")
            .replacingOccurrences(of: ":left_speech_bubble:", with: "🗨")
            .replacingOccurrences(of: ":clock1:", with: "🕐")
            .replacingOccurrences(of: ":clock2:", with: "🕑")
            .replacingOccurrences(of: ":clock3:", with: "🕒")
            .replacingOccurrences(of: ":clock4:", with: "🕓")
            .replacingOccurrences(of: ":clock5:", with: "🕔")
            .replacingOccurrences(of: ":clock6:", with: "🕕")
            .replacingOccurrences(of: ":clock7:", with: "🕖")
            .replacingOccurrences(of: ":clock8:", with: "🕗")
            .replacingOccurrences(of: ":clock9:", with: "🕘")
            .replacingOccurrences(of: ":clock10:", with: "🕙")
            .replacingOccurrences(of: ":clock11:", with: "🕚")
            .replacingOccurrences(of: ":clock12:", with: "🕛")
            .replacingOccurrences(of: ":clock130:", with: "🕜")
            .replacingOccurrences(of: ":clock230:", with: "🕝")
            .replacingOccurrences(of: ":clock330:", with: "🕞")
            .replacingOccurrences(of: ":clock430:", with: "🕟")
            .replacingOccurrences(of: ":clock530:", with: "🕠")
            .replacingOccurrences(of: ":clock630:", with: "🕡")
            .replacingOccurrences(of: ":clock730:", with: "🕢")
            .replacingOccurrences(of: ":clock830:", with: "🕣")
            .replacingOccurrences(of: ":clock930:", with: "🕤")
            .replacingOccurrences(of: ":clock1030:", with: "🕥")
            .replacingOccurrences(of: ":clock1130:", with: "🕦")
            .replacingOccurrences(of: ":clock1230:", with: "🕧")
    }
}


================================================
FILE: Sources/SlackEvent.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

enum SlackEvent {
    
    case message(SlackMessage)
    case messageChanged(SlackMessage)
    case messageDeleted(String, String)
    case messageReactionAdded(String, String, String)
    case messageReactionRemoved(String, String, String)
    case hello
    case reconnectUrl
    case userTyping(String, String)
    case channelMarked
    case presenceChange(String, SlackUser.Presence)
    case unknown(String)
    case fileCreated
    case filePublic
    case fileShared
    case fileChange
    case prefChange
    case groupMarked
    case mpimMarked
    case imMarked
    case userChange
    case reply(Int, String)
    case teamRename(String)
    case desktopNotification(String, String)
}


================================================
FILE: Sources/SlackGroup.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

struct SlackGroup {
    
    let id: String
    let name: String
    let members: [String]
    let topic: String
}


================================================
FILE: Sources/SlackIM.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

struct SlackIM {
    
    let id: String
    let user: String
}


================================================
FILE: Sources/SlackMessage.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

struct SlackMessage {
    
    let ts: String
    let channel: String
    let user: String
    let text: String
    
    let reactions: [SlackMessageReaction]
}



================================================
FILE: Sources/SlackMessageReaction.swift
================================================
//
//  SlackMessageReaction.swift
//  slash
//
//  Created by damian on 08.02.2019.
//  Copyright © 2019 kolakowski. All rights reserved.
//

import Foundation

struct SlackMessageReaction {
    
    let name: String
    let count: Int
    let users: [String]
}


================================================
FILE: Sources/SlackOAuth2.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

enum SlackOAuth2Error: Error {
    case error(String)
}

class SlackOAuth2 {
    
    static let port = 7777
    static let address = "http://localhost:\(SlackOAuth2.port)"
    
    private let clientId : String
    private let clientSecret : String
    private let permissions : [String]
    
    private var accessToken : String?
    
    init(clientId: String, clientSecret: String, permissions: [String]) {
        self.clientId = clientId
        self.clientSecret = clientSecret
        self.permissions = permissions
    }
    
    func authenticate() throws -> String? {
        
        let permissionsStr = self.permissions.joined(separator: " ")
        
        Utils.shell("open", "https://slack.com/oauth/authorize?client_id=\(self.clientId)&scope=\(permissionsStr)&redirect_uri=\(SlackOAuth2.address)")
        
        let server = try Server(in_port_t(SlackOAuth2.port))
        
        var processIncomingRequests = true

        while processIncomingRequests {
            
            try server.serve { (request, responder) in
                
                guard request.path == "/" else {
                    responder(TextResponse(200, "Invalid request."))
                    return
                }
                
                guard let code = request.query.first?.1 else {
                    responder(TextResponse(200, "Could not get the code."))
                    return
                }
                
                guard let url = URL(string: "https://slack.com/api/oauth.access?client_id=\(self.clientId)&client_secret=\(self.clientSecret)&code=\(code)&redirect_uri=\(SlackOAuth2.address)") else {
                    responder(TextResponse(200, "Could not create URL object."))
                    return
                }
                
                do {
                    
                    let (theData, _) = try URLSession.shared.synchronousDataTask(with: URLRequest(url: url))
                    guard let data = theData else {
                        responder(TextResponse(200, "No response from Slack."))
                        return
                    }
                    let object = try JSONSerialization.jsonObject(with:data)
                    
                    guard let dict = object as? Dictionary<String, Any> else {
                        responder(TextResponse(200, "Slack's response is not a dictionary \(object)."))
                        return
                    }
                    
                    guard let accessToken = dict["access_token"] as? String else {
                        responder(TextResponse(200, "Could not find access token in the response \(dict)."))
                        return
                    }
                    
                    self.accessToken = accessToken
                    processIncomingRequests = false
                    
                    responder(HtmlResponse(200, R.string.authConfirmation))
                } catch {
                    responder(TextResponse(200, "Error occured for token request \(error)."))
                }
            }
        }
        

        return self.accessToken
    }
}


================================================
FILE: Sources/SlackRealTimeClient.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation


class SlackRealTimeClient {
    
    enum Err: Error {
        case error(String)
    }
    
    private let websocketClient: WebSocketClient
    
    init(_ url: String) throws {
        
        guard let wssUrl = URL(string: url) else {
            throw Err.error("Failed to create URL object from: \(url).")
        }
        
        guard let wssHost = wssUrl.host else {
            throw Err.error("Could not find host for: \(wssUrl).")
        }

        self.websocketClient = try WebSocketClient(wssHost, path: wssUrl.path)
    }
 
    func send(_ channel: String, message: String, replyId: Int) throws {
        let jsonData = try JSONSerialization.data(withJSONObject:
            ["id": replyId, "type": "message", "channel": channel, "text": message],
             options: .prettyPrinted)
        try self.websocketClient.writeFrame(opcode: .text, payload: [UInt8](jsonData))
    }
    
    func waitForEvent() throws -> SlackEvent? {
        
        guard let frame = try self.websocketClient.waitForFrame() else {
            return nil
        }
        switch frame.opcode {
        case .text:
            let object = try JSONSerialization.jsonObject(with: Data(frame.payload), options: .init(rawValue: 0))
            guard let dictionary = object as? Dictionary<String, Any> else {
                return nil
            }
            if let replyToId = dictionary["reply_to"] as? Int {
                let ts = (dictionary["ts"] as? String) ?? ""
                return .reply(replyToId, ts)
            }
            guard let type = dictionary["type"] as? String else {
                return nil
            }
            switch type {
                case "hello":
                    return .hello
                case "message":
                    return self.handleMessageEvent(dictionary)
                case "reconnect_url":
                    return .reconnectUrl
                case "user_typing":
                    let channel = (dictionary["channel"] as? String) ?? ""
                    let user = (dictionary["user"] as? String) ?? ""
                    return .userTyping(channel, user)
                case "channel_marked":
                    return .channelMarked
                case "presence_change":
                    let user = (dictionary["user"] as? String) ?? ""
                    let presenceValue: String = (dictionary["presence"] as? String) ?? ""
                    return .presenceChange(user, presenceValue == "active" ? .active : .away)
                case "file_created":
                    return .fileCreated
                case "file_public":
                    return .filePublic
                case "file_shared":
                    return .fileShared
                case "file_change":
                    return .fileChange
                case "pref_change":
                    return .prefChange
                case "group_marked":
                    return .groupMarked
                case "mpim_marked":
                    return .mpimMarked
                case "im_marked":
                    return .imMarked
                case "reaction_added":
                    if let item = dictionary["item"] as? [String: Any] {
                        if (item["type"] as? String) == "message" {
                            let reaction = (dictionary["reaction"] as? String) ?? ""
                            let channel = item["channel"] as? String ?? ""
                            let ts = item["ts"] as? String ?? ""
                            return .messageReactionAdded(reaction, channel, ts)
                        }
                    }
                    return nil
                case "user_change":
                    return .userChange
                case "team_rename":
                    let name = (dictionary["name"] as? String) ?? ""
                    return .teamRename(name)
                case "desktop_notification":
                    let title = ((dictionary["title"] as? String) ?? "") + " " + ((dictionary["subtitle"] as? String) ?? "")
                    let message = ((dictionary["content"] as? String) ?? "")
                    return .desktopNotification(title, message)
                default:
                    return .unknown("\(type) - \(dictionary)")
            }
        case .ping:
            try self.websocketClient.writeFrame(opcode: .pong)
        default:
            return nil
        }
        return nil
    }
    
    private func handleMessageEvent(_ dictionary: Dictionary<String, Any>) -> SlackEvent {
        
        let channel = (dictionary["channel"] as? String) ?? ""
        let user    = (dictionary["user"] as? String) ?? "unknown"
        let message = (dictionary["text"] as? String) ?? ""
        let ts      = (dictionary["ts"] as? String) ?? ""
        let subType = (dictionary["subtype"] as? String) ?? ""
        
        switch subType {
            case "message_changed":
                if let updatedMessage = (dictionary["message"] as? Dictionary<String, Any>) {
                    let user = (updatedMessage["user"] as? String) ?? "unknown"
                    let ts = (updatedMessage["ts"] as? String) ?? ""
                    let text = (updatedMessage["text"] as? String) ?? ""
                    return .messageChanged(SlackMessage(ts: ts, channel: channel, user: user, text: text, reactions: []))
                }
            case "message_deleted":
                let ts = (dictionary["deleted_ts"] as? String) ?? ""
                return .messageDeleted(ts, channel)
            default:break
        }
        
        return .message(SlackMessage(ts: ts, channel: channel, user: user, text: message, reactions: []))
    }
}


================================================
FILE: Sources/SlackTeam.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//


import Foundation

struct SlackTeam {
    
    let selfId: String
    let name: String
    let users: [SlackUser]
    let channels: [SlackChannel]
    let groups: [SlackGroup]
    let ims: [SlackIM]
    let wssUrl: String
}


================================================
FILE: Sources/SlackUser.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation


struct SlackUser {
    
    enum Presence {
        case active, away
    }
    
    let id: String
    let name: String
    let color: String
    let presence: Presence
}


================================================
FILE: Sources/SlackWebClient.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//


import Foundation

enum SlackWebClientError: Error {
    case error(String)
}

class SlackWebClient {
    
    private let token: String
    
    init(authenticatedBy token: String) {
        self.token = token
    }
    
    func rtm() throws -> SlackTeam {
        return processStartRTMresponse(try self.rpc(forMethod: "rtm.start"))
    }
    
    func history(for channel: String) throws -> [SlackMessage] {
        
        var method = "channels.history"
        
        if let firstCharacter = channel.first {
            switch firstCharacter {
                //TODO - This mapping is rather naive. There should be separated methods for: groups and ims.
                case "C": method = "channels.history"
                case "G": method = "groups.history"
                case "D": method = "im.history"
                default: break
            }
        }
        
        let response = try self.rpc(forMethod: method, withParams: ["channel": channel])
        
        guard let messages = response["messages"] as? Array<Any> else {
            throw SlackWebClientError.error("No messages array in the response \(response).")
        }
        
        return messages.map { item in
            guard let dictionary = item as? Dictionary<String, Any> else {
                return SlackMessage(ts: "", channel: "", user: "", text: "", reactions: [])
            }
            return SlackMessage(ts: (dictionary["ts"] as? String) ?? "",
                channel: channel,
                user: (dictionary["user"] as? String) ?? "",
                text: (dictionary["text"] as? String) ?? "",
                reactions: (dictionary["reactions"] as? [[String: Any]])?.map({ item in
                    return SlackMessageReaction(
                        name: item["name"] as? String ?? "",
                        count: item["count"] as? Int ?? 0,
                        users: item["users"] as? [String] ?? []
                    )
                }) ?? []
            )
        }
    }
    
    private func rpc(forMethod rpcMethod: String, withParams params: [String: String] = [:]) throws -> Dictionary<String, Any> {
        
        var queryParams = [String: String]()
        
        queryParams["token"] = token
        params.forEach { queryParams[$0.key] = $0.value }
        
        let urlString = ("https://slack.com/api/\(rpcMethod)?") + queryParams.map({ $0 + "=" + $1}).joined(separator: "&")
    
        guard let url = URL(string: urlString) else {
            throw SlackWebClientError.error("Could not create URL object.")
        }
        
        let (theData, _) = try URLSession.shared.synchronousDataTask(with: URLRequest(url: url))
        guard let data = theData else {
            throw SlackWebClientError.error("Error receiving data.")
        }
        let object = try JSONSerialization.jsonObject(with:data)
        
        guard let dict = object as? Dictionary<String, Any> else {
            throw SlackWebClientError.error("\(rpcMethod)'s response is not a dictionary.")
        }
        
        guard (dict["ok"] as? Bool) == true else {
            throw SlackWebClientError.error("result not ok \(dict).")
        }
        
        return dict
    }
    
    private func processStartRTMresponse(_ object: Any) -> SlackTeam {
        
        return SlackTeam(
            selfId : object ← "self" ← "id",
            name : object ← "team" ← "name",
            users: (object ←← "users").map(
                { SlackUser(id: $0 ← "id", name: $0 ← "name", color: $0 ← "color", presence: ($0 ← "presence") == "active" ? .active : .away) }
            ),
            channels: (object ←← "channels").map({
                SlackChannel(
                    id: $0 ← "id",
                    name: $0 ← "name",
                    members: ($0 ←← "members").map({ ($0 as? String) ?? "" }),
                    topic: $0 ← "topic",
                    general: $0 ← "is_general",
                    isMember: $0 ← "is_member"
                )}
            ),
            groups: (object ←← "groups").map(
                { SlackGroup(id: $0 ← "id", name: $0 ← "name",
                    members: ($0 ←← "members").map({ ($0 as? String) ?? "" }),
                    topic: $0 ← "topic")}
            ),
            ims: (object ←← "ims").map({ SlackIM(id: $0 ← "id", user: $0 ← "user") }),
            wssUrl: object ← "url"
        )
    }
}

precedencegroup LookupSeparatorPrecedence { associativity: left }

infix operator ← : LookupSeparatorPrecedence
infix operator ←← : LookupSeparatorPrecedence

func ← (left: Any, right: String) -> [String: Any] {
    if let dict = left as? [String: Any] {
        return (dict[right] as? [String: Any]) ?? [String: Any]()
    }
    return [String: Any]()
}

func ←← (left: Any, right: String) -> [Any] {
    if let dict = left as? [String: Any] {
        return (dict[right] as? [Any]) ?? [Any]()
    }
    return [Any]()
}

func ← (left: Any, right: String) -> String? {
    if let dict = left as? [String: Any] {
        return (dict[right] as? String)
    }
    return nil
}

func ← (left: Any, right: String) -> String {
    if let dict = left as? [String: Any] {
        return (dict[right] as? String) ?? ""
    }
    return ""
}

func ← (left: Any, right: String) -> Bool? {
    if let dict = left as? [String: Any] {
        return (dict[right] as? Bool)
    }
    return nil
}

func ← (left: Any, right: String) -> Bool {
    if let dict = left as? [String: Any] {
        return (dict[right] as? Bool) ?? false
    }
    return false
}

func ← (left: [String: Any], right: String) -> [String: Any] {
    return (left[right] as? [String: Any]) ?? [String: Any]()
}

func ← (left: [String: Any], right: String) -> Int? {
    return (left[right] as? Int) ?? nil
}

func ← (left: [String: Any], right: String) -> Int {
    return (left[right] as? Int) ?? 0
}

func ← (left: [String: Any], right: String) -> String? {
    return (left[right] as? String) ?? nil
}

func ← (left: [String: Any], right: String) -> String {
    return (left[right] as? String) ?? ""
}

func ← (left: [String: Any], right: String) -> Bool? {
    return (left[right] as? Bool)
}

func ← (left: [String: Any], right: String) -> Bool {
    return (left[right] as? Bool) ?? false
}


================================================
FILE: Sources/Socket.swift
================================================
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
	import Darwin
#elseif os(Linux)
	import Glibc
#endif

struct Socket {
  static func read(_ socket:Int32, _ buffer: UnsafeMutableRawPointer, _ size:Int) -> Int {
    #if os(macOS) 
      return Darwin.read(socket, buffer, size) 
    #elseif os(Linux)
      return Glibc.read(socket, buffer, size) 
    #endif
  }
  
  static func write(_ socket:Int32, _ buffer: Array<UInt8>, _ size:Int) -> Int {
    #if os(macOS) 
      return Darwin.write(socket, buffer, size) 
    #elseif os(Linux)
      return Glibc.write(socket, buffer, size) 
    #endif
  }
  
  static func close(_ socket:Int32) -> Int32 {
    #if os(macOS) 
      return Darwin.close(socket) 
    #elseif os(Linux)
      return Glibc.close(socket)
    #endif
  }
}


================================================
FILE: Sources/TLSSocket.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

#if os(OSX) || os(iOS)

enum TLSSocketError: Error {
    case error(String)
}

class TLSSocket {
    
    private var socket: Int32
    private let sslContext: SSLContext
    
    init(_ address: String, port: Int = 443) throws {
        
        guard let context = SSLCreateContext(nil, .clientSide, .streamType) else {
            throw TLSSocketError.error("SSLCreateContext returned null.")
        }
        
        self.sslContext = context
        
        let socket = Darwin.socket(AF_INET, SOCK_STREAM, 0)
        
        guard socket != -1 else {
            throw TLSSocketError.error("Darwin.socket failed: \(errno)")
        }
        
        self.socket = socket
        
        var addr = sockaddr_in()
        addr.sin_len = __uint8_t(MemoryLayout<sockaddr_in>.size)
        addr.sin_family = sa_family_t(AF_INET)
        addr.sin_port = UInt16(port).bigEndian
        
        guard inet_pton(AF_INET, address, &(addr.sin_addr)) == 1 else {
            let _ = Darwin.close(self.socket)
            throw TLSSocketError.error("inet_pton failed.")
        }
        
        if withUnsafePointer(to: &addr, {
            Darwin.connect(socket, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in>.size))
        }) == -1 {
            let _ = Darwin.close(self.socket)
            throw TLSSocketError.error("Darwin.connect failed: \(errno)")
        }
        
        SSLSetIOFuncs(context, sslRead, sslWrite)
        
        guard SSLSetConnection(context, &self.socket) == noErr else {
            let _ = Darwin.close(self.socket)
            throw TLSSocketError.error("SSLSetConnection failed.")
        }
        
        let handshakeResult = SSLHandshake(context)
        
        guard handshakeResult == noErr else {
            let _ = Darwin.close(self.socket)
            throw TLSSocketError.error("SSLHandshake failed: \(handshakeResult)")
        }
    }
    
    func close() {
        SSLClose(self.sslContext)
        let _ = Darwin.close(self.socket)
    }

    func writeData(_ data: [UInt8]) throws {
        var processed = 0
        let result = SSLWrite(self.sslContext, data, data.count, &processed)
        guard result == noErr else {
            throw TLSSocketError.error("SSLWrite failed: \(result)")
        }
    }
    
    func readData() throws -> [UInt8] {
        var processed = 0
        var data = [UInt8](repeating: 0, count: 1024)
        let result = SSLRead(self.sslContext, &data, data.count, &processed)
        guard result == noErr else {
            throw TLSSocketError.error("SSLRead failed: \(result)")
        }
        data.removeLast(data.count - processed)
        return data
    }
}

func sslRead(_ socketRef: SSLConnectionRef, _ data: UnsafeMutableRawPointer, _ length: UnsafeMutablePointer<Int>) -> OSStatus {
    let socket = socketRef.load(as: Int32.self)
    var n = 0
    while n < length.pointee {
        let result = read(socket, data + n, length.pointee - n)
        if result <= 0 {
            if result == Int(ENOENT) {
                return errSSLClosedGraceful
            }
            if result == Int(ECONNRESET) {
                return errSSLClosedAbort
            }
            return OSStatus(ioErr)
        }
        n += result
    }
    length.pointee = n
    return noErr
}

func sslWrite(_ socketRef: SSLConnectionRef, _ data: UnsafeRawPointer, _ length: UnsafeMutablePointer<Int>) -> OSStatus {
    let socket = socketRef.load(as: Int32.self)
    var n = 0
    while n < length.pointee {
        let result = write(socket, data + n, length.pointee - n)
        if result <= 0 {
            if result == Int(EPIPE) {
                return errSSLClosedAbort
            }
            if result == Int(ECONNRESET) {
                return errSSLClosedAbort
            }
            return OSStatus(ioErr)
        }
        n += result
    }
    length.pointee = n
    return noErr
}

#endif


================================================
FILE: Sources/TerminalCanvas.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

class TerminalCanvas {
    
    var buffer = [UInt8]()
    
    init() {
        self.buffer.reserveCapacity(4_000)
    }
    
    @discardableResult func clear() -> TerminalCanvas {
        self.buffer.removeAll(keepingCapacity: true)
        return self
    }
    
    @discardableResult func cursor(_ x: Int, _ y: Int) -> TerminalCanvas {
        self.buffer.append(contentsOf: "\u{001B}[\(y);\(x)H".utf8)
        return self
    }
    
    @discardableResult func hideCursor() -> TerminalCanvas {
        self.buffer.append(contentsOf: "\u{001B}[?25l".utf8)
        return self
    }
    
    @discardableResult func showCursor() -> TerminalCanvas {
        self.buffer.append(contentsOf: "\u{001B}[?25h".utf8)
        return self
    }
    
    @discardableResult func clean() -> TerminalCanvas {
        buffer.append(contentsOf: "\u{001B}[0m\u{001B}[2J".utf8)
        return self
    }
    
    @discardableResult func color(_ color: Int) -> TerminalCanvas {
        if color < 0 {
            buffer.append(contentsOf: "\u{001B}[39m".utf8)
        } else {
            buffer.append(contentsOf: "\u{001B}[38;5;\(color)m".utf8)
        }
        return self
    }

    @discardableResult func background(_ color: Int) -> TerminalCanvas {
        if color < 0 {
            buffer.append(contentsOf: "\u{001B}[49m".utf8)
        } else {
            buffer.append(contentsOf: "\u{001B}[48;5;\(color)m".utf8)
        }
        return self
    }
    
    @discardableResult func blink(_ flag: Bool) -> TerminalCanvas {
        self.buffer.append(contentsOf: "\u{001B}[\(flag ? "5" : "25")m".utf8)
        return self
    }
    
    @discardableResult func text(_ text: String) -> TerminalCanvas {
        buffer.append(contentsOf: text.utf8)
        return self
    }
    
    @discardableResult func reset() -> TerminalCanvas {
        buffer.append(contentsOf: "\u{001B}[0m".utf8)
        return self
    }
}


================================================
FILE: Sources/TerminalDevice.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

enum ControlKey {
    
    case null
    case ctrlC
    case ctrlD
    case ctrlF
    case ctrlH
    case tab(Bool)
    case cr
    case ctrlL
    case enter
    case ctrlQ
    case ctrlS
    case ctrlU
    case esc
    case backspace
    case arrowUp
    case arrowDown
    case arrowLeft
    case arrowRight
    
    case other(Character)
}

class TerminalDevice {
    
    enum TerminalError: Error {
        case error(String)
    }
    
    private var originalTermios = termios()
    
    init() throws {
        guard tcgetattr(fileno(stdin), &self.originalTermios) == 0 else {
            throw TerminalError.error("Could not load current terminal config: \(errno)")
        }
        try self.terminalEnableRawMode()
        
        self.flush(TerminalCanvas().clean().buffer)
    }

    var size: (width: Int, height: Int) {
        var w = winsize()
        guard ioctl(fileno(stdout), TIOCGWINSZ, &w) == 0 else {
            exit(1)
        }
        return (Int(w.ws_col), Int(w.ws_row))
    }
    
    func key() -> ControlKey {

        let c = getwchar()

        switch c {
            
            case 0: return .null
            case 3: return .ctrlC
            case 4: return .ctrlD
            case 6: return .ctrlF
            case 8: return .ctrlH
            case 9: return .tab(false)
            case 10: return .cr
            case 12: return .ctrlL
            case 13: return .enter
            case 17: return .ctrlQ
            case 19: return .ctrlS
            case 21: return .ctrlU
            
            case 27:
         
                let c1 = getwchar()
                let c2 = getwchar()
                
                if c1 == 91 {
                    switch c2 {
                        case 65: return .arrowUp
                        case 66: return .arrowDown
                        case 68: return .arrowLeft
                        case 67: return .arrowRight
                        case 90: return .tab(true)
                        default: break
                    }
                }
                
                return .esc
                
            case 127: return .backspace
                
            default: return .other(Character(UnicodeScalar(Int(c))!))
        }
    }
    
    func flush(_ buffer: [UInt8]) {
        write(fileno(stdout), buffer, buffer.count)
    }
    
    func reset() throws {
        guard tcsetattr(fileno(stdin), TCSAFLUSH, &self.originalTermios) == 0 else {
            throw TerminalError.error("Could not revert the original mode: \(errno)")
        }
        self.flush(TerminalCanvas().clean().cursor(1, 1).showCursor().buffer)
    }
    
    private func terminalEnableRawMode() throws {
        
        var rawModeTermios = termios()
        
        memcpy(&rawModeTermios, &self.originalTermios, MemoryLayout<termios>.size)
        
        rawModeTermios.c_lflag = UInt(Int32(rawModeTermios.c_lflag)
            
            & (~(ECHO | ECHONL | ICANON | IEXTEN | ISIG)))
        
        rawModeTermios.c_iflag = UInt(Int32(rawModeTermios.c_iflag)
            
            & (~(IGNBRK | BRKINT | INLCR | ICRNL | INPCK | PARMRK | ISTRIP | IXON | IUTF8)))
        
        rawModeTermios.c_cflag = UInt(Int32(rawModeTermios.c_cflag) & CS8)
        rawModeTermios.c_oflag = 0
        
        rawModeTermios.c_cc.17 /*[VTIME]*/ = 0
        rawModeTermios.c_cc.16 /*[VMIN] */ = 1
        
        guard tcsetattr(fileno(stdin), TCSAFLUSH, &rawModeTermios) == 0 else {
            throw TerminalError.error("Could not enable raw mode: \(errno)")
        }
    }
}


================================================
FILE: Sources/TextLayout.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation


struct TextSpan: ExpressibleByStringLiteral {
    
    let text: String
    
    let textColor: Int
    
    let backgroundColor: Int
    
    init(stringLiteral value: String) {
        self.text = value
        self.textColor = R.color.defaulTextColor
        self.backgroundColor = R.color.defaultBgColor
    }
    
    init(extendedGraphemeClusterLiteral value: String) {
        self.text = value
        self.textColor = R.color.defaulTextColor
        self.backgroundColor = R.color.defaultBgColor
    }
    
    init(unicodeScalarLiteral value: String) {
        self.text = value
        self.textColor = R.color.defaulTextColor
        self.backgroundColor = R.color.defaultBgColor
    }
    
    init(_ text: String, withColor: Int = R.color.defaulTextColor, withBackground: Int = R.color.defaultBgColor) {
        self.text = text
        self.textColor = withColor
        self.backgroundColor = withBackground
    }
}

class TextLayout {
    
    let canvas = TerminalCanvas()
    
    func layout(_ spans: [TextSpan], alignToWidth width: Int, highlightColor: Int? = nil) -> [[UInt8]] {
        
        canvas.clear()
        
        var counter = 0
        var lines = [[UInt8]]()
        
        for span in spans {
            
            canvas.background(highlightColor ?? span.backgroundColor)
            canvas.color(span.textColor)
            
            for character in span.text {
                if character == "\n" {
                    canvas.text(String(repeating: " ", count: width - counter))
                    counter = 0
                    lines.append(canvas.buffer)
                    canvas.clear()
                    canvas.background(highlightColor ?? span.backgroundColor)
                    canvas.color(span.textColor)
                } else {
                    canvas.text(String(character))
                    counter = counter + 1
                    if counter == width {
                        counter = 0
                        lines.append(canvas.buffer)
                        canvas.clear()
                        canvas.background(highlightColor ?? span.backgroundColor)
                        canvas.color(span.textColor)
                    }
                }
            
            }
        }
        
        if counter < width {
            canvas.text(String(repeating: " ", count: width - counter))
            lines.append(canvas.buffer)
        }
        
        return lines
    }
    
}


================================================
FILE: Sources/URLSession.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

extension URLSession {

    /// Synchonized version of dataTask(with URLRequest)
    func synchronousDataTask(with request: URLRequest) throws -> (data: Data?, response: HTTPURLResponse?) {
        
        let semaphore = DispatchSemaphore(value: 0)
        
        var data: Data?
        var response: URLResponse?
        var error: Error?
        
        URLSession.shared.dataTask(with: request) { (theData, theResponse, theError) -> Void in
            // extract information from callback
            data = theData
            response = theResponse
            error = theError
            
            // wake semaphore
            semaphore.signal()
            
            }.resume()
        
        // wait until signaled
        _ = semaphore.wait(timeout: .distantFuture)
        
        // do we have an error?
        if let error = error {
            throw error
        }
        
        return (data: data, response: response as! HTTPURLResponse?)
    }
}


================================================
FILE: Sources/UserInputView.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation


class UserInputView {
    
    private let renderer = TerminalCanvas()
    
    private let terminalDevice: TerminalDevice
    
    init(_ device: TerminalDevice) {
        self.terminalDevice = device
    }
    
    var placeholder = R.string.inputPlaceholder
    
    var input = ""
    
    var cursor = 0
    
    func draw() {
        
        let size = self.terminalDevice.size
        
        guard size.width > 0 && size.height > 0 else {
            return
        }
        
        self.renderer
            .clear()
            .hideCursor()
            .cursor(R.dimen.channelsListWidth + 1, size.height - 1)
            .background(R.color.defaultBgColor)
            .color(R.color.channelListBgColor)
            .text(String(repeating: "─", count: size.width-R.dimen.channelsListWidth))
            .cursor(R.dimen.channelsListWidth + 1, size.height)
        
        if self.input.isEmpty {
            self.renderer
                .color(R.color.userInputPlaceholderTextColor)
                .background(R.color.userInputBackgorundColor)
                .text((" " + placeholder).padding(toLength: size.width - R.dimen.channelsListWidth, withPad: " ", startingAt: 0))
                .cursor(R.dimen.channelsListWidth + 2, size.height)
        } else {
            self.renderer
                .color(R.color.userInputTextColor)
                .background(R.color.userInputBackgorundColor)
                .text((" " + input).padding(toLength: size.width - R.dimen.channelsListWidth, withPad: " ", startingAt: 0))
                .cursor(R.dimen.channelsListWidth + 2 + cursor, size.height)
        }
        
        self.renderer.showCursor()
        
        self.terminalDevice.flush(renderer.buffer)
    }
}


================================================
FILE: Sources/Utils.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation


class Utils {
    
    class func shell(_ args: String...) {
        let task = Process()
        task.launchPath = "/usr/bin/env"
        task.arguments = args
        task.launch()
    }
    
    class func xterm256Color(forUser user: SlackUser) -> Int {
        // Slack API provides a True-Color value for every user (example: 4b3a5a). Terminal supports only 256 colors.
        // Instead of using complex alghoritm for finding the closet color from 256 palette, just get modulo 255 value.
        return (Int(user.color, radix: 16) ?? R.color.messageAuthorTextColor) % 255
    }
}

================================================
FILE: Sources/WebSocketClient.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

class WebSocketClient {
    
    enum Err: Error {
        
        case unknownOpCode(String)
        case unMaskedFrame
        case notImplemented(String)
        case invalidFrameLength(String)
        case io(String)
    }
    
    enum OpCode: UInt8 {
        
        case `continue` = 0x00
        case close = 0x08
        case ping = 0x09
        case pong = 0x0A
        case text = 0x01
        case binary = 0x02
    }
    
    struct Frame {
        
        let opcode: OpCode
        let payload: [UInt8]
    }
    
    private let mask: [UInt8]
    private let socket: TLSSocket
    
    private var inputBuffer = [UInt8]()
    
    init(_ host: String, path: String) throws {
        
        self.mask = WebSocketClient.provideRandomValues(4)
        
        self.socket = try TLSSocket(try WebSocketClient.addressForHost(host))
        
        let secWebSocketKey = Data(WebSocketClient.provideRandomValues(16)).base64EncodedString()
        
        let handshakeRequest = [UInt8]((
            "GET \(path)?encoding=text HTTP/1.1\r\n" +
            "Host: \(host)\r\n" +
            "Pragma:no-cache\r\n" +
            "Upgrade: websocket\r\n" +
            "Connection: Upgrade\r\n" +
            "Cache-Control: no-cache\r\n" +
            "Sec-WebSocket-Version: 13\r\n" +
            "Sec-WebSocket-Key: \(secWebSocketKey)\r\n\r\n").utf8)
        
        try self.socket.writeData(handshakeRequest)
        
        //TODO: parse http response in a better way to validate returned Sec-WebSocket-Accept.
        
        skipHeaders: while true {
            let chunk = try self.socket.readData()
            var iteratpr = chunk.makeIterator()
            while let b = iteratpr.next() {
                if b != 13 { inputBuffer.append(b) }
                if inputBuffer.count >= 2 && inputBuffer.last == 10 && inputBuffer[inputBuffer.endIndex - 2] == 10 {
                    inputBuffer.removeAll(keepingCapacity: true)
                    inputBuffer.append(contentsOf: iteratpr)
                    break skipHeaders
                }
            }
        }
    }
    
    func writeFrame(fin: Bool = true, opcode: OpCode, payload: [UInt8] = []) throws  {
        var data = [UInt8]()
        data.append(UInt8(fin ? 0x80 : 0x00) | opcode.rawValue)
        data.append(contentsOf: encodeLengthAndMaskFlag(UInt64(payload.count), mask: self.mask))
        data.append(contentsOf: payload.enumerated().map { item in
            item.element ^ self.mask[item.offset % self.mask.count]
        })
        try self.socket.writeData(data)
    }
    
    private class func provideRandomValues(_ count: Int) -> [UInt8] {
        var result = [UInt8]()
        for _ in 0..<count {
            result.append(UInt8(arc4random() % UInt32(UInt8.max)))
        }
        return result
    }

    private func encodeLengthAndMaskFlag(_ len: UInt64, mask: [UInt8]? = nil) -> [UInt8] {
        let encodedLngth = UInt8(mask != nil ? 0x80 : 0x00)
        var encodedBytes = [UInt8]()
        switch len {
        case 0...125:
            encodedBytes.append(encodedLngth | UInt8(len));
        case 126...UInt64(UINT16_MAX):
            encodedBytes.append(encodedLngth | 0x7E);
            encodedBytes.append(UInt8(len >> 8 & 0xFF));
            encodedBytes.append(UInt8(len >> 0 & 0xFF));
        default:
            encodedBytes.append(encodedLngth | 0x7F);
            encodedBytes.append(UInt8(len >> 56 & 0xFF));
            encodedBytes.append(UInt8(len >> 48 & 0xFF));
            encodedBytes.append(UInt8(len >> 40 & 0xFF));
            encodedBytes.append(UInt8(len >> 32 & 0xFF));
            encodedBytes.append(UInt8(len >> 24 & 0xFF));
            encodedBytes.append(UInt8(len >> 16 & 0xFF));
            encodedBytes.append(UInt8(len >> 08 & 0xFF));
            encodedBytes.append(UInt8(len >> 00 & 0xFF));
        }
        if let mask = mask {
            encodedBytes.append(contentsOf: mask)
        }
        return encodedBytes
    }
    
    func waitForFrame() throws -> Frame? {
    
        // Handle remaining frames after the handshake.
        
        if let frame = try self.lookfForFrame() {
            return frame
        }
        
        inputBuffer.append(contentsOf: try self.socket.readData())
        
        if let frame = try self.lookfForFrame() {
            return frame
        }
        
        return nil
    }
    
    private func lookfForFrame() throws -> Frame? {
        
        guard inputBuffer.count > 1 else { return nil }
        
        let _ /* fin flag */ = inputBuffer[0] & 0x80 != 0
        let opc = inputBuffer[0] & 0x0F
        
        guard let opcode = OpCode(rawValue: opc) else {
            // "If an unknown opcode is received, the receiving endpoint MUST _Fail the WebSocket Connection_."
            // http://tools.ietf.org/html/rfc6455#section-5.2 ( Page 29 )
            throw Err.unknownOpCode("\(opc)")
        }
        
        var offset = 2
        var len = UInt64(0)
        
        switch UInt64(inputBuffer[1] & 0x7F) {
        case let short where short < 0x7E:
            len = short
        case 0x7E:
            guard inputBuffer.count > 3 else { return nil }
            len = UInt64(littleEndian: UInt64(inputBuffer[2]) << 8 | UInt64(inputBuffer[3]))
            offset = 4
        case 0x7F:
            guard inputBuffer.count > 9 else { return nil }
            let byte2 = UInt64(inputBuffer[2]) << 54
            let byte3 = UInt64(inputBuffer[3]) << 48
            let byte4 = UInt64(inputBuffer[4]) << 40
            let byte5 = UInt64(inputBuffer[5]) << 32
            let byte6 = UInt64(inputBuffer[6]) << 24
            let byte7 = UInt64(inputBuffer[7]) << 16
            let byte8 = UInt64(inputBuffer[8]) << 8
            let byte9 = UInt64(inputBuffer[9])
            len = UInt64(littleEndian: byte2 | byte3 | byte4 | byte5 | byte6 | byte7 | byte8 | byte9)
            offset = 10
        default:
            throw Err.invalidFrameLength("Not allowed frame length: \(len)")
        }
        
        let masked = (inputBuffer[1] & 0x80) != 0
        
        guard (len + UInt64(offset) + (masked ? 4 : 0)) <= UInt64(inputBuffer.count) else {
            return nil
        }
        
        if masked {
        
            let mask = [inputBuffer[offset], inputBuffer[offset+1], inputBuffer[offset+2], inputBuffer[offset+3]]
            
            offset = offset + mask.count
            
            let payload = inputBuffer[offset..<(offset + Int(len /* //TODO fix Int64/Int conversion */))]
                .enumerated()
                .map {
                    $0.element ^ mask[Int($0.offset % 4)]
                }
            
            inputBuffer.removeFirst(offset+Int(len))
            
            return Frame(opcode: opcode, payload: payload)
            
        } else {
            
            let payload = [UInt8](inputBuffer[offset..<(offset + Int(len /* //TODO fix Int64/Int conversion */))])
            
            inputBuffer.removeFirst(offset+Int(len))
            
            return Frame(opcode: opcode, payload: payload)
        }
    }
    
    private static func addressForHost(_ host: String) throws -> String {
        guard let info = host.withCString({ gethostbyname($0) }) else {
            throw Err.io("Could not find address for \(host): gethostbyname failed.")
        }
        guard let first = info.pointee.h_addr_list[0] else {
            throw Err.io("Could not find address for \(host): empty list.")
        }
        var buffer = [Int8](repeating: 0, count: 256)
        guard inet_ntop(AF_INET, first, &buffer, socklen_t(buffer.count)) != nil else {
            throw Err.io("Could not find address for \(host): inet_ntop failed \(errno).")
        }
        return String(cString: buffer)
    }
}


================================================
FILE: Sources/main.swift
================================================
//
//  slash
//
//  Copyright © 2016 slash Corp. All rights reserved.
//

import Foundation

setlocale(LC_CTYPE,"UTF-8")

let device = try TerminalDevice()

CrashReporter.watch(usingDevice: device)

var token: String!

if CommandLine.arguments.count > 1 {
    
    token = CommandLine.arguments[1]
    
} else {
    
    device.flush(TerminalCanvas()
        .clean()
        .cursor(1, 1)
        .text(String(format: R.string.authHelpMessage, SlackOAuth2.address)).buffer)
    
    let slackAuthenticator = SlackOAuth2(clientId: "2296647491.109731100693", clientSecret: "db81eea6c974916693ab746775dbc096", permissions: ["client"])
    
    token = try slackAuthenticator.authenticate()
    
    device.flush(TerminalCanvas().clean().buffer)
}

let application = try Application(usingDevice: device, authenticatedBy: token)

signal(SIGWINCH) { _ in
    application.notifyTerminalSizeHasChanged()
}

application.run()



================================================
FILE: slash.rb
================================================
class Slash < Formula
  desc "Slack terminal client written in Swift."
  homepage "https://github.com/slash-hq/slash"
  url "https://github.com/slash-hq/slash/archive/0.1.0.tar.gz"
  sha256 "8a709579ffba7c47b1e1975bb418d72ecbd542539d4cd6f7a72d876808bfbdb2"

  depends_on :xcode
  def install
    xcodebuild "-workspace", "slash.xcodeproj/project.xcworkspace", "-derivedDataPath", "prefix.to_s", "-configuration", "Release", "-scheme", "slash", "SYMROOT=#{prefix}/Build"
    bin.install(prefix + "Build/Release/slash")
  end

  test do
    system "false"
  end
end


================================================
FILE: slash.sublime-project
================================================
{
  "build_systems": [
    {
      "shell_cmd": "swift build -v",
      "name": "Sublime SPM Build for Swift."
    }
  ],
  "folders": [
    {
      "path": ".",
      "follow_symlinks": true
    }
  ]
}

================================================
FILE: slash.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
	archiveVersion = 1;
	classes = {
	};
	objectVersion = 46;
	objects = {

/* Begin PBXBuildFile section */
		2DB32B79220D933300D23E57 /* SlackMessageReaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DB32B78220D933300D23E57 /* SlackMessageReaction.swift */; };
		7C92EB571E03F3C900F92267 /* TerminalCanvas.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB541E03F3C900F92267 /* TerminalCanvas.swift */; };
		7C92EB581E03F3C900F92267 /* TerminalDevice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB551E03F3C900F92267 /* TerminalDevice.swift */; };
		7C92EB591E03F3C900F92267 /* TextLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB561E03F3C900F92267 /* TextLayout.swift */; };
		7C92EB651E03F3ED00F92267 /* Application.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB5A1E03F3ED00F92267 /* Application.swift */; };
		7C92EB661E03F3ED00F92267 /* ChannelsListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB5B1E03F3ED00F92267 /* ChannelsListView.swift */; };
		7C92EB671E03F3ED00F92267 /* CrashReporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB5C1E03F3ED00F92267 /* CrashReporter.swift */; };
		7C92EB681E03F3ED00F92267 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB5D1E03F3ED00F92267 /* main.swift */; };
		7C92EB691E03F3ED00F92267 /* MessagesListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB5E1E03F3ED00F92267 /* MessagesListView.swift */; };
		7C92EB6A1E03F3ED00F92267 /* R.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB5F1E03F3ED00F92267 /* R.swift */; };
		7C92EB6B1E03F3ED00F92267 /* Server.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB601E03F3ED00F92267 /* Server.swift */; };
		7C92EB6C1E03F3ED00F92267 /* SlackAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB611E03F3ED00F92267 /* SlackAdapter.swift */; };
		7C92EB6D1E03F3ED00F92267 /* SlackContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB621E03F3ED00F92267 /* SlackContext.swift */; };
		7C92EB6E1E03F3ED00F92267 /* UserInputView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB631E03F3ED00F92267 /* UserInputView.swift */; };
		7C92EB6F1E03F3ED00F92267 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB641E03F3ED00F92267 /* Utils.swift */; };
		7C92EB7D1E03F3FC00F92267 /* SlackChannel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB701E03F3FC00F92267 /* SlackChannel.swift */; };
		7C92EB7E1E03F3FC00F92267 /* SlackEmojiDecoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB711E03F3FC00F92267 /* SlackEmojiDecoder.swift */; };
		7C92EB7F1E03F3FC00F92267 /* SlackEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB721E03F3FC00F92267 /* SlackEvent.swift */; };
		7C92EB801E03F3FC00F92267 /* SlackGroup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB731E03F3FC00F92267 /* SlackGroup.swift */; };
		7C92EB811E03F3FC00F92267 /* SlackIM.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB741E03F3FC00F92267 /* SlackIM.swift */; };
		7C92EB821E03F3FC00F92267 /* SlackMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB751E03F3FC00F92267 /* SlackMessage.swift */; };
		7C92EB831E03F3FC00F92267 /* SlackOAuth2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB761E03F3FC00F92267 /* SlackOAuth2.swift */; };
		7C92EB841E03F3FC00F92267 /* SlackRealTimeClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB771E03F3FC00F92267 /* SlackRealTimeClient.swift */; };
		7C92EB851E03F3FC00F92267 /* SlackTeam.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB781E03F3FC00F92267 /* SlackTeam.swift */; };
		7C92EB861E03F3FC00F92267 /* SlackUser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB791E03F3FC00F92267 /* SlackUser.swift */; };
		7C92EB871E03F3FC00F92267 /* SlackWebClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB7A1E03F3FC00F92267 /* SlackWebClient.swift */; };
		7C92EB881E03F3FC00F92267 /* TLSSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB7B1E03F3FC00F92267 /* TLSSocket.swift */; };
		7C92EB891E03F3FC00F92267 /* WebSocketClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB7C1E03F3FC00F92267 /* WebSocketClient.swift */; };
		7C9FE5F11E18F9B900FB8166 /* Socket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C9FE5F01E18F9B900FB8166 /* Socket.swift */; };
		D42C5DF71E156BEE008CDA3C /* URLSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = D42C5DF61E156BEE008CDA3C /* URLSession.swift */; };
/* End PBXBuildFile section */

/* Begin PBXCopyFilesBuildPhase section */
		7CBB81F01DC12E8B00DC0334 /* CopyFiles */ = {
			isa = PBXCopyFilesBuildPhase;
			buildActionMask = 2147483647;
			dstPath = /usr/share/man/man1/;
			dstSubfolderSpec = 0;
			files = (
			);
			runOnlyForDeploymentPostprocessing = 1;
		};
/* End PBXCopyFilesBuildPhase section */

/* Begin PBXFileReference section */
		2DB32B78220D933300D23E57 /* SlackMessageReaction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackMessageReaction.swift; path = Sources/SlackMessageReaction.swift; sourceTree = SOURCE_ROOT; };
		7C92EB541E03F3C900F92267 /* TerminalCanvas.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = TerminalCanvas.swift; path = Sources/TerminalCanvas.swift; sourceTree = SOURCE_ROOT; };
		7C92EB551E03F3C900F92267 /* TerminalDevice.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = TerminalDevice.swift; path = Sources/TerminalDevice.swift; sourceTree = SOURCE_ROOT; };
		7C92EB561E03F3C900F92267 /* TextLayout.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = TextLayout.swift; path = Sources/TextLayout.swift; sourceTree = SOURCE_ROOT; };
		7C92EB5A1E03F3ED00F92267 /* Application.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Application.swift; path = Sources/Application.swift; sourceTree = SOURCE_ROOT; };
		7C92EB5B1E03F3ED00F92267 /* ChannelsListView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ChannelsListView.swift; path = Sources/ChannelsListView.swift; sourceTree = SOURCE_ROOT; };
		7C92EB5C1E03F3ED00F92267 /* CrashReporter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = CrashReporter.swift; path = Sources/CrashReporter.swift; sourceTree = SOURCE_ROOT; };
		7C92EB5D1E03F3ED00F92267 /* main.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = main.swift; path = Sources/main.swift; sourceTree = SOURCE_ROOT; };
		7C92EB5E1E03F3ED00F92267 /* MessagesListView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MessagesListView.swift; path = Sources/MessagesListView.swift; sourceTree = SOURCE_ROOT; };
		7C92EB5F1E03F3ED00F92267 /* R.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = R.swift; path = Sources/R.swift; sourceTree = SOURCE_ROOT; };
		7C92EB601E03F3ED00F92267 /* Server.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Server.swift; path = Sources/Server.swift; sourceTree = SOURCE_ROOT; };
		7C92EB611E03F3ED00F92267 /* SlackAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackAdapter.swift; path = Sources/SlackAdapter.swift; sourceTree = SOURCE_ROOT; };
		7C92EB621E03F3ED00F92267 /* SlackContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackContext.swift; path = Sources/SlackContext.swift; sourceTree = SOURCE_ROOT; };
		7C92EB631E03F3ED00F92267 /* UserInputView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = UserInputView.swift; path = Sources/UserInputView.swift; sourceTree = SOURCE_ROOT; };
		7C92EB641E03F3ED00F92267 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Utils.swift; path = Sources/Utils.swift; sourceTree = SOURCE_ROOT; };
		7C92EB701E03F3FC00F92267 /* SlackChannel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackChannel.swift; path = Sources/SlackChannel.swift; sourceTree = SOURCE_ROOT; };
		7C92EB711E03F3FC00F92267 /* SlackEmojiDecoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackEmojiDecoder.swift; path = Sources/SlackEmojiDecoder.swift; sourceTree = SOURCE_ROOT; };
		7C92EB721E03F3FC00F92267 /* SlackEvent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackEvent.swift; path = Sources/SlackEvent.swift; sourceTree = SOURCE_ROOT; };
		7C92EB731E03F3FC00F92267 /* SlackGroup.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackGroup.swift; path = Sources/SlackGroup.swift; sourceTree = SOURCE_ROOT; };
		7C92EB741E03F3FC00F92267 /* SlackIM.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackIM.swift; path = Sources/SlackIM.swift; sourceTree = SOURCE_ROOT; };
		7C92EB751E03F3FC00F92267 /* SlackMessage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackMessage.swift; path = Sources/SlackMessage.swift; sourceTree = SOURCE_ROOT; };
		7C92EB761E03F3FC00F92267 /* SlackOAuth2.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackOAuth2.swift; path = Sources/SlackOAuth2.swift; sourceTree = SOURCE_ROOT; };
		7C92EB771E03F3FC00F92267 /* SlackRealTimeClient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackRealTimeClient.swift; path = Sources/SlackRealTimeClient.swift; sourceTree = SOURCE_ROOT; };
		7C92EB781E03F3FC00F92267 /* SlackTeam.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackTeam.swift; path = Sources/SlackTeam.swift; sourceTree = SOURCE_ROOT; };
		7C92EB791E03F3FC00F92267 /* SlackUser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackUser.swift; path = Sources/SlackUser.swift; sourceTree = SOURCE_ROOT; };
		7C92EB7A1E03F3FC00F92267 /* SlackWebClient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackWebClient.swift; path = Sources/SlackWebClient.swift; sourceTree = SOURCE_ROOT; };
		7C92EB7B1E03F3FC00F92267 /* TLSSocket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = TLSSocket.swift; path = Sources/TLSSocket.swift; sourceTree = SOURCE_ROOT; };
		7C92EB7C1E03F3FC00F92267 /* WebSocketClient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WebSocketClient.swift; path = Sources/WebSocketClient.swift; sourceTree = SOURCE_ROOT; };
		7C9FE5F01E18F9B900FB8166 /* Socket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Socket.swift; path = Sources/Socket.swift; sourceTree = SOURCE_ROOT; };
		7CBB81F21DC12E8B00DC0334 /* slash */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = slash; sourceTree = BUILT_PRODUCTS_DIR; };
		D42C5DF61E156BEE008CDA3C /* URLSession.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileTyp
Download .txt
gitextract_itntp5kx/

├── .gitignore
├── GitHub/
│   ├── scr.pxm
│   ├── slash_logo.pxm
│   └── slash_logo_small.pxm
├── LICENSE
├── Package.swift
├── README.md
├── Sources/
│   ├── Application.swift
│   ├── ChannelsListView.swift
│   ├── CrashReporter.swift
│   ├── MessagesListView.swift
│   ├── R.swift
│   ├── Server.swift
│   ├── SlackAdapter.swift
│   ├── SlackChannel.swift
│   ├── SlackContext.swift
│   ├── SlackEmojiDecoder.swift
│   ├── SlackEvent.swift
│   ├── SlackGroup.swift
│   ├── SlackIM.swift
│   ├── SlackMessage.swift
│   ├── SlackMessageReaction.swift
│   ├── SlackOAuth2.swift
│   ├── SlackRealTimeClient.swift
│   ├── SlackTeam.swift
│   ├── SlackUser.swift
│   ├── SlackWebClient.swift
│   ├── Socket.swift
│   ├── TLSSocket.swift
│   ├── TerminalCanvas.swift
│   ├── TerminalDevice.swift
│   ├── TextLayout.swift
│   ├── URLSession.swift
│   ├── UserInputView.swift
│   ├── Utils.swift
│   ├── WebSocketClient.swift
│   └── main.swift
├── slash.rb
├── slash.sublime-project
└── slash.xcodeproj/
    ├── project.pbxproj
    ├── project.xcworkspace/
    │   └── contents.xcworkspacedata
    └── xcshareddata/
        └── xcschemes/
            └── slash.xcscheme
Download .txt
SYMBOL INDEX (2 symbols across 1 files)

FILE: slash.rb
  class Slash (line 1) | class Slash < Formula
    method install (line 8) | def install
Condensed preview — 42 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (229K chars).
[
  {
    "path": ".gitignore",
    "chars": 494,
    "preview": "## Build generated\nbuild/\nDerivedData/\n\n## Various settings\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode"
  },
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "Package.swift",
    "chars": 218,
    "preview": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"slash\",\n    products: [.executab"
  },
  {
    "path": "README.md",
    "chars": 1412,
    "preview": "<img src=\"GitHub/slash_logo_small.png\" alt=\"logo\" width=\"200px;\"/>\n\nSlack terminal client.\n\n</br>\n\n![screenshot](GitHub/"
  },
  {
    "path": "Sources/Application.swift",
    "chars": 13358,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nclass Application {\n    \n  "
  },
  {
    "path": "Sources/ChannelsListView.swift",
    "chars": 3949,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\n\nimport Foundation\n\nstruct ChannelListRow {\n  "
  },
  {
    "path": "Sources/CrashReporter.swift",
    "chars": 1944,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\n\nstruct CrashReporter {\n   "
  },
  {
    "path": "Sources/MessagesListView.swift",
    "chars": 2602,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nstruct MessagesListRow {\n  "
  },
  {
    "path": "Sources/R.swift",
    "chars": 3067,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nclass R {\n    \n    class st"
  },
  {
    "path": "Sources/Server.swift",
    "chars": 22902,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nclass Request {\n    \n    en"
  },
  {
    "path": "Sources/SlackAdapter.swift",
    "chars": 6347,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\n\nimport Foundation\n\nclass SlackAdapter {\n    \n"
  },
  {
    "path": "Sources/SlackChannel.swift",
    "chars": 255,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nstruct SlackChannel {\n    \n"
  },
  {
    "path": "Sources/SlackContext.swift",
    "chars": 2922,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\n\nclass SlackContext {\n    \n"
  },
  {
    "path": "Sources/SlackEmojiDecoder.swift",
    "chars": 68708,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nclass SlackEmojiDecoder {\n "
  },
  {
    "path": "Sources/SlackEvent.swift",
    "chars": 791,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nenum SlackEvent {\n    \n    "
  },
  {
    "path": "Sources/SlackGroup.swift",
    "chars": 208,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nstruct SlackGroup {\n    \n  "
  },
  {
    "path": "Sources/SlackIM.swift",
    "chars": 157,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nstruct SlackIM {\n    \n    l"
  },
  {
    "path": "Sources/SlackMessage.swift",
    "chars": 255,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nstruct SlackMessage {\n    \n"
  },
  {
    "path": "Sources/SlackMessageReaction.swift",
    "chars": 262,
    "preview": "//\n//  SlackMessageReaction.swift\n//  slash\n//\n//  Created by damian on 08.02.2019.\n//  Copyright © 2019 kolakowski. All"
  },
  {
    "path": "Sources/SlackOAuth2.swift",
    "chars": 3252,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nenum SlackOAuth2Error: Erro"
  },
  {
    "path": "Sources/SlackRealTimeClient.swift",
    "chars": 5824,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\n\nclass SlackRealTimeClient "
  },
  {
    "path": "Sources/SlackTeam.swift",
    "chars": 299,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\n\nimport Foundation\n\nstruct SlackTeam {\n    \n  "
  },
  {
    "path": "Sources/SlackUser.swift",
    "chars": 266,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\n\nstruct SlackUser {\n    \n  "
  },
  {
    "path": "Sources/SlackWebClient.swift",
    "chars": 6352,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\n\nimport Foundation\n\nenum SlackWebClientError: "
  },
  {
    "path": "Sources/Socket.swift",
    "chars": 778,
    "preview": "#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)\n\timport Darwin\n#elseif os(Linux)\n\timport Glibc\n#endif\n\nstruct Socket"
  },
  {
    "path": "Sources/TLSSocket.swift",
    "chars": 4023,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\n#if os(OSX) || os(iOS)\n\nenu"
  },
  {
    "path": "Sources/TerminalCanvas.swift",
    "chars": 2008,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nclass TerminalCanvas {\n    "
  },
  {
    "path": "Sources/TerminalDevice.swift",
    "chars": 3673,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nenum ControlKey {\n    \n    "
  },
  {
    "path": "Sources/TextLayout.swift",
    "chars": 2570,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\n\nstruct TextSpan: Expressib"
  },
  {
    "path": "Sources/URLSession.swift",
    "chars": 1077,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nextension URLSession {\n\n   "
  },
  {
    "path": "Sources/UserInputView.swift",
    "chars": 1832,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\n\nclass UserInputView {\n    "
  },
  {
    "path": "Sources/Utils.swift",
    "chars": 680,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\n\nclass Utils {\n    \n    cla"
  },
  {
    "path": "Sources/WebSocketClient.swift",
    "chars": 7902,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nclass WebSocketClient {\n   "
  },
  {
    "path": "Sources/main.swift",
    "chars": 919,
    "preview": "//\n//  slash\n//\n//  Copyright © 2016 slash Corp. All rights reserved.\n//\n\nimport Foundation\n\nsetlocale(LC_CTYPE,\"UTF-8\")"
  },
  {
    "path": "slash.rb",
    "chars": 564,
    "preview": "class Slash < Formula\n  desc \"Slack terminal client written in Swift.\"\n  homepage \"https://github.com/slash-hq/slash\"\n  "
  },
  {
    "path": "slash.sublime-project",
    "chars": 203,
    "preview": "{\n  \"build_systems\": [\n    {\n      \"shell_cmd\": \"swift build -v\",\n      \"name\": \"Sublime SPM Build for Swift.\"\n    }\n  ]"
  },
  {
    "path": "slash.xcodeproj/project.pbxproj",
    "chars": 24322,
    "preview": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 46;\n\tobjects = {\n\n/* Begin PBXBuildFile section *"
  },
  {
    "path": "slash.xcodeproj/project.xcworkspace/contents.xcworkspacedata",
    "chars": 135,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef"
  },
  {
    "path": "slash.xcodeproj/xcshareddata/xcschemes/slash.xcscheme",
    "chars": 3263,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Scheme\n   LastUpgradeVersion = \"1000\"\n   version = \"1.3\">\n   <BuildAction\n      "
  }
]

// ... and 3 more files (download for full content)

About this extraction

This page contains the full source code of the slash-hq/slash GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 42 files (206.2 KB), approximately 54.1k tokens, and a symbol index with 2 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!