[
  {
    "path": ".dockerignore",
    "content": ".git/**/*\nassets/**/*\nbenchmark/**/*\nbuild/**/*\ncoverage/**/*\ndist/**/*\nnode_modules/**/*\ntests/**/*\n.env\nnpm-debug.log\nyarn.lock\n*.db\n"
  },
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*]\ncharset = utf-8\nend_of_line = lf\ninsert_final_newline = true\nindent_style = space\nindent_size = 4\ntrim_trailing_whitespace = true\n\n[*.md]\ntrim_trailing_whitespace = false\n\n[*.{yml,yaml,json}]\nindent_size = 2\n"
  },
  {
    "path": ".eslintrc.js",
    "content": "module.exports = {\n    root: true,\n    env: {\n        browser: true,\n        jest: true,\n        node: true,\n    },\n    parser: \"@typescript-eslint/parser\",\n    plugins: [\"@typescript-eslint\"],\n    extends: [\"eslint:recommended\", \"plugin:@typescript-eslint/recommended\"],\n    rules: {\n        \"@typescript-eslint/ban-ts-comment\": \"off\",\n        \"@typescript-eslint/ban-types\": \"off\",\n        \"@typescript-eslint/explicit-module-boundary-types\": \"off\",\n        \"@typescript-eslint/no-explicit-any\": \"off\",\n        \"@typescript-eslint/no-unused-vars\": \"off\",\n        \"@typescript-eslint/no-var-requires\": \"off\",\n        \"prefer-const\": \"off\",\n    },\n};\n"
  },
  {
    "path": ".gitattributes",
    "content": "* text=auto\n\n/.github export-ignore\n/tests export-ignore\n.editorconfig export-ignore\n.gitattributes export-ignore\n.gitignore export-ignore\n.npmignore export-ignore\n.styleci.yml export-ignore\nCHANGELOG.md export-ignore"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "github: rennokki\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug-report---.md",
    "content": "---\nname: \"Bug Report \\U0001F41E\"\nabout: Report a bug. This is NOT for other versions of Soketi. Use the Discussions board for Cloudflare Serverless.\ntitle: \"[BUG] \"\nlabels:\n  - status:triage\nassignees:\n  - rennokki\n\n---\n\n<!---\nNOTICE: Keep in mind that bugs that state simple usage disfunctionalities (i.e. message did not get sent) are more likely to be your fault for not using the Pusher properly.\n\nAfter enabling debugging with SOKETI_DEBUG=1, make sure to read the console to see if the message is actually being sent to the server.\n-->\n\n**Description**\nA clear and concise description of what the bug is.\n\n**Reproduction steps**\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Environment**\n- Soketi version (i.e. 1.3.0): \n- Adapter (local, redis): local\n- App Manager (array, mysql, postgres, dynamodb) : array\n- Queue (sqs, redis, sync): sync\n- Cache Managers (memory, redis): memory\n\n**Configuration**\nRun the server with `SOKETI_DEBUG=1` and paste the nested object configuration that outputs:\n```js\n{\n    //\n}\n```\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature-request-🚀.md",
    "content": "---\nname: \"Feature request \\U0001F680\"\nabout: Suggest an idea for this project\ntitle: \"[REQUEST]\"\nlabels: ''\nassignees: rennokki\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nregistries:\n  quay:\n    type: docker-registry\n    url: quay.io\n    username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}\n    password: ${{ secrets.DOCKER_REGISTRY_TOKEN }}\nupdates:\n  - package-ecosystem: github-actions\n    directory: \"/\"\n    groups:\n      all:\n        patterns: [\"*\"]\n    schedule:\n      interval: weekly\n    open-pull-requests-limit: 100\n    rebase-strategy: auto\n    reviewers:\n      - rennokki\n    labels:\n      - dependabot:actions\n      - auto:dependabot\n      - dependencies\n\n  - package-ecosystem: npm\n    directory: \"/\"\n    groups:\n      typescript:\n        patterns:\n          - \"@babel/*\"\n          - \"@types/*\"\n          - \"eslint\"\n          - typescript\n          - \"@typescript*\"\n          - \"ts*\"\n          - \"*ts\"\n          - \"jest\"\n          - \"jest*\"\n          - \"*jest\"\n        exclude-patterns:\n          - \"@types/pusher*\"\n      dev-utils:\n        patterns:\n          - \"body-parser\"\n          - \"express\"\n          - \"tcp-port-used\"\n      databases:\n        patterns:\n          - \"knex\"\n          - \"ioredis\"\n          - \"mysql*\"\n          - \"pg\"\n      utils:\n        patterns:\n          - \"arraybuffer-to-string\"\n          - \"async\"\n          - \"boolean\"\n          - \"colors\"\n          - \"dot*\"\n          - \"query-string\"\n          - \"uuid\"\n      ws:\n        patterns:\n          - \"uWebSockets.js\"\n          - \"pusher*\"\n    schedule:\n      interval: weekly\n    open-pull-requests-limit: 100\n    rebase-strategy: auto\n    reviewers:\n      - rennokki\n    labels:\n      - dependabot:npm\n      - auto:dependabot\n      - dependencies\n    versioning-strategy: auto\n\n  - package-ecosystem: docker\n    directory: \"/\"\n    registries:\n      - quay\n    schedule:\n      interval: weekly\n    open-pull-requests-limit: 100\n    rebase-strategy: auto\n    reviewers:\n      - rennokki\n    labels:\n      - dependabot:docker\n      - auto:dependabot\n      - dependencies\n"
  },
  {
    "path": ".github/stale.yml",
    "content": "# Number of days of inactivity before an issue becomes stale\ndaysUntilStale: 29\n# Number of days of inactivity before a stale issue is closed\ndaysUntilClose: 1\n# Issues with these labels will never be considered stale\nexemptLabels:\n  - pinned\n  - security\n# Label to use when marking an issue as stale\nstaleLabel: wontfix\n# Comment to post when marking an issue as stale. Set to `false` to disable\nmarkComment: false\n# Comment to post when closing a stale issue. Set to `false` to disable\ncloseComment: >\n  This issue has been automatically closed because it has not had any recent activity. 😨\n"
  },
  {
    "path": ".github/workflows/benchmark.yml",
    "content": "name: Benchmark\n\non:\n  workflow_run:\n    workflows:\n      - \"CI\"\n    types:\n      - completed\n\njobs:\n  build:\n    if: \"!contains(github.event.head_commit.message, 'skip ci')\"\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      fail-fast: false\n\n      matrix:\n        node:\n          - 16.x\n        adapter:\n          - local\n          - redis\n          - cluster\n          - nats\n        app_manager:\n          - array\n          - mysql\n          - postgres\n          - dynamodb\n\n        include:\n          - adapter: local\n            rate_limiter: local\n            queue_driver: sync\n            cache_driver: memory\n          - adapter: local\n            rate_limiter: local\n            queue_driver: sqs\n            cache_driver: memory\n          - adapter: cluster\n            rate_limiter: cluster\n            queue_driver: sync\n            cache_driver: redis\n          - adapter: redis\n            rate_limiter: redis\n            queue_driver: redis\n            cache_driver: redis\n          - adapter: nats\n            rate_limiter: redis\n            queue_driver: sync\n            cache_driver: redis\n\n    name: Node.js ${{ matrix.node }} (adapter:${{ matrix.adapter }} manager:${{ matrix.app_manager }} ratelimiter:${{ matrix.rate_limiter }} queue:${{ matrix.queue_driver }})\n\n    steps:\n      - uses: actions/checkout@v4.1.0\n\n      - uses: actions/setup-node@v3.8.1\n        name: Installing Node.js v${{ matrix.node }}\n        with:\n          node-version: ${{ matrix.node }}\n\n      - uses: actions/cache@v3.3.2\n        name: Cache npm dependencies\n        with:\n          path: node_modules\n          key: npm-${{ hashFiles('package-lock.json') }}\n\n      - name: Install dependencies\n        run: npm ci\n\n      - name: Execute lint & build\n        run: |\n          npm run lint\n          npm run build\n\n      - name: Setup PHP\n        uses: shivammathur/setup-php@2.26.0\n        with:\n          php-version: \"8.0\"\n          extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, yaml\n          coverage: pcov\n\n      - uses: actions/cache@v3.3.2\n        name: Cache Composer dependencies\n        with:\n          path: ~/.composer/cache/files\n          key: composer-php-${{ hashFiles('benchmark/composer.json') }}\n\n      - name: Setup message sender\n        run: |\n          cd benchmark/\n          composer install --no-interaction --no-progress --prefer-dist --optimize-autoloader\n\n      - name: Setup k6\n        run: |\n          sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys C5AD17C747E3415A3642D57D77C6C491D6AC1D69\n          echo \"deb https://dl.k6.io/deb stable main\" | sudo tee /etc/apt/sources.list.d/k6.list\n          sudo apt-get update\n          sudo apt-get install k6\n\n      - name: Setup Redis\n        if: \"matrix.adapter == 'redis' || matrix.adapter == 'cluster' || matrix.adapter == 'nats'\"\n        run: docker run -p 6379:6379 redis:6-alpine &\n\n      # Setup MySQL with user `root`, password `root` and database `testing`\n      - name: Setup MySQL\n        if: \"matrix.app_manager == 'mysql'\"\n        run: |\n          sudo systemctl start mysql.service\n          mysql -e 'CREATE DATABASE testing;' -u root -proot\n          mysql -u root -proot --database=testing < tests/fixtures/mysql_schema.sql\n\n      # Setup PostgreSQL with user `testing`, password `testing` and database `testing`\n      - name: Setup PostgreSQL\n        if: \"matrix.app_manager == 'postgres'\"\n        run: |\n          sudo systemctl start postgresql.service\n          pg_isready\n          sudo -u postgres psql --command=\"CREATE USER testing PASSWORD 'testing'\"\n          sudo -u postgres createdb --owner=postgres testing\n          psql --host=127.0.0.1 --username=testing testing < tests/fixtures/postgres_schema.sql\n        env:\n          PGPASSWORD: testing\n\n      - name: Setup DynamoDB\n        if: \"matrix.app_manager == 'dynamodb'\"\n        run: |\n          docker run -p 8000:8000 amazon/dynamodb-local:1.22.0 &\n          node tests/fixtures/dynamodb_schema.js\n        env:\n          AWS_ACCESS_KEY_ID: fake-id\n          AWS_SECRET_ACCESS_KEY: fake-secret\n\n      - name: Setup Localstack\n        if: \"matrix.queue_driver == 'sqs'\"\n        run: |\n          docker-compose up -d localstack\n          docker-compose run initialize_sqs\n\n      - name: Setup NATS\n        if: \"matrix.adapter == 'nats'\"\n        run: |\n          docker run -d \\\n            -p 4222:4222 \\\n            -p 6222:6222 \\\n            -p 8222:8222 \\\n            nats --jetstream --user=\"\" --pass=\"\"\n\n      - name: Run Soketi (port 6001)\n        run: |\n          node bin/server.js start &\n          timeout 30 bash -c 'while [[ \"$(curl -s -o /dev/null -w ''%{http_code}'' http://127.0.0.1:6001/ready)\" != \"200\" ]]; do echo \"Waiting for server to be ready...\"; sleep 5; done' || false\n        env:\n          SOKETI_PORT: 6001\n          SOKETI_ADAPTER_DRIVER: ${{ matrix.adapter }}\n          SOKETI_CACHE_DRIVER: ${{ matrix.cache_driver }}\n          SOKETI_APP_MANAGER_DRIVER: ${{ matrix.app_manager }}\n          SOKETI_APP_MANAGER_DYNAMODB_ENDPOINT: http://127.0.0.1:8000\n          SOKETI_APP_MANAGER_MYSQL_USE_V2: true\n          SOKETI_METRICS_ENABLED: true\n          SOKETI_QUEUE_DRIVER: ${{ matrix.queue_driver }}\n          SOKETI_QUEUE_SQS_URL: http://localhost:4566/000000000000/test.fifo\n          SOKETI_RATE_LIMITER_DRIVER: ${{ matrix.rate_limiter }}\n          AWS_ACCESS_KEY_ID: fake-id\n          AWS_SECRET_ACCESS_KEY: fake-secret\n          SOKETI_DB_MYSQL_USERNAME: root\n          SOKETI_DB_MYSQL_PASSWORD: root\n\n      - name: Run Soketi (port 6002)\n        if: \"matrix.adapter == 'redis' || matrix.adapter == 'cluster' || matrix.adapter == 'nats'\"\n        run: |\n          node bin/server.js start &\n          timeout 30 bash -c 'while [[ \"$(curl -s -o /dev/null -w ''%{http_code}'' http://127.0.0.1:6002/ready)\" != \"200\" ]]; do echo \"Waiting for server to be ready...\"; sleep 5; done' || false\n        env:\n          SOKETI_PORT: 6002\n          SOKETI_ADAPTER_DRIVER: ${{ matrix.adapter }}\n          SOKETI_CACHE_DRIVER: ${{ matrix.cache_driver }}\n          SOKETI_APP_MANAGER_DRIVER: ${{ matrix.app_manager }}\n          SOKETI_APP_MANAGER_DYNAMODB_ENDPOINT: http://127.0.0.1:8000\n          SOKETI_APP_MANAGER_MYSQL_USE_V2: true\n          SOKETI_METRICS_ENABLED: true\n          SOKETI_QUEUE_DRIVER: ${{ matrix.queue_driver }}\n          SOKETI_QUEUE_SQS_URL: http://localhost:4566/000000000000/test.fifo\n          SOKETI_RATE_LIMITER_DRIVER: ${{ matrix.rate_limiter }}\n          AWS_ACCESS_KEY_ID: fake-id\n          AWS_SECRET_ACCESS_KEY: fake-secret\n          SOKETI_DB_MYSQL_USERNAME: root\n          SOKETI_DB_MYSQL_PASSWORD: root\n\n      - name: Run message sender (port 6001)\n        run: ./benchmark/send --interval 1 --port 6001 &\n\n      - name: Run message sender (port 6002)\n        if: \"matrix.adapter == 'redis' || matrix.adapter == 'cluster' || matrix.adapter == 'nats'\"\n        run: ./benchmark/send --interval 1 --port 6002 &\n\n      - name: Execute benchmarks (single nodes)\n        if: \"matrix.adapter == 'local'\"\n        run: k6 run benchmark/ci-local.js\n        env:\n          ADAPTER_DRIVER: ${{ matrix.adapter }}\n          CACHE_DRIVER: ${{ matrix.cache_driver }}\n          APP_MANAGER_DRIVER: ${{ matrix.app_manager }}\n          QUEUE_DRIVER: ${{ matrix.queue_driver }}\n          RATE_LIMITER_DRIVER: ${{ matrix.rate_limiter }}\n\n      - name: Execute benchmarks (multiple nodes)\n        if: \"matrix.adapter == 'redis' || matrix.adapter == 'cluster' || matrix.adapter == 'nats'\"\n        run: k6 run benchmark/ci-horizontal.js\n        env:\n          ADAPTER_DRIVER: ${{ matrix.adapter }}\n          CACHE_DRIVER: ${{ matrix.cache_driver }}\n          APP_MANAGER_DRIVER: ${{ matrix.app_manager }}\n          QUEUE_DRIVER: ${{ matrix.queue_driver }}\n          RATE_LIMITER_DRIVER: ${{ matrix.rate_limiter }}\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\n\non:\n  push:\n    branches:\n      - '*'\n    tags:\n      - '*'\n    paths-ignore:\n      - \"**.md\"\n  pull_request:\n    branches:\n      - '*'\n\njobs:\n  build:\n    if: \"!contains(github.event.head_commit.message, 'skip ci')\"\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      fail-fast: false\n\n      matrix:\n        node:\n          - 16.x\n        adapter:\n          - local\n          - redis\n          - cluster\n          - nats\n        app_manager:\n          - array\n          - mysql\n          - postgres\n          - dynamodb\n\n        include:\n          - adapter: local\n            rate_limiter: local\n            queue_driver: sync\n            cache_driver: memory\n          - adapter: local\n            rate_limiter: local\n            queue_driver: sqs\n            cache_driver: memory\n          - adapter: cluster\n            rate_limiter: cluster\n            queue_driver: sync\n            cache_driver: redis\n          - adapter: redis\n            rate_limiter: redis\n            queue_driver: redis\n            cache_driver: redis\n          - adapter: nats\n            rate_limiter: redis\n            queue_driver: sync\n            cache_driver: redis\n\n    name: Node.js ${{ matrix.node }} (adapter:${{ matrix.adapter }} manager:${{ matrix.app_manager }} ratelimiter:${{ matrix.rate_limiter }} queue:${{ matrix.queue_driver }})\n\n    steps:\n      - uses: actions/checkout@v4.1.0\n\n      - uses: actions/setup-node@v3.8.1\n        name: Setup Node.js v${{ matrix.node }}\n        with:\n          node-version: ${{ matrix.node }}\n\n      - name: Install dependencies\n        run: npm install\n\n      - name: Execute lint & build\n        run: |\n          npm run lint\n          npm run build\n\n      - name: Setup Redis\n        if: \"matrix.adapter == 'redis' || matrix.adapter == 'cluster' || matrix.adapter == 'nats'\"\n        run: docker run -p 6379:6379 redis:6-alpine &\n\n      # Setup MySQL with user `root`, password `root` and database `testing`\n      - name: Setup MySQL\n        if: \"matrix.app_manager == 'mysql'\"\n        run: |\n          sudo systemctl start mysql.service\n          mysql -e 'CREATE DATABASE testing;' -u root -proot\n          mysql -u root -proot --database=testing < tests/fixtures/mysql_schema.sql\n\n      # Setup PostgreSQL with user `testing`, password `testing` and database `testing`\n      - name: Setup PostgreSQL\n        if: \"matrix.app_manager == 'postgres'\"\n        run: |\n          sudo systemctl start postgresql.service\n          pg_isready\n          sudo -u postgres psql --command=\"CREATE USER testing PASSWORD 'testing'\"\n          sudo -u postgres createdb --owner=postgres testing\n          psql --host=127.0.0.1 --username=testing testing < tests/fixtures/postgres_schema.sql\n        env:\n          PGPASSWORD: testing\n\n      - name: Setup DynamoDB\n        if: \"matrix.app_manager == 'dynamodb'\"\n        run: |\n          docker run -p 8000:8000 amazon/dynamodb-local:1.22.0 &\n          node tests/fixtures/dynamodb_schema.js\n        env:\n          AWS_ACCESS_KEY_ID: fake-id\n          AWS_SECRET_ACCESS_KEY: fake-secret\n\n      - name: Setup Localstack\n        if: \"matrix.queue_driver == 'sqs'\"\n        run: |\n          docker-compose up -d localstack\n          docker-compose run initialize_sqs\n\n      - name: Setup NATS\n        if: \"matrix.adapter == 'nats'\"\n        run: |\n          docker run -d \\\n            -p 4222:4222 \\\n            -p 6222:6222 \\\n            -p 8222:8222 \\\n            nats --jetstream --user=\"\" --pass=\"\"\n\n      - name: Execute tests\n        run: npm run test\n        env:\n          RETRY_TIMES: 2\n          TEST_ADAPTER: ${{ matrix.adapter }}\n          TEST_APP_MANAGER: ${{ matrix.app_manager }}\n          TEST_CACHE_DRIVER: ${{ matrix.cache_driver }}\n          TEST_QUEUE_DRIVER: ${{ matrix.queue_driver }}\n          TEST_RATE_LIMITER: ${{ matrix.rate_limiter }}\n          TEST_MYSQL_USER: root\n          TEST_MYSQL_PASSWORD: root\n          TEST_SQS_URL: http://localhost:4566/000000000000/test.fifo\n          AWS_ACCESS_KEY_ID: fake-id\n          AWS_SECRET_ACCESS_KEY: fake-secret\n\n      - uses: codecov/codecov-action@v3.1.4\n        with:\n          token: ${{ secrets.CODECOV_TOKEN }}\n          fail_ci_if_error: false\n"
  },
  {
    "path": ".github/workflows/docker-commit.yml",
    "content": "name: Docker Commit\n\non:\n  push:\n    branches:\n      - \"*\"\n  pull_request:\n    branches:\n      - \"*\"\n    tags-ignore:\n      - \"*\"\n\njobs:\n  # Alpine build.\n  # WARNING: Deprecated, will be removed as it is not recommended\n  #          for uWebSockets.js\n  alpine:\n    if: \"!contains(github.event.head_commit.message, 'skip ci')\"\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      fail-fast: false\n\n      matrix:\n        node:\n          - '16'\n\n    name: Tag Alpine Commit (node:${{ matrix.node }})\n\n    steps:\n      - uses: actions/checkout@v4.1.0\n\n      - name: Docker meta\n        id: docker_meta\n        uses: docker/metadata-action@v5.0.0\n        with:\n          images: quay.io/soketi/soketi\n          tags: |\n            type=ref,event=pr,suffix=-${{ matrix.node }}-alpine\n            type=raw,value=${{ github.sha }}-${{ matrix.node }}-alpine\n          labels: |\n            quay.expires-after=7d\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n        with:\n          driver-opts: network=host\n\n      - name: Login to Quay\n        uses: docker/login-action@v3\n        with:\n          registry: quay.io\n          username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}\n          password: ${{ secrets.DOCKER_REGISTRY_TOKEN }}\n\n      - name: Build and Push\n        uses: docker/build-push-action@v5\n        with:\n          push: true\n          context: .\n          tags: ${{ steps.docker_meta.outputs.tags }}\n          labels: ${{ steps.docker_meta.outputs.labels }}\n          build-args: |\n            VERSION=${{ matrix.node }}\n          cache-from: |\n            type=gha,scope=alpine\n          cache-to: |\n            type=gha,scope=alpine\n          platforms: |\n            linux/amd64\n            linux/arm64\n            linux/arm/v7\n\n  # Distroless build.\n  distroless:\n    if: \"!contains(github.event.head_commit.message, 'skip ci')\"\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      fail-fast: false\n\n      matrix:\n        node:\n          - '16'\n\n    name: Tag Distroless Commit (node:${{ matrix.node }})\n\n    steps:\n      - uses: actions/checkout@v4.1.0\n\n      - name: Docker meta\n        id: docker_meta\n        uses: docker/metadata-action@v5.0.0\n        with:\n          images: quay.io/soketi/soketi\n          tags: |\n            type=ref,event=pr,suffix=-${{ matrix.node }}-distroless\n            type=raw,value=${{ github.sha }}-${{ matrix.node }}-distroless\n          labels: |\n            quay.expires-after=7d\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n        with:\n          driver-opts: network=host\n\n      - name: Login to Quay\n        uses: docker/login-action@v3\n        with:\n          registry: quay.io\n          username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}\n          password: ${{ secrets.DOCKER_REGISTRY_TOKEN }}\n\n      - name: Build and Push\n        uses: docker/build-push-action@v5\n        with:\n          push: true\n          context: .\n          tags: ${{ steps.docker_meta.outputs.tags }}\n          labels: ${{ steps.docker_meta.outputs.labels }}\n          file: Dockerfile.distroless\n          build-args: |\n            VERSION=${{ matrix.node }}\n          cache-from: |\n            type=gha,scope=distroless\n          cache-to: |\n            type=gha,scope=distroless\n          platforms: |\n            linux/amd64\n            linux/arm64\n\n  # Stable Debian build.\n  debian:\n    if: \"!contains(github.event.head_commit.message, 'skip ci')\"\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      fail-fast: false\n\n      matrix:\n        node:\n          - '16'\n\n    name: Tag Debian Commit (node:${{ matrix.node }})\n\n    steps:\n      - uses: actions/checkout@v4.1.0\n\n      - name: Docker meta\n        id: docker_meta\n        uses: docker/metadata-action@v5.0.0\n        with:\n          images: quay.io/soketi/soketi\n          tags: |\n            type=ref,event=pr,suffix=-${{ matrix.node }}-debian\n            type=raw,value=${{ github.sha }}-${{ matrix.node }}-debian\n          labels: |\n            quay.expires-after=7d\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n        with:\n          driver-opts: network=host\n\n      - name: Login to Quay\n        uses: docker/login-action@v3\n        with:\n          registry: quay.io\n          username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}\n          password: ${{ secrets.DOCKER_REGISTRY_TOKEN }}\n\n      - name: Build and Push\n        uses: docker/build-push-action@v5\n        with:\n          push: true\n          context: .\n          tags: ${{ steps.docker_meta.outputs.tags }}\n          labels: ${{ steps.docker_meta.outputs.labels }}\n          file: Dockerfile.debian\n          build-args: |\n            VERSION=${{ matrix.node }}\n          cache-from: |\n            type=gha,scope=debian\n          cache-to: |\n            type=gha,scope=debian\n          platforms: |\n            linux/amd64\n            linux/arm64\n            linux/arm/v7\n"
  },
  {
    "path": ".github/workflows/docker-latest-tag.yml",
    "content": "name: Docker Latest - Standard\n\non:\n  push:\n    branches:\n      - master\n    tags-ignore:\n      - \"*\"\n  pull_request:\n    tags-ignore:\n      - \"*\"\n    branches-ignore:\n      - \"*\"\n\njobs:\n  # Alpine build.\n  # WARNING: Deprecated, will be removed as it is not recommended\n  #          for uWebSockets.js\n  alpine:\n    if: \"!contains(github.event.head_commit.message, 'skip ci')\"\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      matrix:\n        node:\n          - '16'\n\n    name: Tag Latest Alpine (node:${{ matrix.node }})\n\n    steps:\n      - uses: actions/checkout@v4.1.0\n\n      - name: Docker meta\n        id: docker_meta\n        uses: docker/metadata-action@v5.0.0\n        with:\n          images: quay.io/soketi/soketi\n          tags: |\n            type=raw,value=latest-${{ matrix.node }}-alpine\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n        with:\n          driver-opts: network=host\n\n      - name: Login to Quay\n        uses: docker/login-action@v3\n        with:\n          registry: quay.io\n          username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}\n          password: ${{ secrets.DOCKER_REGISTRY_TOKEN }}\n\n      - name: Build and Push\n        uses: docker/build-push-action@v5\n        with:\n          push: true\n          context: .\n          tags: ${{ steps.docker_meta.outputs.tags }}\n          labels: ${{ steps.docker_meta.outputs.labels }}\n          build-args: |\n            VERSION=${{ matrix.node }}\n          cache-from: |\n            type=gha,scope=alpine\n          cache-to: |\n            type=gha,scope=alpine\n          platforms: |\n            linux/amd64\n            linux/arm64\n            linux/arm/v7\n\n  # Distroless build.\n  distroless:\n    if: \"!contains(github.event.head_commit.message, 'skip ci')\"\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      matrix:\n        node:\n          - '16'\n\n    name: Tag Latest Distroless (node:${{ matrix.node }})\n\n    steps:\n      - uses: actions/checkout@v4.1.0\n\n      - name: Docker meta\n        id: docker_meta\n        uses: docker/metadata-action@v5.0.0\n        with:\n          images: quay.io/soketi/soketi\n          tags: |\n            type=raw,value=latest-${{ matrix.node }}-distroless\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n        with:\n          driver-opts: network=host\n\n      - name: Login to Quay\n        uses: docker/login-action@v3\n        with:\n          registry: quay.io\n          username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}\n          password: ${{ secrets.DOCKER_REGISTRY_TOKEN }}\n\n      - name: Build and Push\n        uses: docker/build-push-action@v5\n        with:\n          push: true\n          context: .\n          tags: ${{ steps.docker_meta.outputs.tags }}\n          labels: ${{ steps.docker_meta.outputs.labels }}\n          file: Dockerfile.distroless\n          build-args: |\n            VERSION=${{ matrix.node }}\n          cache-from: |\n            type=gha,scope=distroless\n          cache-to: |\n            type=gha,scope=distroless\n          platforms: |\n            linux/amd64\n            linux/arm64\n\n  # Debian build.\n  debian:\n    if: \"!contains(github.event.head_commit.message, 'skip ci')\"\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      matrix:\n        node:\n          - '16'\n\n    name: Tag Latest Debian (node:${{ matrix.node }})\n\n    steps:\n      - uses: actions/checkout@v4.1.0\n\n      - name: Docker meta\n        id: docker_meta\n        uses: docker/metadata-action@v5.0.0\n        with:\n          images: quay.io/soketi/soketi\n          tags: |\n            type=raw,value=latest-${{ matrix.node }}-debian\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n        with:\n          driver-opts: network=host\n\n      - name: Login to Quay\n        uses: docker/login-action@v3\n        with:\n          registry: quay.io\n          username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}\n          password: ${{ secrets.DOCKER_REGISTRY_TOKEN }}\n\n      - name: Build and Push\n        uses: docker/build-push-action@v5\n        with:\n          push: true\n          context: .\n          tags: ${{ steps.docker_meta.outputs.tags }}\n          labels: ${{ steps.docker_meta.outputs.labels }}\n          file: Dockerfile.debian\n          build-args: |\n            VERSION=${{ matrix.node }}\n          cache-from: |\n            type=gha,scope=debian\n          cache-to: |\n            type=gha,scope=debian\n          platforms: |\n            linux/amd64\n            linux/arm64\n            linux/arm/v7\n"
  },
  {
    "path": ".github/workflows/docker-release-tag.yml",
    "content": "name: Docker Release - Standard\n\non:\n  push:\n    tags:\n      - \"*\"\n\njobs:\n  # Alpine build.\n  # WARNING: Deprecated, will be removed as it is not recommended\n  #          for uWebSockets.js\n  alpine:\n    if: \"!contains(github.event.head_commit.message, 'skip ci')\"\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      matrix:\n        node:\n          - '16'\n\n    name: Tag Alpine Release (node:${{ matrix.node }})\n\n    steps:\n      - uses: actions/checkout@v4.1.0\n\n      - name: Docker meta\n        id: docker_meta\n        uses: docker/metadata-action@v5.0.0\n        with:\n          images: quay.io/soketi/soketi\n          tags: |\n            type=semver,pattern={{version}}-${{ matrix.node }}-alpine\n            type=semver,pattern={{major}}.{{minor}}-${{ matrix.node }}-alpine\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n\n      - name: Compute GitHub tag\n        id: tag\n        uses: dawidd6/action-get-tag@v1.1.0\n\n      - name: Login to Quay\n        uses: docker/login-action@v3\n        with:\n          registry: quay.io\n          username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}\n          password: ${{ secrets.DOCKER_REGISTRY_TOKEN }}\n\n      - name: Build and push (node:${{ matrix.node }})\n        uses: docker/build-push-action@v5\n        with:\n          push: true\n          context: .\n          tags: ${{ steps.docker_meta.outputs.tags }}\n          labels: ${{ steps.docker_meta.outputs.labels }}\n          build-args: |\n            VERSION=${{ matrix.node }}\n          cache-from: |\n            type=gha,scope=alpine\n          cache-to: |\n            type=gha,scope=alpine\n          platforms: |\n            linux/amd64\n            linux/arm64\n            linux/arm/v7\n\n  # Distroless build.\n  distroless:\n    if: \"!contains(github.event.head_commit.message, 'skip ci')\"\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      matrix:\n        node:\n          - '16'\n\n    name: Tag Distroless Release (node:${{ matrix.node }})\n\n    steps:\n      - uses: actions/checkout@v4.1.0\n\n      - name: Docker meta\n        id: docker_meta\n        uses: docker/metadata-action@v5.0.0\n        with:\n          images: quay.io/soketi/soketi\n          tags: |\n            type=semver,pattern={{version}}-${{ matrix.node }}-distroless\n            type=semver,pattern={{major}}.{{minor}}-${{ matrix.node }}-distroless\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n\n      - name: Compute GitHub tag\n        id: tag\n        uses: dawidd6/action-get-tag@v1.1.0\n\n      - name: Login to Quay\n        uses: docker/login-action@v3\n        with:\n          registry: quay.io\n          username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}\n          password: ${{ secrets.DOCKER_REGISTRY_TOKEN }}\n\n      - name: Build and push (node:${{ matrix.node }})\n        uses: docker/build-push-action@v5\n        with:\n          push: true\n          context: .\n          tags: ${{ steps.docker_meta.outputs.tags }}\n          labels: ${{ steps.docker_meta.outputs.labels }}\n          file: Dockerfile.distroless\n          build-args: |\n            VERSION=${{ matrix.node }}\n          cache-from: |\n            type=gha,scope=distroless\n          cache-to: |\n            type=gha,scope=distroless\n          platforms: |\n            linux/amd64\n            linux/arm64\n\n  # Debian build.\n  debian:\n    if: \"!contains(github.event.head_commit.message, 'skip ci')\"\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      matrix:\n        node:\n          - '16'\n\n    name: Tag Debian Release (node:${{ matrix.node }})\n\n    steps:\n      - uses: actions/checkout@v4.1.0\n\n      - name: Docker meta\n        id: docker_meta\n        uses: docker/metadata-action@v5.0.0\n        with:\n          images: quay.io/soketi/soketi\n          tags: |\n            type=semver,pattern={{version}}-${{ matrix.node }}-debian\n            type=semver,pattern={{major}}.{{minor}}-${{ matrix.node }}-debian\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n\n      - name: Compute GitHub tag\n        id: tag\n        uses: dawidd6/action-get-tag@v1.1.0\n\n      - name: Login to Quay\n        uses: docker/login-action@v3\n        with:\n          registry: quay.io\n          username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}\n          password: ${{ secrets.DOCKER_REGISTRY_TOKEN }}\n\n      - name: Build and push (node:${{ matrix.node }})\n        uses: docker/build-push-action@v5\n        with:\n          push: true\n          context: .\n          tags: ${{ steps.docker_meta.outputs.tags }}\n          labels: ${{ steps.docker_meta.outputs.labels }}\n          file: Dockerfile.debian\n          build-args: |\n            VERSION=${{ matrix.node }}\n          cache-from: |\n            type=gha,scope=debian\n          cache-to: |\n            type=gha,scope=debian\n          platforms: |\n            linux/amd64\n            linux/arm64\n            linux/arm/v7\n"
  },
  {
    "path": ".github/workflows/release-npm.yml",
    "content": "name: NPM Release\n\non:\n  push:\n    tags:\n      - \"*\"\n\njobs:\n  build:\n    if: \"!contains(github.event.head_commit.message, 'skip ci')\"\n\n    runs-on: ubuntu-latest\n\n    name: Publish to NPM\n\n    steps:\n      - uses: actions/checkout@v4.1.0\n\n      - uses: actions/setup-node@v3.8.1\n        name: Installing Node.js v16.x\n        with:\n          node-version: 16.x\n\n      - uses: actions/cache@v3.3.2\n        name: Cache npm dependencies\n        with:\n          path: node_modules\n          key: npm-${{ hashFiles('package-lock.json') }}\n\n      - name: Installing dependencies\n        run: |\n          npm ci\n\n      - name: Lint & Compile\n        run: |\n          npm run lint\n          npm run build\n\n      - name: Cleanup\n        run: |\n          npm prune --production\n          rm -rf node_modules/*/test/ node_modules/*/tests/\n\n      - name: Compute GitHub tag\n        id: tag\n        uses: dawidd6/action-get-tag@v1.1.0\n\n      - name: Publish\n        run: |\n          git config --local user.email \"41898282+github-actions[bot]@users.noreply.github.com\"\n          git config --local user.name \"github-actions[bot]\"\n\n          npm set //registry.npmjs.org/:_authToken $NPM_TOKEN\n          npm version ${{ steps.tag.outputs.tag }}\n          npm publish --access=public\n        env:\n          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}\n          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}\n"
  },
  {
    "path": ".gitignore",
    "content": "benchmark/vendor/\nbuild/\ncoverage/\ndist/\nnode_modules/\n.env\nbenchmark/composer.lock\nconfig.json\nnpm-debug.log\nyarn.lock\n*.db\n"
  },
  {
    "path": ".npmignore",
    "content": "src/\ntests/\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\nContributions are **welcome** and will be fully **credited**.\n\nPlease read and understand the contribution guide before creating an issue or pull request.\n\n## Etiquette\n\nThis project is open source, and as such, the maintainers give their free time to build and maintain the source code\nheld within. They make the code freely available in the hope that it will be of use to other developers. It would be\nextremely unfair for them to suffer abuse or anger for their hard work.\n\nPlease be considerate towards maintainers when raising issues or presenting pull requests. Let's show the\nworld that developers are civilized and selfless people.\n\nIt's the duty of the maintainer to ensure that all submissions to the project are of sufficient\nquality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used.\n\n## Viability\n\nWhen requesting or submitting new features, first consider whether it might be useful to others. Open\nsource projects are used by many developers, who may have entirely different needs to your own. Think about\nwhether or not your feature is likely to be used by other users of the project.\n\n## Procedure\n\nBefore filing an issue:\n\n- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident.\n- Check to make sure your feature suggestion isn't already present within the project.\n- Check the pull requests tab to ensure that the bug doesn't have a fix in progress.\n- Check the pull requests tab to ensure that the feature isn't already in progress.\n\nBefore submitting a pull request:\n\n- Check the codebase to ensure that your feature doesn't already exist.\n- Check the pull requests to ensure that another person hasn't already submitted the feature or fix.\n\n## Requirements\n\nIf the project maintainer has any additional requirements, you will find them listed here.\n\n- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer).\n\n- **Add tests!** - Your patch won't be accepted if it doesn't have tests.\n\n- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.\n\n- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.\n\n- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.\n\n- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.\n\n**Happy coding**!\n"
  },
  {
    "path": "Dockerfile",
    "content": "ARG VERSION=lts\n\nFROM --platform=$BUILDPLATFORM node:$VERSION-alpine as build\n\nENV PYTHONUNBUFFERED=1\n\nCOPY . /tmp/build\n\nWORKDIR /tmp/build\n\nRUN apk add --no-cache --update git python3 gcompat ; \\\n    apk add --virtual build-dependencies build-base gcc wget ; \\\n    ln -sf python3 /usr/bin/python ; \\\n    python3 -m ensurepip ; \\\n    pip3 install --no-cache --upgrade pip setuptools ; \\\n    npm ci ; \\\n    npm run build ; \\\n    npm ci --omit=dev --ignore-scripts ; \\\n    npm prune --production ; \\\n    rm -rf node_modules/*/test/ node_modules/*/tests/ ; \\\n    npm install -g modclean ; \\\n    modclean -n default:safe --run ; \\\n    mkdir -p /app ; \\\n    cp -r bin/ dist/ node_modules/ LICENSE package.json package-lock.json README.md /app/\n\nFROM --platform=$TARGETPLATFORM node:$VERSION-alpine\n\nLABEL org.opencontainers.image.authors=\"Soketi <open-source@soketi.app>\"\nLABEL org.opencontainers.image.source=\"https://github.com/soketi/soketi\"\nLABEL org.opencontainers.image.url=\"https://soketi.app\"\nLABEL org.opencontainers.image.documentation=\"https://docs.soketi.app\"\nLABEL org.opencontainers.image.vendor=\"Soketi\"\nLABEL org.opencontainers.image.licenses=\"AGPL-3.0\"\n\nRUN apk add --no-cache libc6-compat ; \\\n    ln -s /lib/libc.musl-x86_64.so.1 /lib/ld-linux-x86-64.so.2\n\nCOPY --from=build /app /app\n\nWORKDIR /app\n\nEXPOSE 6001\n\nENTRYPOINT [\"node\", \"/app/bin/server.js\", \"start\"]\n"
  },
  {
    "path": "Dockerfile.awslocal",
    "content": "FROM python:3-alpine\n\nRUN pip install awscli-local awscli && \\\n    mkdir -p ~/.aws && \\\n    touch ~/.aws/credentials && \\\n    echo \"[default]\" >> ~/.aws/credentials && \\\n    echo \"aws_access_key_id = fake-id\" >> ~/.aws/credentials && \\\n    echo \"aws_secret_access_key = fake-secret\" >> ~/.aws/credentials\n\nENTRYPOINT [\"awslocal\"]\n"
  },
  {
    "path": "Dockerfile.debian",
    "content": "ARG VERSION=lts\n\nFROM --platform=$BUILDPLATFORM node:$VERSION-bullseye as build\n\nENV PYTHONUNBUFFERED=1\n\nCOPY . /tmp/build\n\nWORKDIR /tmp/build\n\nRUN apt-get update -y ; \\\n    apt-get upgrade -y ; \\\n    apt-get install -y git python3 gcc wget ; \\\n    npm ci ; \\\n    npm run build ; \\\n    npm ci --omit=dev --ignore-scripts ; \\\n    npm prune --production ; \\\n    rm -rf node_modules/*/test/ node_modules/*/tests/ ; \\\n    npm install -g modclean ; \\\n    modclean -n default:safe --run ; \\\n    mkdir -p /app ; \\\n    cp -r bin/ dist/ node_modules/ LICENSE package.json package-lock.json README.md /app/\n\nFROM --platform=$TARGETPLATFORM node:$VERSION-bullseye-slim\n\nLABEL org.opencontainers.image.authors=\"Soketi <open-source@soketi.app>\"\nLABEL org.opencontainers.image.source=\"https://github.com/soketi/soketi\"\nLABEL org.opencontainers.image.url=\"https://soketi.app\"\nLABEL org.opencontainers.image.documentation=\"https://docs.soketi.app\"\nLABEL org.opencontainers.image.vendor=\"Soketi\"\nLABEL org.opencontainers.image.licenses=\"AGPL-3.0\"\n\nCOPY --from=build /app /app\n\nWORKDIR /app\n\nEXPOSE 6001\n\nENTRYPOINT [\"node\", \"/app/bin/server.js\", \"start\"]\n"
  },
  {
    "path": "Dockerfile.distroless",
    "content": "ARG VERSION=16\n\nFROM --platform=$BUILDPLATFORM node:$VERSION-alpine as base\n\nENV PYTHONUNBUFFERED=1\n\nCOPY . /tmp/build\n\nWORKDIR /tmp/build\n\nRUN apk add --no-cache --update git python3 gcompat ; \\\n    apk add --virtual build-dependencies build-base gcc wget ; \\\n    ln -sf python3 /usr/bin/python ; \\\n    python3 -m ensurepip ; \\\n    pip3 install --no-cache --upgrade pip setuptools ; \\\n    npm ci ; \\\n    npm run build ; \\\n    npm ci --omit=dev --ignore-scripts ; \\\n    npm prune --production ; \\\n    rm -rf node_modules/*/test/ node_modules/*/tests/ ; \\\n    npm install -g modclean ; \\\n    modclean -n default:safe --run ; \\\n    mkdir -p /app ; \\\n    cp -r bin/ dist/ node_modules/ LICENSE package.json package-lock.json README.md /app/ ; \\\n    chgrp -R 0 /app/ ; \\\n    chmod -R g+rx /app/\n\nFROM --platform=$TARGETPLATFORM gcr.io/distroless/nodejs:$VERSION\n\nLABEL org.opencontainers.image.authors=\"Soketi <open-source@soketi.app>\"\nLABEL org.opencontainers.image.source=\"https://github.com/soketi/soketi\"\nLABEL org.opencontainers.image.url=\"https://soketi.app\"\nLABEL org.opencontainers.image.documentation=\"https://docs.soketi.app\"\nLABEL org.opencontainers.image.vendor=\"Soketi\"\nLABEL org.opencontainers.image.licenses=\"AGPL-3.0\"\n\nCOPY --from=base /app /app\n\nWORKDIR /app\n\nUSER 65534\n\nEXPOSE 6001\n\nCMD [\"/app/bin/server.js\", \"start\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published\n    by the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "README.md",
    "content": "# soketi\n\n<img src=\"assets/logo.png\" width=\"120\" />\n\n![CI](https://github.com/soketi/soketi/workflows/CI/badge.svg?branch=master)\n[![codecov](https://codecov.io/gh/soketi/soketi/branch/master/graph/badge.svg)](https://codecov.io/gh/soketi/soketi/branch/master)\n[![Latest Stable Version](https://img.shields.io/github/v/release/soketi/soketi)](https://www.npmjs.com/package/@soketi/soketi)\n[![Total Downloads](https://img.shields.io/npm/dt/@soketi/soketi)](https://www.npmjs.com/package/@soketi/soketi)\n[![License](https://img.shields.io/npm/l/@soketi/soketi)](https://www.npmjs.com/package/@soketi/soketi)\n\n[![Artifact Hub](https://img.shields.io/endpoint?url=https://artifacthub.io/badge/repository/soketi)](https://artifacthub.io/packages/search?repo=soketi)\n\n[![Discord](https://img.shields.io/discord/957380329985958038?color=%235865F2&label=Discord&logo=discord&logoColor=%23fff)](https://discord.gg/VgfKCQydjb)\n\nNext-gen, Pusher-compatible, open-source WebSockets server. Simple, fast, and resilient. 📣\n\n## 🤝 Supporting\n\nSoketi is meant to be open source, forever and ever. It solves issues that many developers face - the one of wanting to be limitless while testing locally or performing benchmarks. More than that, itt is also suited for production usage, either it is public for your frontend applications or internal to your team.\n\nThe frequency of releases and maintenance is based on the available time, which is tight as hell. Recently, there were issues with the maintenance and this caused infrequent updates, as well as infrequent support.\n\nTo cover some of the expenses of handling new features or having to maintain the project, we would be more than happy if you can donate towards the goal. This will ensure that Soketi will be taken care of at its full extent.\n\n**[💰 Sponsor the development via Github Sponsors](https://github.com/sponsors/rennokki)**\n\n<p align=\"center\">\n  <a href=\"https://github.com/sponsors/rennokki\">\n    <img src='https://cdn.jsdelivr.net/gh/rennokki/sponsorkit-assets@main/assets/sponsors.svg' alt=\"Logos from Sponsors\" />\n  </a>\n</p>\n\n## Soketi\n\n### Blazing fast speed ⚡\n\nThe server is built on top of [uWebSockets.js](https://github.com/uNetworking/uWebSockets.js) - a C application ported to Node.js. uWebSockets.js is demonstrated to perform at levels [_8.5x that of Fastify_](https://alexhultman.medium.com/serving-100k-requests-second-from-a-fanless-raspberry-pi-4-over-ethernet-fdd2c2e05a1e) and at least [_10x that of Socket.IO_](https://medium.com/swlh/100k-secure-websockets-with-raspberry-pi-4-1ba5d2127a23). ([_source_](https://github.com/uNetworking/uWebSockets.js))\n\n### Cheaper than most competitors 🤑\n\nFor a $49 plan on Pusher, you get a limited amount of connections (500) and messages (30M).\n\nWith Soketi, for the price of an instance on Vultr or DigitalOcean ($5-$10), you get virtually unlimited connections, messages, and some more!\n\nSoketi is capable to hold thousands of active connections with high traffic on less than **1 GB and 1 CPU** in the cloud. You can also [get free $100 on Vultr to try out soketi →](https://www.vultr.com/?ref=9032189-8H)\n\n### Easy to use 👶\n\nWhether you run your infrastructure in containers or monoliths, soketi is portable. There are multiple ways to [install](https://docs.soketi.app/getting-started/installation) and [configure](https://docs.soketi.app/getting-started/environment-variables) soketi, from single instances for development, to tens of active instances at scale with hundreds or thousands of active users.\n\n### Pusher Protocol 📡\n\nsoketi implements the [Pusher Protocol v7](https://pusher.com/docs/channels/library\\_auth\\_reference/pusher-websockets-protocol#version-7-2017-11). Your existing projects that connect to Pusher requires minimal code change to make it work with Soketi - you just add the host and port and swap the credentials.\n\n### App-based access 🔐\n\nJust like Pusher, you can access the API and WebSockets through the [apps you define](https://docs.soketi.app/app-management/introduction). Store the data with the built-in support for static arrays, DynamoDB and SQL-based servers like Postgres.\n\n### Production-ready! 🤖\n\nIn addition to being a good companion during local development, soketi comes with the resiliency and speed required for demanding production applications. At scale with Redis, you get the breeze of scaling as you grow.\n\n### Built-in monitoring 📈\n\nYou just have to scrape the Prometheus metrics. Soketi offers a lot of metrics to monitor the deployment and \n\n## See it in action\n\n- [Laravel chat app](https://github.com/soketi/laravel-chat-app)\n- [ETH History chart](https://github.com/soketi/laravel-eth-history)\n\n### Deployments\n\n- [Deploy with Railway](https://github.com/soketi/soketi-railway-deploy-example)\n- [Deploy with Cleavr](https://cleavr.io/cleavr-slice/how-to-install-soketi)\n\n## Community projects\n\n- [Soketi UI](https://github.com/Daynnnnn/soketi-ui) - manage Soketi apps via UI\n- [Soketi App Manager for Filament](https://github.com/rahulhaque/soketi-app-manager-filament) - manage Soketi apps via Filament\n- [Basement Chat](https://github.com/basement-chat/basement-chat) - add chat to your Laravel application\n- [Simple Chat](https://github.com/kitar/simplechat) - showcased chat app built with Soketi and DynamoDB\n\n## 📃 Documentation\n\n[The entire documentation is available on Gitbook 🌍](https://rennokki.gitbook.io/soketi-docs/)\n\n## 🌟 Stargazers\n\nWe really appreciate how this project turned to be such a great success. It will always remain open-source, free, and maintained. This is the real-time as it should be.\n\n[![Stargazers over time](https://starchart.cc/soketi/soketi.svg)](https://starchart.cc/soketi/soketi)\n\n## 🤝 Contributing\n\nPlease see [CONTRIBUTING](CONTRIBUTING.md) for details.\n\n## ⁉ Ideas or Discussions?\n\nHave any ideas that can make into the project? Perhaps you have questions? [Jump into the discussions board](https://github.com/soketi/soketi/discussions) or [join the Discord channel](https://discord.gg/VgfKCQydjb)\n\n## 🔒  Security\n\nIf you discover any security related issues, please email alex@renoki.org instead of using the issue tracker.\n\n## 🎉 Credits\n\n- [Alex Renoki](https://github.com/rennokki)\n- [Pusher Protocol](https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol)\n- [All Contributors](../../contributors)\n- Thank you to Bunny! 🌸\n"
  },
  {
    "path": "SECURITY.md",
    "content": "# Security Policy\n\n## Supported Versions\n\n| Version | Supported |\n| - | - |\n| <0.26.1 | :x: |\n| >=0.26.1 < 1.0.0 | :x: |\n| >= 1.6.0 | :white_check_mark: |\n\n## Reporting a Vulnerability\n\nIf you discover any security-related issues, please email alex@renoki.org instead of using the issue tracker.\n"
  },
  {
    "path": "babel.config.js",
    "content": "module.exports = {\n    presets: [\n        '@babel/preset-typescript',\n    ],\n};\n"
  },
  {
    "path": "benchmark/ci-horizontal.js",
    "content": "import { Trend } from 'k6/metrics';\nimport ws from 'k6/ws';\n\n/**\n * You need to run 4 terminals for this.\n *\n * 1. Run the servers:\n *\n * SOKETI_PORT=6001 SOKETI_ADAPTER_DRIVER=cluster SOKETI_RATE_LIMITER_DRIVER=cluster bin/server.js start\n * SOKETI_PORT=6002 SOKETI_ADAPTER_DRIVER=cluster SOKETI_RATE_LIMITER_DRIVER=cluster bin/server.js start\n *\n * 2. Run the PHP senders based on the amount of messages per second you want to receive.\n *    The sending rate influences the final benchmark.\n *\n * Low, 1 message per second:\n * php send --interval 1 --port 6001\n * php send --interval 1 --port 6002\n *\n * Mild, 2 messages per second:\n * php send --interval 0.5 --port 6001\n * php send --interval 0.5 --port 6002\n *\n * Overkill, 10 messages per second:\n * php send --interval 0.1 --port 6001\n * php send --interval 0.1 --port 6002\n */\n\nconst delayTrend = new Trend('message_delay_ms');\n\nlet maxP95 = 100;\nlet maxAvg = 100;\n\n// External DBs are really slow for benchmarks.\nif (['mysql', 'postgres', 'dynamodb'].includes(__ENV.APP_MANAGER_DRIVER)) {\n    maxP95 += 500;\n    maxAvg += 100;\n}\n\n// Horizontal drivers take additional time to communicate with other nodes.\nif (['redis', 'cluster', 'nats'].includes(__ENV.ADAPTER_DRIVER)) {\n    maxP95 += 100;\n    maxAvg += 100;\n}\n\nexport const options = {\n    thresholds: {\n        message_delay_ms: [\n            { threshold: `p(95)<${maxP95}`, abortOnFail: false },\n            { threshold: `avg<${maxAvg}`, abortOnFail: false },\n        ],\n    },\n\n    scenarios: {\n        // Keep connected many users users at the same time.\n        soakTraffic1: {\n            executor: 'ramping-vus',\n            startVUs: 0,\n            startTime: '0s',\n            stages: [\n                { duration: '50s', target: 125 },\n                { duration: '110s', target: 125 },\n            ],\n            gracefulRampDown: '40s',\n            env: {\n                SLEEP_FOR: '160',\n                WS_HOST: 'ws://127.0.0.1:6001/app/app-key',\n            },\n        },\n        soakTraffic2: {\n            executor: 'ramping-vus',\n            startVUs: 0,\n            startTime: '0s',\n            stages: [\n                { duration: '50s', target: 125 },\n                { duration: '110s', target: 125 },\n            ],\n            gracefulRampDown: '40s',\n            env: {\n                SLEEP_FOR: '160',\n                WS_HOST: 'ws://127.0.0.1:6002/app/app-key',\n            },\n        },\n\n        // Having high amount of connections and disconnections\n        // representing active traffic that starts after 5 seconds\n        // from the soakTraffic scenario.\n        highTraffic1: {\n            executor: 'ramping-vus',\n            startVUs: 0,\n            startTime: '50s',\n            stages: [\n                { duration: '50s', target: 125 },\n                { duration: '30s', target: 125 },\n                { duration: '10s', target: 50 },\n                { duration: '10s', target: 25 },\n                { duration: '10s', target: 50 },\n            ],\n            gracefulRampDown: '25s',\n            env: {\n                SLEEP_FOR: '160',\n                WS_HOST: 'ws://127.0.0.1:6001/app/app-key',\n            },\n        },\n        highTraffic2: {\n            executor: 'ramping-vus',\n            startVUs: 0,\n            startTime: '50s',\n            stages: [\n                { duration: '50s', target: 125 },\n                { duration: '30s', target: 125 },\n                { duration: '10s', target: 50 },\n                { duration: '10s', target: 25 },\n                { duration: '10s', target: 50 },\n            ],\n            gracefulRampDown: '25s',\n            env: {\n                SLEEP_FOR: '160',\n                WS_HOST: 'ws://127.0.0.1:6002/app/app-key',\n            },\n        },\n    },\n};\n\nexport default () => {\n    ws.connect(__ENV.WS_HOST, null, (socket) => {\n        socket.setTimeout(() => {\n            socket.close();\n        }, __ENV.SLEEP_FOR * 1000);\n\n        socket.on('open', () => {\n            // Keep connection alive with pusher:ping\n            socket.setInterval(() => {\n                socket.send(JSON.stringify({\n                    event: 'pusher:ping',\n                    data: JSON.stringify({}),\n                }));\n            }, 30000);\n\n            socket.on('message', message => {\n                let receivedTime = Date.now();\n\n                message = JSON.parse(message);\n\n                if (message.event === 'pusher:connection_established') {\n                    socket.send(JSON.stringify({\n                        event: 'pusher:subscribe',\n                        data: { channel: 'benchmark' },\n                    }));\n                }\n\n                if (message.event === 'timed-message') {\n                    let data = JSON.parse(message.data);\n\n                    delayTrend.add(receivedTime - data.time);\n                }\n            });\n        });\n    });\n}\n"
  },
  {
    "path": "benchmark/ci-local.js",
    "content": "import { Trend } from 'k6/metrics';\nimport ws from 'k6/ws';\n\n/**\n * You need to run 4 terminals for this.\n *\n * 1. Run the servers:\n *\n * SOKETI_PORT=6001 SOKETI_ADAPTER_DRIVER=local SOKETI_RATE_LIMITER_DRIVER=local bin/server.js start\n *\n * 2. Run the PHP senders based on the amount of messages per second you want to receive.\n *    The sending rate influences the final benchmark.\n *\n * Low, 1 message per second:\n * php send --interval 1 --port 6001\n *\n * Mild, 2 messages per second:\n * php send --interval 0.5 --port 6001\n *\n * Overkill, 10 messages per second:\n * php send --interval 0.1 --port 6001\n */\n\nconst delayTrend = new Trend('message_delay_ms');\n\nlet maxP95 = 100;\nlet maxAvg = 100;\n\n// External DBs are really slow for benchmarks.\nif (['mysql', 'postgres', 'dynamodb'].includes(__ENV.APP_MANAGER_DRIVER)) {\n    maxP95 += 500;\n    maxAvg += 100;\n}\n\n// Horizontal drivers take additional time to communicate with other nodes.\nif (['redis', 'cluster', 'nats'].includes(__ENV.ADAPTER_DRIVER)) {\n    maxP95 += 100;\n    maxAvg += 100;\n}\n\nif (['redis'].includes(__ENV.CACHE_DRIVER)) {\n    maxP95 += 20;\n    maxAvg += 20;\n}\n\nexport const options = {\n    thresholds: {\n        message_delay_ms: [\n            { threshold: `p(95)<${maxP95}`, abortOnFail: false },\n            { threshold: `avg<${maxAvg}`, abortOnFail: false },\n        ],\n    },\n\n    scenarios: {\n        // Keep connected many users users at the same time.\n        soakTraffic: {\n            executor: 'ramping-vus',\n            startVUs: 0,\n            startTime: '0s',\n            stages: [\n                { duration: '50s', target: 250 },\n                { duration: '110s', target: 250 },\n            ],\n            gracefulRampDown: '40s',\n            env: {\n                SLEEP_FOR: '160',\n                WS_HOST: __ENV.WS_HOST || 'ws://127.0.0.1:6001/app/app-key',\n            },\n        },\n\n        // Having high amount of connections and disconnections\n        // representing active traffic that starts after 5 seconds\n        // from the soakTraffic scenario.\n        highTraffic: {\n            executor: 'ramping-vus',\n            startVUs: 0,\n            startTime: '50s',\n            stages: [\n                { duration: '50s', target: 250 },\n                { duration: '30s', target: 250 },\n                { duration: '10s', target: 100 },\n                { duration: '10s', target: 50 },\n                { duration: '10s', target: 100 },\n            ],\n            gracefulRampDown: '20s',\n            env: {\n                SLEEP_FOR: '110',\n                WS_HOST: __ENV.WS_HOST || 'ws://127.0.0.1:6001/app/app-key',\n            },\n        },\n    },\n};\n\nexport default () => {\n    ws.connect(__ENV.WS_HOST, null, (socket) => {\n        socket.setTimeout(() => {\n            socket.close();\n        }, __ENV.SLEEP_FOR * 1000);\n\n        socket.on('open', () => {\n            // Keep connection alive with pusher:ping\n            socket.setInterval(() => {\n                socket.send(JSON.stringify({\n                    event: 'pusher:ping',\n                    data: JSON.stringify({}),\n                }));\n            }, 30000);\n\n            socket.on('message', message => {\n                let receivedTime = Date.now();\n\n                message = JSON.parse(message);\n\n                if (message.event === 'pusher:connection_established') {\n                    socket.send(JSON.stringify({\n                        event: 'pusher:subscribe',\n                        data: { channel: 'benchmark' },\n                    }));\n                }\n\n                if (message.event === 'timed-message') {\n                    let data = JSON.parse(message.data);\n\n                    delayTrend.add(receivedTime - data.time);\n                }\n            });\n        });\n    });\n}\n"
  },
  {
    "path": "benchmark/composer.json",
    "content": "{\n    \"name\": \"soketi/soketi-benchmark\",\n    \"type\": \"package\",\n    \"license\": \"MIT\",\n    \"minimum-stability\": \"dev\",\n    \"require\": {\n        \"pusher/pusher-php-server\": \"^7.0\",\n        \"nesbot/carbon\": \"^2.0\",\n        \"ratchet/pawl\": \"dev-master\",\n        \"toolkit/pflag\": \"dev-main\"\n    }\n}\n"
  },
  {
    "path": "benchmark/send",
    "content": "#!/usr/bin/env php\n<?php\n\nrequire __DIR__ . '/vendor/autoload.php';\n\nuse Carbon\\Carbon;\nuse Pusher\\Pusher;\nuse React\\EventLoop\\Loop;\nuse Toolkit\\PFlag\\Flags;\nuse Toolkit\\PFlag\\FlagType;\n\n$loop = Loop::get();\n$flags = array_shift($argv);\n\n$fs = Flags::new();\n$fs->setScriptFile($flags);\n\n$fs->addOpt('interval', 'i', 'Specify at which interval to send each message.', FlagType::FLOAT, false, 0.1);\n$fs->addOpt('messages', 'm', 'Specify the number of messages to send.', FlagType::INT, false);\n$fs->addOpt('host', 'h', 'Specify the host to connect to.', FlagType::STRING, false, '127.0.0.1');\n$fs->addOpt('app-id', 'app-id', 'Specify the ID to use.', FlagType::STRING, false, 'app-id');\n$fs->addOpt('app-key', 'app-key', 'Specify the key to use.', FlagType::STRING, false, 'app-key');\n$fs->addOpt('app-secret', 'app-secret', 'Specify the secret to use.', FlagType::STRING, false, 'app-secret');\n$fs->addOpt('port', 'p', 'Specify the port to connect to.', FlagType::INT, false, 6001);\n$fs->addOpt('ssl', 's', 'Securely connect to the server.', FlagType::BOOL, false, false);\n$fs->addOpt('verbose', 'v', 'Enable verbosity.', FlagType::BOOL, false, false);\n\nif (! $fs->parse($argv)) {\n    return;\n}\n\n$options = $fs->getOpts();\n$args = $fs->getArgs();\n\n$pusher = new Pusher(\n    $options['app-key'] ?? 'app-key',\n    $options['app-secret'] ?? 'app-secret',\n    $options['app-id'] ?? 'app-id',\n    [\n        'host' => $options['host'],\n        'port' => $options['port'],\n        'scheme' => $options['ssl'] ? 'https' : 'http',\n        'encrypted' => true,\n        'useTLS' => $options['ssl'],\n    ]\n);\n\n$interval = $options['interval'] ?? null;\n$messagesBeforeStop = $options['messages'] ?? null;\n$totalMessages = 0;\n\n$loop->addPeriodicTimer($interval, function () use ($pusher, &$totalMessages, $messagesBeforeStop, $loop) {\n    if ($messagesBeforeStop && $totalMessages >= $messagesBeforeStop) {\n        echo \"Sent: {$totalMessages} messages\";\n        return $loop->stop();\n    }\n\n    $pusher->trigger('benchmark', 'timed-message', [\n        'time' => $time = Carbon::now()->getPreciseTimestamp(3),\n    ]);\n\n    $totalMessages++;\n\n    if ($options['verbose'] ?? false) {\n        echo 'Sent message with time: '.$time.PHP_EOL;\n    }\n});\n"
  },
  {
    "path": "bin/pm2.js",
    "content": "#! /usr/bin/env node\n\nconst { Cli } = require('./../dist/cli/cli');\n\nprocess.title = 'soketi-server';\n\nCli.startWithPm2();\n"
  },
  {
    "path": "bin/server.js",
    "content": "#! /usr/bin/env node\n\nrequire('./../dist/cli');\n\nprocess.title = 'soketi-server';\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "version: \"3\"\n\nnetworks:\n  soketi:\n    driver: bridge\n\nservices:\n  localstack:\n    container_name: localstack\n    image: localstack/localstack\n    ports:\n      - \"4510-4530:4510-4530\"\n      - \"4566:4566\"\n      - \"4571:4571\"\n    environment:\n      - SERVICES=sqs,s3\n      - DEBUG=1\n      - HOST_TMP_FOLDER=/tmp/localstack\n      - DOCKER_HOST=unix:///var/run/docker.sock\n    volumes:\n      - \"${TMPDIR:-/tmp}/localstack:/tmp/localstack\"\n      - \"/var/run/docker.sock:/var/run/docker.sock\"\n    networks:\n      - soketi\n    healthcheck:\n      test: [\"CMD\", \"curl\", \"-f\", \"http://localhost:4566/health\"]\n      retries: 3\n      timeout: 5s\n  initialize_sqs:\n    container_name: initialize_sqs\n    build:\n      context: .\n      dockerfile: Dockerfile.awslocal\n    volumes:\n      - ./tests/fixtures/sqs.json:/tmp/sqs.json\n    networks:\n      - soketi\n    command:\n      - sqs\n      - create-queue\n      - --endpoint-url=http://localstack:4566\n      - --queue-name=test.fifo\n      - --region=us-east-1\n      - --attributes=file:///tmp/sqs.json\n    depends_on:\n      localstack:\n        condition: service_healthy\n  dynamodb:\n    container_name: dynamodb\n    image: amazon/dynamodb-local:1.22.0\n    ports:\n      - \"8000:8000\"\n    command: \"-jar DynamoDBLocal.jar -sharedDb\"\n    networks:\n      - soketi\n    environment:\n      AWS_ACCESS_KEY_ID: fake-id\n      AWS_SECRET_ACCESS_KEY: fake-secret\n  initialize_dynamodb:\n    container_name: initialize_dynamodb\n    image: node:18-alpine\n    volumes:\n      - .:/app/\n    networks:\n      - soketi\n    environment:\n      - DYNAMODB_URL=\"dynamodb:8000\"\n    entrypoint:\n      - node\n      - /app/tests/fixtures/dynamodb_schema.js\n"
  },
  {
    "path": "jest.config.js",
    "content": "module.exports = {\n    transform: {\n        '^.+\\\\.tsx?$': 'ts-jest',\n    },\n    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],\n    testTimeout: 20 * 1000,\n    collectCoverage: true,\n    maxWorkers: 1,\n    testRunner: 'jest-circus/runner',\n    globals: {\n        'ts-jest': {\n            isolatedModules: true,\n        },\n        Uint8Array: Uint8Array,\n    },\n};\n"
  },
  {
    "path": "new-connection.sh",
    "content": "#!/bin/bash\n\nwebsocat -t - autoreconnect:ws://127.0.0.1:$1/app/app-key -v --ping-interval=15\n\n# Send this event for testing:\n# {\"event\": \"pusher:subscribe\", \"data\": { \"channel\": \"public\" } }\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"@soketi/soketi\",\n  \"version\": \"0.0.0-dev\",\n  \"description\": \"Just another simple, fast, and resilient open-source WebSockets server.\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/soketi/soketi.git\"\n  },\n  \"main\": \"dist/index.js\",\n  \"keywords\": [\n    \"laravel\",\n    \"socket.io\",\n    \"broadcasting\",\n    \"events\",\n    \"redis\",\n    \"socket\",\n    \"pusher\"\n  ],\n  \"author\": \"Alex Renoki\",\n  \"license\": \"AGPL-3.0\",\n  \"jshintConfig\": {\n    \"esversion\": 9\n  },\n  \"dependencies\": {\n    \"arraybuffer-to-string\": \"^1.0.2\",\n    \"async\": \"^3.2.4\",\n    \"aws-sdk\": \"^2.1426.0\",\n    \"axios\": \"^0.27.2\",\n    \"boolean\": \"^3.1.4\",\n    \"bullmq\": \"^1.80.3\",\n    \"colors\": \"1.4.0\",\n    \"dot-wild\": \"^3.0.1\",\n    \"dotenv\": \"^16.0.1\",\n    \"ioredis\": \"^5.0.4\",\n    \"knex\": \"^3.0.1\",\n    \"mysql\": \"^2.18.1\",\n    \"mysql2\": \"^3.5.2\",\n    \"nats\": \"^2.7.1\",\n    \"node-discover\": \"^1.2.1\",\n    \"pg\": \"^8.7.1\",\n    \"pm2\": \"^5.3.0\",\n    \"prom-client\": \"^14.0.1\",\n    \"prometheus-query\": \"^3.2.5\",\n    \"pusher\": \"^5.1.0-beta\",\n    \"query-string\": \"^7.1.0\",\n    \"rate-limiter-flexible\": \"^2.3.8\",\n    \"sqs-consumer\": \"^5.7.0\",\n    \"uuid\": \"^8.3.2\",\n    \"uWebSockets.js\": \"https://github.com/uNetworking/uWebSockets.js.git#v20.10.0\",\n    \"yargs\": \"^17.5.1\"\n  },\n  \"devDependencies\": {\n    \"@babel/plugin-proposal-decorators\": \"^7.18.10\",\n    \"@babel/plugin-proposal-export-namespace-from\": \"^7.16.7\",\n    \"@babel/plugin-proposal-function-sent\": \"^7.18.6\",\n    \"@babel/plugin-proposal-numeric-separator\": \"^7.16.7\",\n    \"@babel/plugin-proposal-throw-expressions\": \"^7.16.7\",\n    \"@babel/plugin-transform-object-assign\": \"^7.16.7\",\n    \"@babel/preset-env\": \"^7.18.2\",\n    \"@types/bull\": \"^3.15.9\",\n    \"@types/express\": \"^4.17.13\",\n    \"@types/jest\": \"^28.1.6\",\n    \"@types/node\": \"^18.7.6\",\n    \"@types/pusher-js\": \"^5.1.0\",\n    \"@typescript-eslint/eslint-plugin\": \"^5.33.1\",\n    \"@typescript-eslint/parser\": \"^5.33.1\",\n    \"body-parser\": \"^1.20.0\",\n    \"eslint\": \"^8.6.0\",\n    \"express\": \"^4.18.1\",\n    \"jest\": \"^26.6.3\",\n    \"jest-circus\": \"^26.6.3\",\n    \"pusher-js\": \"^7.1.1-beta\",\n    \"tcp-port-used\": \"^1.0.2\",\n    \"ts-jest\": \"^26.5.6\",\n    \"tslib\": \"^2.3.1\",\n    \"typescript\": \"^4.5.4\"\n  },\n  \"scripts\": {\n    \"build\": \"node node_modules/typescript/bin/tsc\",\n    \"build:watch\": \"npm run build -- -W\",\n    \"lint\": \"eslint --ext .js,.ts ./src\",\n    \"prepublish\": \"npm run build\",\n    \"test\": \"jest --detectOpenHandles --forceExit --silent\",\n    \"test:local\": \"jest --detectOpenHandles --forceExit --verbose\",\n    \"test:watch\": \"npm test -- --watch\"\n  },\n  \"bin\": {\n    \"soketi\": \"bin/server.js\",\n    \"soketi-pm2\": \"bin/pm2.js\"\n  },\n  \"peerDependencies\": {\n    \"@pm2/agent\": \"^2.0.3\"\n  }\n}\n"
  },
  {
    "path": "src/adapters/adapter-interface.ts",
    "content": "import { Namespace } from '../namespace';\nimport { PresenceMemberInfo } from '../channels/presence-channel-manager';\nimport { WebSocket } from 'uWebSockets.js';\n\nconst Discover = require('node-discover');\n\nexport interface AdapterInterface {\n    /**\n     * The app connections storage class to manage connections.\n     */\n    namespaces?: Map<string, Namespace>;\n\n    /**\n     * The list of nodes in the current private network.\n     */\n    driver?: AdapterInterface;\n\n    /**\n     * Initialize the adapter.\n     */\n    init(): Promise<AdapterInterface>;\n\n    /**\n     * Get the app namespace.\n     */\n    getNamespace(appId: string): Namespace;\n\n    /**\n     * Get all namespaces.\n     */\n    getNamespaces(): Map<string, Namespace>;\n\n    /**\n     * Add a new socket to the namespace.\n     */\n    addSocket(appId: string, ws: WebSocket): Promise<boolean>;\n\n    /**\n     * Remove a socket from the namespace.\n     */\n    removeSocket(appId: string, wsId: string): Promise<boolean>;\n\n    /**\n     * Add a socket ID to the channel identifier.\n     * Return the total number of connections after the connection.\n     */\n    addToChannel(appId: string, channel: string, ws: WebSocket): Promise<number>;\n\n    /**\n     * Remove a socket ID from the channel identifier.\n     * Return the total number of connections remaining to the channel.\n     */\n    removeFromChannel(appId: string, channel: string|string[], wsId: string): Promise<number|void>;\n\n    /**\n     * Send a message to a namespace and channel.\n     */\n    send(appId: string, channel: string, data: string, exceptingId?: string|null): any;\n\n    /**\n     * Terminate an User ID's connections.\n     */\n    terminateUserConnections(appId: string, userId: number|string): void;\n\n    /**\n     * Clear the connection for the adapter.\n     */\n    disconnect(): Promise<void>;\n\n    /**\n     * Clear the namespace from the local adapter.\n     */\n    clearNamespace(namespaceId: string): Promise<void>;\n\n    /**\n     * Clear all namespaces from the local adapter.\n     */\n    clearNamespaces(): Promise<void>;\n\n    /**\n     * Get all sockets from the namespace.\n     */\n    getSockets(appId: string, onlyLocal?: boolean): Promise<Map<string, WebSocket>>;\n\n    /**\n     * Get total sockets count.\n     */\n    getSocketsCount(appId: string, onlyLocal?: boolean): Promise<number>;\n\n    /**\n     * Get the list of channels with the websocket IDs.\n     */\n    getChannels(appId: string, onlyLocal?: boolean): Promise<Map<string, Set<string>>>;\n\n    /**\n     * Get the list of channels with the websockets count.\n     */\n    getChannelsWithSocketsCount(appId: string, onlyLocal?: boolean): Promise<Map<string, number>>;\n\n    /**\n     * Get all the channel sockets associated with a namespace.\n     */\n    getChannelSockets(appId: string, channel: string, onlyLocal?: boolean): Promise<Map<string, WebSocket>>;\n\n    /**\n     * Get a given channel's total sockets count.\n     */\n    getChannelSocketsCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number>;\n\n    /**\n     * Get a given presence channel's members.\n     */\n    getChannelMembers(appId: string, channel: string, onlyLocal?: boolean): Promise<Map<string, PresenceMemberInfo>>;\n\n    /**\n     * Get a given presence channel's members count\n     */\n    getChannelMembersCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number>;\n\n    /**\n     * Check if a given connection ID exists in a channel.\n     */\n    isInChannel(appId: string, channel: string, wsId: string, onlyLocal?: boolean): Promise<boolean>;\n\n    /**\n     * Add to the users list the associated socket connection ID.\n     */\n    addUser(ws: WebSocket): Promise<void>;\n\n    /**\n     * Remove the user associated with the connection ID.\n     */\n    removeUser(ws: WebSocket): Promise<void>;\n\n    /**\n     * Get the sockets associated with an user.\n     */\n    getUserSockets(appId: string, userId: string|number): Promise<Set<WebSocket>>;\n}\n"
  },
  {
    "path": "src/adapters/adapter.ts",
    "content": "import { AdapterInterface } from './adapter-interface';\nimport { ClusterAdapter } from './cluster-adapter';\nimport { LocalAdapter } from './local-adapter';\nimport { Log } from '../log';\nimport { Namespace } from '../namespace';\nimport { NatsAdapter } from './nats-adapter';\nimport { PresenceMemberInfo } from '../channels/presence-channel-manager';\nimport { RedisAdapter } from './redis-adapter';\nimport { Server } from '../server';\nimport { WebSocket } from 'uWebSockets.js';\n\nexport class Adapter implements AdapterInterface {\n    /**\n     * The adapter driver.\n     */\n    public driver: AdapterInterface;\n\n    /**\n     * Initialize adapter scaling.\n     */\n    constructor(server: Server) {\n        if (server.options.adapter.driver === 'local') {\n            this.driver = new LocalAdapter(server);\n        } else if (server.options.adapter.driver === 'redis') {\n            this.driver = new RedisAdapter(server);\n        } else if (server.options.adapter.driver === 'nats') {\n            this.driver = new NatsAdapter(server);\n        } else if (server.options.adapter.driver === 'cluster') {\n            this.driver = new ClusterAdapter(server);\n        } else {\n            Log.error('Adapter driver not set.');\n        }\n    }\n\n    /**\n     * Initialize the adapter.\n     */\n    async init(): Promise<AdapterInterface> {\n        return await this.driver.init();\n    }\n\n    /**\n     * Get the app namespace.\n     */\n    getNamespace(appId: string): Namespace {\n        return this.driver.getNamespace(appId);\n    }\n\n    /**\n     * Get all namespaces.\n     */\n    getNamespaces(): Map<string, Namespace> {\n        return this.driver.getNamespaces();\n    }\n\n    /**\n     * Add a new socket to the namespace.\n     */\n    async addSocket(appId: string, ws: WebSocket): Promise<boolean> {\n        return this.driver.addSocket(appId, ws);\n    }\n\n    /**\n     * Remove a socket from the namespace.\n     */\n    async removeSocket(appId: string, wsId: string): Promise<boolean> {\n        return this.driver.removeSocket(appId, wsId);\n    }\n\n    /**\n     * Add a socket ID to the channel identifier.\n     * Return the total number of connections after the connection.\n     */\n    async addToChannel(appId: string, channel: string, ws: WebSocket): Promise<number> {\n        return this.driver.addToChannel(appId, channel, ws);\n    }\n\n    /**\n     * Remove a socket ID from the channel identifier.\n     * Return the total number of connections remaining to the channel.\n     */\n    async removeFromChannel(appId: string, channel: string|string[], wsId: string): Promise<number|void> {\n        return this.driver.removeFromChannel(appId, channel, wsId);\n    }\n\n    /**\n     * Get all sockets from the namespace.\n     */\n    async getSockets(appId: string, onlyLocal = false): Promise<Map<string, WebSocket>> {\n        return this.driver.getSockets(appId, onlyLocal);\n    }\n\n    /**\n     * Get total sockets count.\n     */\n    async getSocketsCount(appId: string, onlyLocal?: boolean): Promise<number> {\n        return this.driver.getSocketsCount(appId, onlyLocal);\n    }\n\n    /**\n     * Get the list of channels with the websocket IDs.\n     */\n    async getChannels(appId: string, onlyLocal = false): Promise<Map<string, Set<string>>> {\n        return this.driver.getChannels(appId, onlyLocal);\n    }\n\n    /**\n     * Get the list of channels with the websockets count.\n     */\n    async getChannelsWithSocketsCount(appId: string, onlyLocal = false): Promise<Map<string, number>> {\n        return this.driver.getChannelsWithSocketsCount(appId, onlyLocal);\n    }\n\n    /**\n     * Get all the channel sockets associated with a namespace.\n     */\n    async getChannelSockets(appId: string, channel: string, onlyLocal = false): Promise<Map<string, WebSocket>> {\n        return this.driver.getChannelSockets(appId, channel, onlyLocal);\n    }\n\n    /**\n     * Get a given channel's total sockets count.\n     */\n    async getChannelSocketsCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number> {\n        return this.driver.getChannelSocketsCount(appId, channel, onlyLocal);\n    }\n\n    /**\n     * Get a given presence channel's members.\n     */\n    async getChannelMembers(appId: string, channel: string, onlyLocal = false): Promise<Map<string, PresenceMemberInfo>> {\n        return this.driver.getChannelMembers(appId, channel, onlyLocal);\n    }\n\n    /**\n     * Get a given presence channel's members count\n     */\n    async getChannelMembersCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number> {\n        return this.driver.getChannelMembersCount(appId, channel, onlyLocal);\n    }\n\n    /**\n     * Check if a given connection ID exists in a channel.\n     */\n    async isInChannel(appId: string, channel: string, wsId: string, onlyLocal?: boolean): Promise<boolean> {\n        return this.driver.isInChannel(appId, channel, wsId, onlyLocal);\n    }\n\n    /**\n     * Send a message to a namespace and channel.\n     */\n    send(appId: string, channel: string, data: string, exceptingId: string|null = null): void {\n        return this.driver.send(appId, channel, data, exceptingId);\n    }\n\n    /**\n     * Terminate an User ID's connections.\n     */\n    terminateUserConnections(appId: string, userId: number|string): void {\n        return this.driver.terminateUserConnections(appId, userId);\n    }\n\n    /**\n     * Add to the users list the associated socket connection ID.\n     */\n    addUser(ws: WebSocket): Promise<void> {\n        return this.driver.addUser(ws);\n    }\n\n    /**\n     * Remove the user associated with the connection ID.\n     */\n    removeUser(ws: WebSocket): Promise<void> {\n        return this.driver.removeUser(ws);\n    }\n\n    /**\n     * Get the sockets associated with an user.\n     */\n    getUserSockets(appId: string, userId: string|number): Promise<Set<WebSocket>> {\n        return this.driver.getUserSockets(appId, userId);\n    }\n\n    /**\n     * Clear the namespace from the local adapter.\n     */\n    clearNamespace(namespaceId: string): Promise<void> {\n        return this.driver.clearNamespace(namespaceId);\n    }\n\n    /**\n     * Clear all namespaces from the local adapter.\n     */\n    clearNamespaces(): Promise<void> {\n        return this.driver.clearNamespaces();\n    }\n\n    /**\n     * Clear the connections.\n     */\n    disconnect(): Promise<void> {\n        return this.driver.disconnect();\n    }\n}\n"
  },
  {
    "path": "src/adapters/cluster-adapter.ts",
    "content": "import { AdapterInterface } from './adapter-interface';\nimport { HorizontalAdapter, PubsubBroadcastedMessage } from './horizontal-adapter';\nimport { Server } from '../server';\n\nexport class ClusterAdapter extends HorizontalAdapter {\n    /**\n     * The channel to broadcast the information.\n     */\n    protected channel = 'cluster-adapter';\n\n    /**\n     * Initialize the adapter.\n     */\n    constructor(server: Server) {\n        super(server);\n\n        this.channel = server.clusterPrefix(this.channel);\n        this.requestChannel = `${this.channel}#comms#req`;\n        this.responseChannel = `${this.channel}#comms#res`;\n        this.requestsTimeout = server.options.adapter.cluster.requestsTimeout;\n    }\n\n    /**\n     * Initialize the adapter.\n     */\n    async init(): Promise<AdapterInterface> {\n        this.server.discover.join(this.requestChannel, this.onRequest.bind(this));\n        this.server.discover.join(this.responseChannel, this.onResponse.bind(this));\n        this.server.discover.join(this.channel, this.onMessage.bind(this));\n\n        return this;\n    }\n\n    /**\n     * Listen for requests coming from other nodes.\n     */\n    protected onRequest(msg: any): void {\n        if (typeof msg === 'object') {\n            msg = JSON.stringify(msg);\n        }\n\n        super.onRequest(this.requestChannel, msg);\n    }\n\n    /**\n     * Handle a response from another node.\n     */\n    protected onResponse(msg: any): void {\n        if (typeof msg === 'object') {\n            msg = JSON.stringify(msg);\n        }\n\n        super.onResponse(this.responseChannel, msg);\n    }\n\n    /**\n     * Listen for message coming from other nodes to broadcast\n     * a specific message to the local sockets.\n     */\n    protected onMessage(msg: any): void {\n        if (typeof msg === 'string') {\n            msg = JSON.parse(msg);\n        }\n\n        let message: PubsubBroadcastedMessage = msg;\n\n        const { uuid, appId, channel, data, exceptingId } = message;\n\n        if (uuid === this.uuid || !appId || !channel || !data) {\n            return;\n        }\n\n        super.sendLocally(appId, channel, data, exceptingId);\n    }\n\n    /**\n     * Broadcast data to a given channel.\n     */\n    protected broadcastToChannel(channel: string, data: string): void {\n        this.server.discover.send(channel, data);\n    }\n\n    /**\n     * Get the number of Discover nodes.\n     */\n    protected getNumSub(): Promise<number> {\n        return Promise.resolve(this.server.nodes.size);\n    }\n}\n"
  },
  {
    "path": "src/adapters/horizontal-adapter.ts",
    "content": "import { LocalAdapter } from './local-adapter';\nimport { Log } from '../log';\nimport { PresenceMemberInfo } from '../channels/presence-channel-manager';\nimport { v4 as uuidv4 } from 'uuid';\nimport { WebSocket } from 'uWebSockets.js';\n\n/**\n *                                          |-----> NODE1 ----> SEEKS DATA (ONREQUEST) ----> SEND TO THE NODE0 ---> NODE0 (ONRESPONSE) APPENDS DATA TO REQUEST OBJECT\n *                                          |\n * NODE0 ---> PUBLISH TO PUBLISHER  ------> |-----> NODE2 ----> SEEKS DATA (ONREQUEST) ----> SEND TO THE NODE0 ---> NODE0 (ONRESPONSE) APPENDS DATA TO REQUEST OBJECT\n *            (IN ADAPTER METHOD)           |\n *                                          |-----> NODE3 ----> SEEKS DATA (ONREQUEST) ----> SEND TO THE NODE0 ---> NODE0 (ONRESPONSE) APPENDS DATA TO REQUEST OBJECT\n */\n\nexport enum RequestType {\n    SOCKETS = 0,\n    CHANNELS = 1,\n    CHANNEL_SOCKETS = 2,\n    CHANNEL_MEMBERS = 3,\n    SOCKETS_COUNT = 4,\n    CHANNEL_MEMBERS_COUNT = 5,\n    CHANNEL_SOCKETS_COUNT = 6,\n    SOCKET_EXISTS_IN_CHANNEL = 7,\n    CHANNELS_WITH_SOCKETS_COUNT = 8,\n    TERMINATE_USER_CONNECTIONS = 9,\n}\n\nexport interface RequestExtra {\n    numSub?: number;\n    msgCount?: number;\n    sockets?: Map<string, any>;\n    members?: Map<string, PresenceMemberInfo>;\n    channels?: Map<string, Set<string>>;\n    channelsWithSocketsCount?: Map<string, number>;\n    totalCount?: number;\n}\n\nexport interface Request extends RequestExtra {\n    appId: string;\n    type: RequestType;\n    time: number;\n    resolve: Function;\n    reject: Function;\n    timeout: any;\n    [other: string]: any;\n}\n\nexport interface RequestOptions {\n    opts?: { [key: string]: any };\n}\n\nexport interface RequestBody extends RequestOptions {\n    type: RequestType;\n    requestId: string;\n    appId: string;\n}\n\nexport interface Response {\n    requestId: string;\n    sockets?: Map<string, WebSocket>;\n    members?: [string, PresenceMemberInfo][];\n    channels?: [string, string[]][];\n    channelsWithSocketsCount?: [string, number][];\n    totalCount?: number;\n    exists?: boolean;\n}\n\nexport interface PubsubBroadcastedMessage {\n    uuid: string;\n    appId: string;\n    channel: string;\n    data: any;\n    exceptingId?: string|null;\n}\n\nexport abstract class HorizontalAdapter extends LocalAdapter {\n    /**\n     * The time (in ms) for the request to be fulfilled.\n     */\n    public requestsTimeout = 5_000;\n\n    /**\n     * The channel to listen for new requests.\n     */\n    protected requestChannel;\n\n    /**\n     * The channel to emit back based on the requests.\n     */\n    protected responseChannel;\n\n    /**\n     * The list of current request made by this instance.\n     */\n    protected requests: Map<string, Request> = new Map();\n\n    /**\n     * The channel to broadcast the information.\n     */\n    protected channel = 'horizontal-adapter';\n\n    /**\n     * The UUID assigned for the current instance.\n     */\n    protected uuid: string = uuidv4();\n\n    /**\n     * The list of resolvers for each response type.\n     */\n    protected resolvers = {\n        [RequestType.SOCKETS]: {\n            computeResponse: (request: Request, response: Response) => {\n                if (response.sockets) {\n                    response.sockets.forEach(ws => request.sockets.set(ws.id, ws));\n                }\n            },\n            resolveValue: (request: Request, response: Response) => {\n                return request.sockets;\n            },\n        },\n        [RequestType.CHANNEL_SOCKETS]: {\n            computeResponse: (request: Request, response: Response) => {\n                if (response.sockets) {\n                    response.sockets.forEach(ws => request.sockets.set(ws.id, ws));\n                }\n            },\n            resolveValue: (request: Request, response: Response) => {\n                return request.sockets;\n            },\n        },\n        [RequestType.CHANNELS]: {\n            computeResponse: (request: Request, response: Response) => {\n                if (response.channels) {\n                    response.channels.forEach(([channel, connections]) => {\n                        if (request.channels.has(channel)) {\n                            connections.forEach(connection => {\n                                request.channels.set(channel, request.channels.get(channel).add(connection));\n                            });\n                        } else {\n                            request.channels.set(channel, new Set(connections));\n                        }\n                    });\n                }\n            },\n            resolveValue: (request: Request, response: Response) => {\n                return request.channels;\n            },\n        },\n        [RequestType.CHANNELS_WITH_SOCKETS_COUNT]: {\n            computeResponse: (request: Request, response: Response) => {\n                if (response.channelsWithSocketsCount) {\n                    response.channelsWithSocketsCount.forEach(([channel, connectionsCount]) => {\n                        if (request.channelsWithSocketsCount.has(channel)) {\n                            request.channelsWithSocketsCount.set(\n                                channel,\n                                request.channelsWithSocketsCount.get(channel) + connectionsCount,\n                            );\n                        } else {\n                            request.channelsWithSocketsCount.set(channel, connectionsCount);\n                        }\n                    });\n                }\n            },\n            resolveValue: (request: Request, response: Response) => {\n                return request.channelsWithSocketsCount;\n            },\n        },\n        [RequestType.CHANNEL_MEMBERS]: {\n            computeResponse: (request: Request, response: Response) => {\n                if (response.members) {\n                    response.members.forEach(([id, member]) => request.members.set(id, member));\n                }\n            },\n            resolveValue: (request: Request, response: Response) => {\n                return request.members;\n            },\n        },\n        [RequestType.SOCKETS_COUNT]: {\n            computeResponse: (request: Request, response: Response) => {\n                if (typeof response.totalCount !== 'undefined') {\n                    request.totalCount += response.totalCount;\n                }\n            },\n            resolveValue: (request: Request, response: Response) => {\n                return request.totalCount;\n            },\n        },\n        [RequestType.CHANNEL_MEMBERS_COUNT]: {\n            computeResponse: (request: Request, response: Response) => {\n                if (typeof response.totalCount !== 'undefined') {\n                    request.totalCount += response.totalCount;\n                }\n            },\n            resolveValue: (request: Request, response: Response) => {\n                return request.totalCount;\n            },\n        },\n        [RequestType.CHANNEL_SOCKETS_COUNT]: {\n            computeResponse: (request: Request, response: Response) => {\n                if (typeof response.totalCount !== 'undefined') {\n                    request.totalCount += response.totalCount;\n                }\n            },\n            resolveValue: (request: Request, response: Response) => {\n                return request.totalCount;\n            },\n        },\n        [RequestType.SOCKET_EXISTS_IN_CHANNEL]: {\n            computeResponse: (request: Request, response: Response) => {\n                if (typeof response.exists !== 'undefined' && response.exists === true) {\n                    request.exists = true;\n                }\n            },\n            resolveValue: (request: Request, response: Response) => {\n                return request.exists || false;\n            },\n        },\n        [RequestType.TERMINATE_USER_CONNECTIONS]: {\n            computeResponse: (request: Request, response: Response) => {\n                // Don't need to compute any response as we won't be sending one.\n            },\n            resolveValue: (request: Request, response: Response) => {\n                return true;\n            },\n        },\n    };\n\n    /**\n     * Broadcast data to a given channel.\n     */\n    protected abstract broadcastToChannel(channel: string, data: string): void;\n\n    /**\n     * Get the number of total subscribers subscribers.\n     */\n    protected abstract getNumSub(): Promise<number>;\n\n    /**\n     * Send a response through the response channel.\n     */\n    protected sendToResponseChannel(data: string): void {\n        this.broadcastToChannel(this.responseChannel, data);\n    }\n\n    /**\n     * Send a request through the request channel.\n     */\n    protected sendToRequestChannel(data: string): void {\n        this.broadcastToChannel(this.requestChannel, data);\n    }\n\n    /**\n     * Send a message to a namespace and channel.\n     */\n    send(appId: string, channel: string, data: string, exceptingId: string|null = null): any {\n        this.broadcastToChannel(this.channel, JSON.stringify({\n            uuid: this.uuid,\n            appId,\n            channel,\n            data,\n            exceptingId,\n        }));\n\n        this.sendLocally(appId, channel, data, exceptingId);\n    }\n\n    /**\n     * Force local sending only for the Horizontal adapter.\n     */\n    sendLocally(appId: string, channel: string, data: string, exceptingId: string|null = null): any {\n        super.send(appId, channel, data, exceptingId);\n    }\n\n    /**\n     * Terminate an User ID's connections.\n     */\n    terminateUserConnections(appId: string, userId: number|string): void {\n        new Promise((resolve, reject) => {\n            this.getNumSub().then(numSub => {\n                if (numSub <= 1) {\n                    this.terminateLocalUserConnections(appId, userId);\n\n                    return;\n                }\n\n                this.sendRequest(\n                    appId,\n                    RequestType.TERMINATE_USER_CONNECTIONS,\n                    resolve,\n                    reject,\n                    { numSub },\n                    { opts: { userId } },\n                );\n            });\n        });\n\n        this.terminateLocalUserConnections(appId, userId);\n    }\n\n    /**\n     * Terminate an User ID's local connections.\n     */\n    terminateLocalUserConnections(appId: string, userId: number|string): void {\n        super.terminateUserConnections(appId, userId);\n    }\n\n    /**\n     * Get all sockets from the namespace.\n     */\n    async getSockets(appId: string, onlyLocal = false): Promise<Map<string, WebSocket>> {\n        return new Promise((resolve, reject) => {\n            super.getSockets(appId, true).then(localSockets => {\n                if (onlyLocal) {\n                    return resolve(localSockets);\n                }\n\n                this.getNumSub().then(numSub => {\n                    if (numSub <= 1) {\n                        return resolve(localSockets);\n                    }\n\n                    this.sendRequest(\n                        appId,\n                        RequestType.SOCKETS,\n                        resolve,\n                        reject,\n                        { numSub, sockets: localSockets },\n                    );\n                });\n            });\n        });\n    }\n\n    /**\n     * Get total sockets count.\n     */\n    async getSocketsCount(appId: string, onlyLocal?: boolean): Promise<number> {\n        return new Promise((resolve, reject) => {\n            super.getSocketsCount(appId).then(wsCount => {\n                if (onlyLocal) {\n                    return resolve(wsCount);\n                }\n\n                this.getNumSub().then(numSub => {\n                    if (numSub <= 1) {\n                        return resolve(wsCount);\n                    }\n\n                    this.sendRequest(\n                        appId,\n                        RequestType.SOCKETS_COUNT,\n                        resolve,\n                        reject,\n                        { numSub, totalCount: wsCount },\n                    );\n                });\n            });\n        });\n    }\n\n    /**\n     * Get all sockets from the namespace.\n     */\n    async getChannels(appId: string, onlyLocal = false): Promise<Map<string, Set<string>>> {\n        return new Promise((resolve, reject) => {\n            super.getChannels(appId).then(localChannels => {\n                if (onlyLocal) {\n                    resolve(localChannels);\n                }\n\n                this.getNumSub().then(numSub => {\n                    if (numSub <= 1) {\n                        return resolve(localChannels);\n                    }\n\n                    this.sendRequest(\n                        appId,\n                        RequestType.CHANNELS,\n                        resolve,\n                        reject,\n                        { numSub, channels: localChannels },\n                    );\n                });\n            });\n        });\n    }\n\n    /**\n     * Get total sockets count.\n     */\n    async getChannelsWithSocketsCount(appId: string, onlyLocal?: boolean): Promise<Map<string, number>> {\n        return new Promise((resolve, reject) => {\n            super.getChannelsWithSocketsCount(appId).then(list => {\n                if (onlyLocal) {\n                    return resolve(list);\n                }\n\n                this.getNumSub().then(numSub => {\n                    if (numSub <= 1) {\n                        return resolve(list);\n                    }\n\n                    this.sendRequest(\n                        appId,\n                        RequestType.CHANNELS_WITH_SOCKETS_COUNT,\n                        resolve,\n                        reject,\n                        { numSub, channelsWithSocketsCount: list },\n                    );\n                });\n            });\n        });\n    }\n\n    /**\n     * Get all the channel sockets associated with a namespace.\n     */\n    async getChannelSockets(appId: string, channel: string, onlyLocal = false): Promise<Map<string, WebSocket>> {\n        return new Promise((resolve, reject) => {\n            super.getChannelSockets(appId, channel).then(localSockets => {\n                if (onlyLocal) {\n                    return resolve(localSockets);\n                }\n\n                this.getNumSub().then(numSub => {\n                    if (numSub <= 1) {\n                        return resolve(localSockets);\n                    }\n\n                    this.sendRequest(\n                        appId,\n                        RequestType.CHANNEL_SOCKETS,\n                        resolve,\n                        reject,\n                        { numSub, sockets: localSockets },\n                        { opts: { channel } },\n                    );\n                });\n            });\n        });\n    }\n\n    /**\n     * Get a given channel's total sockets count.\n     */\n    async getChannelSocketsCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number> {\n        return new Promise((resolve, reject) => {\n            super.getChannelSocketsCount(appId, channel).then(wsCount => {\n                if (onlyLocal) {\n                    return resolve(wsCount);\n                }\n\n                this.getNumSub().then(numSub => {\n                    if (numSub <= 1) {\n                        return resolve(wsCount);\n                    }\n\n                    this.sendRequest(\n                        appId,\n                        RequestType.CHANNEL_SOCKETS_COUNT,\n                        resolve,\n                        reject,\n                        { numSub, totalCount: wsCount },\n                        { opts: { channel } },\n                    );\n                });\n            });\n        });\n    }\n\n    /**\n     * Get all the channel sockets associated with a namespace.\n     */\n    async getChannelMembers(appId: string, channel: string, onlyLocal = false): Promise<Map<string, PresenceMemberInfo>> {\n        return new Promise((resolve, reject) => {\n            super.getChannelMembers(appId, channel).then(localMembers => {\n                if (onlyLocal) {\n                    return resolve(localMembers);\n                }\n\n                this.getNumSub().then(numSub => {\n                    if (numSub <= 1) {\n                        return resolve(localMembers);\n                    }\n\n                    return this.sendRequest(\n                        appId,\n                        RequestType.CHANNEL_MEMBERS,\n                        resolve,\n                        reject,\n                        { numSub, members: localMembers },\n                        { opts: { channel } },\n                    );\n                });\n            });\n        });\n    }\n\n    /**\n     * Get a given presence channel's members count\n     */\n    async getChannelMembersCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number> {\n        return new Promise((resolve, reject) => {\n            super.getChannelMembersCount(appId, channel).then(localMembersCount => {\n                if (onlyLocal) {\n                    return resolve(localMembersCount);\n                }\n\n                this.getNumSub().then(numSub => {\n                    if (numSub <= 1) {\n                        return resolve(localMembersCount);\n                    }\n\n                    this.sendRequest(\n                        appId,\n                        RequestType.CHANNEL_MEMBERS_COUNT,\n                        resolve,\n                        reject,\n                        { numSub, totalCount: localMembersCount },\n                        { opts: { channel } },\n                    );\n                });\n            });\n        });\n    }\n\n    /**\n     * Check if a given connection ID exists in a channel.\n     */\n    async isInChannel(appId: string, channel: string, wsId: string, onlyLocal?: boolean): Promise<boolean> {\n        return new Promise((resolve, reject) => {\n            super.isInChannel(appId, channel, wsId).then(existsLocally => {\n                if (onlyLocal || existsLocally) {\n                    return resolve(existsLocally);\n                }\n\n                this.getNumSub().then(numSub => {\n                    if (numSub <= 1) {\n                        return resolve(existsLocally);\n                    }\n\n                    return this.sendRequest(\n                        appId,\n                        RequestType.SOCKET_EXISTS_IN_CHANNEL,\n                        resolve,\n                        reject,\n                        { numSub },\n                        { opts: { channel, wsId } },\n                    );\n                });\n            });\n        });\n    }\n\n    /**\n     * Listen for requests coming from other nodes.\n     */\n    protected onRequest(channel: string, msg: string): void {\n        let request: RequestBody;\n\n        try {\n            request = JSON.parse(msg);\n        } catch (err) {\n            //\n        }\n\n        let { appId } = request;\n\n        if (this.server.options.debug) {\n            Log.clusterTitle('🧠 Received request from another node');\n            Log.cluster({ request, channel });\n        }\n\n        switch (request.type) {\n            case RequestType.SOCKETS:\n                this.processRequestFromAnotherInstance(request, () => super.getSockets(appId, true).then(sockets => {\n                    let localSockets: WebSocket[] = Array.from(sockets.values());\n\n                    return {\n                        sockets: localSockets.map(ws => ({\n                            id: ws.id,\n                            subscribedChannels: ws.subscribedChannels,\n                            presence: ws.presence,\n                            ip: ws.ip,\n                            ip2: ws.ip2,\n                        })),\n                    };\n                }));\n                break;\n\n            case RequestType.CHANNEL_SOCKETS:\n                this.processRequestFromAnotherInstance(request, () => super.getChannelSockets(appId, request.opts.channel).then(sockets => {\n                    let localSockets: WebSocket[] = Array.from(sockets.values());\n\n                    return {\n                        sockets: localSockets.map(ws => ({\n                            id: ws.id,\n                            subscribedChannels: ws.subscribedChannels,\n                            presence: ws.presence,\n                        })),\n                    };\n                }));\n                break;\n\n            case RequestType.CHANNELS:\n                this.processRequestFromAnotherInstance(request, () => {\n                    return super.getChannels(appId).then(localChannels => {\n                        return {\n                            channels: [...localChannels].map(([channel, connections]) => [channel, [...connections]]),\n                        };\n                    });\n                });\n                break;\n\n            case RequestType.CHANNELS_WITH_SOCKETS_COUNT:\n                this.processRequestFromAnotherInstance(request, () => {\n                    return super.getChannelsWithSocketsCount(appId).then(channelsWithSocketsCount => {\n                        return { channelsWithSocketsCount: [...channelsWithSocketsCount] };\n                    });\n                });\n                break;\n\n            case RequestType.CHANNEL_MEMBERS:\n                this.processRequestFromAnotherInstance(request, () => {\n                    return super.getChannelMembers(appId, request.opts.channel).then(localMembers => {\n                        return { members: [...localMembers] };\n                    });\n                });\n                break;\n\n            case RequestType.SOCKETS_COUNT:\n                this.processRequestFromAnotherInstance(request, () => {\n                    return super.getSocketsCount(appId).then(localCount => {\n                        return { totalCount: localCount };\n                    });\n                });\n                break;\n\n            case RequestType.CHANNEL_MEMBERS_COUNT:\n                this.processRequestFromAnotherInstance(request, () => {\n                    return super.getChannelMembersCount(appId, request.opts.channel).then(localCount => {\n                        return { totalCount: localCount };\n                    });\n                });\n                break;\n\n            case RequestType.CHANNEL_SOCKETS_COUNT:\n                this.processRequestFromAnotherInstance(request, () => {\n                    return super.getChannelSocketsCount(appId, request.opts.channel).then(localCount => {\n                        return { totalCount: localCount };\n                    });\n                });\n                break;\n\n            case RequestType.SOCKET_EXISTS_IN_CHANNEL:\n                this.processRequestFromAnotherInstance(request, () => {\n                    return super.isInChannel(appId, request.opts.channel, request.opts.wsId).then(existsLocally => {\n                        return { exists: existsLocally };\n                    });\n                });\n                break;\n\n            case RequestType.TERMINATE_USER_CONNECTIONS:\n                this.processRequestFromAnotherInstance(request, () => {\n                    this.terminateLocalUserConnections(appId, request.opts.userId);\n\n                    return Promise.resolve();\n                });\n                break;\n        }\n    }\n\n    /**\n     * Handle a response from another node.\n     */\n    protected onResponse(channel: string, msg: string): void {\n        let response: Response;\n\n        try {\n            response = JSON.parse(msg);\n        } catch (err) {\n            //\n        }\n\n        const requestId = response.requestId;\n\n        if (!requestId || !this.requests.has(requestId)) {\n            return;\n        }\n\n        const request = this.requests.get(requestId);\n\n        if (this.server.options.debug) {\n            Log.clusterTitle('🧠 Received response from another node to our request');\n            Log.cluster(msg);\n        }\n\n        this.processReceivedResponse(\n            response,\n            this.resolvers[request.type].computeResponse.bind(this),\n            this.resolvers[request.type].resolveValue.bind(this),\n        );\n    }\n\n    /**\n     * Send a request to find more about what other subscribers\n     * are storing in their memory.\n     */\n    protected sendRequest(\n        appId: string,\n        type: RequestType,\n        resolve: CallableFunction,\n        reject: CallableFunction,\n        requestExtra: RequestExtra = {},\n        requestOptions: RequestOptions = {},\n    ) {\n        const requestId = uuidv4();\n\n        const timeout = setTimeout(() => {\n            if (this.requests.has(requestId)) {\n                if (this.server.options.debug) {\n                    Log.error(`Timeout reached while waiting for response in type ${type}. Forcing resolve with the current values.`);\n                }\n\n                this.processReceivedResponse(\n                    { requestId },\n                    this.resolvers[type].computeResponse.bind(this),\n                    this.resolvers[type].resolveValue.bind(this),\n                    true\n                );\n            }\n        }, this.requestsTimeout);\n\n        // Add the request to the local memory.\n        this.requests.set(requestId, {\n            appId,\n            type,\n            time: Date.now(),\n            timeout,\n            msgCount: 1,\n            resolve,\n            reject,\n            ...requestExtra,\n        });\n\n        // The message to send to other nodes.\n        const requestToSend = JSON.stringify({\n            requestId,\n            appId,\n            type,\n            ...requestOptions,\n        });\n\n        this.sendToRequestChannel(requestToSend);\n\n        if (this.server.options.debug) {\n            Log.clusterTitle('✈ Sent message to other instances');\n            Log.cluster({ request: this.requests.get(requestId) });\n        }\n\n        this.server.metricsManager.markHorizontalAdapterRequestSent(appId);\n    }\n\n    /**\n     * Process the incoming request from other subscriber.\n     */\n    protected processRequestFromAnotherInstance(request: RequestBody, callbackResolver: Function): void {\n        let { requestId, appId } = request;\n\n        // Do not process requests for the same node that created the request.\n        if (this.requests.has(requestId)) {\n            return;\n        }\n\n        callbackResolver().then(extra => {\n            let response = JSON.stringify({ requestId, ...extra });\n\n            this.sendToResponseChannel(response);\n\n            if (this.server.options.debug) {\n                Log.clusterTitle('✈ Sent response to the instance');\n                Log.cluster({ response });\n            }\n\n            this.server.metricsManager.markHorizontalAdapterRequestReceived(appId);\n        });\n    }\n\n    /**\n     * Process the incoming response to a request we made.\n     */\n    protected processReceivedResponse(\n        response: Response,\n        responseComputer: CallableFunction,\n        promiseResolver: CallableFunction,\n        forceResolve = false\n    ) {\n        const request = this.requests.get(response.requestId);\n\n        request.msgCount++;\n\n        responseComputer(request, response);\n\n        this.server.metricsManager.markHorizontalAdapterResponseReceived(request.appId);\n\n        if (forceResolve || request.msgCount === request.numSub) {\n            clearTimeout(request.timeout);\n\n            if (request.resolve) {\n                request.resolve(promiseResolver(request, response));\n                this.requests.delete(response.requestId);\n\n                // If the resolve was forced, it means not all nodes fulfilled the request, thus leading to timeout.\n                this.server.metricsManager.trackHorizontalAdapterResolvedPromises(request.appId, !forceResolve);\n                this.server.metricsManager.trackHorizontalAdapterResolveTime(request.appId, Date.now() - request.time);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/adapters/index.ts",
    "content": "export * from './adapter';\nexport * from './adapter-interface';\nexport * from './cluster-adapter';\nexport * from './horizontal-adapter';\nexport * from './local-adapter';\nexport * from './nats-adapter';\nexport * from './redis-adapter';\n"
  },
  {
    "path": "src/adapters/local-adapter.ts",
    "content": "import { AdapterInterface } from './adapter-interface';\nimport { Namespace } from '../namespace';\nimport { PresenceMemberInfo } from '../channels/presence-channel-manager';\nimport { Server } from '../server';\nimport { WebSocket } from 'uWebSockets.js';\n\nexport class LocalAdapter implements AdapterInterface {\n    // TODO: Force disconnect a specific socket\n    // TODO: Force disconnect all sockets from an app.\n\n    /**\n     * The app connections storage class to manage connections.\n     */\n    public namespaces: Map<string, Namespace> = new Map<string, Namespace>();\n\n    /**\n     * Initialize the adapter.\n     */\n    constructor(protected server: Server) {\n        //\n    }\n\n    /**\n     * Initialize the adapter.\n     */\n    async init(): Promise<AdapterInterface> {\n        return Promise.resolve(this);\n    }\n\n    /**\n     * Get the app namespace.\n     */\n    getNamespace(appId: string): Namespace {\n        if (!this.namespaces.has(appId)) {\n            this.namespaces.set(appId, new Namespace(appId));\n        }\n\n        return this.namespaces.get(appId);\n    }\n\n    /**\n     * Get all namespaces.\n     */\n    getNamespaces(): Map<string, Namespace> {\n        return this.namespaces;\n    }\n\n    /**\n     * Add a new socket to the namespace.\n     */\n    async addSocket(appId: string, ws: WebSocket): Promise<boolean> {\n        return this.getNamespace(appId).addSocket(ws);\n    }\n\n    /**\n     * Remove a socket from the namespace.\n     */\n    async removeSocket(appId: string, wsId: string): Promise<boolean> {\n        return this.getNamespace(appId).removeSocket(wsId);\n    }\n\n    /**\n     * Add a socket ID to the channel identifier.\n     * Return the total number of connections after the connection.\n     */\n    async addToChannel(appId: string, channel: string, ws: WebSocket): Promise<number> {\n        return this.getNamespace(appId).addToChannel(ws, channel).then(() => {\n            return this.getChannelSocketsCount(appId, channel);\n        });\n    }\n\n    /**\n     * Remove a socket ID from the channel identifier.\n     * Return the total number of connections remaining to the channel.\n     */\n    async removeFromChannel(appId: string, channel: string|string[], wsId: string): Promise<number|void> {\n        return this.getNamespace(appId).removeFromChannel(wsId, channel).then((remainingConnections) => {\n            if (!Array.isArray(channel)) {\n                return this.getChannelSocketsCount(appId, channel);\n            }\n\n            return;\n        });\n    }\n\n    /**\n     * Get all sockets from the namespace.\n     */\n    async getSockets(appId: string, onlyLocal = false): Promise<Map<string, WebSocket>> {\n        return this.getNamespace(appId).getSockets();\n    }\n\n    /**\n     * Get total sockets count.\n     */\n    async getSocketsCount(appId: string, onlyLocal?: boolean): Promise<number> {\n        return this.getNamespace(appId).getSockets().then(sockets => {\n            return sockets.size;\n        });\n    }\n\n    /**\n     * Get all sockets from the namespace.\n     */\n    async getChannels(appId: string, onlyLocal = false): Promise<Map<string, Set<string>>> {\n        return this.getNamespace(appId).getChannels();\n    }\n\n    /**\n     * Get channels with total sockets count.\n     */\n    async getChannelsWithSocketsCount(appId: string, onlyLocal?: boolean): Promise<Map<string, number>> {\n        return this.getNamespace(appId).getChannelsWithSocketsCount();\n    }\n\n    /**\n     * Get all the channel sockets associated with a namespace.\n     */\n    async getChannelSockets(appId: string, channel: string, onlyLocal = false): Promise<Map<string, WebSocket>> {\n        return this.getNamespace(appId).getChannelSockets(channel);\n    }\n\n    /**\n     * Get a given channel's total sockets count.\n     */\n    async getChannelSocketsCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number> {\n        return this.getNamespace(appId).getChannelSockets(channel).then(sockets => {\n            return sockets.size;\n        });\n    }\n\n    /**\n     * Get a given presence channel's members.\n     */\n    async getChannelMembers(appId: string, channel: string, onlyLocal = false): Promise<Map<string, PresenceMemberInfo>> {\n        return this.getNamespace(appId).getChannelMembers(channel);\n    }\n\n    /**\n     * Get a given presence channel's members count\n     */\n    async getChannelMembersCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number> {\n        return this.getNamespace(appId).getChannelMembers(channel).then(members => {\n            return members.size;\n        });\n    }\n\n    /**\n     * Check if a given connection ID exists in a channel.\n     */\n    async isInChannel(appId: string, channel: string, wsId: string, onlyLocal?: boolean): Promise<boolean> {\n        return this.getNamespace(appId).isInChannel(wsId, channel);\n    }\n\n    /**\n     * Send a message to a namespace and channel.\n     */\n    send(appId: string, channel: string, data: string, exceptingId: string|null = null): any {\n        // For user-dedicated channels, intercept the .send() call and use custom logic.\n        if (channel.indexOf('#server-to-user-') === 0) {\n            let userId = channel.split('#server-to-user-').pop();\n\n            this.getUserSockets(appId, userId).then(sockets => {\n                sockets.forEach(ws => {\n                    if (ws.sendJson) {\n                        ws.sendJson(JSON.parse(data));\n                    }\n                });\n            });\n\n            return;\n        }\n\n        this.getNamespace(appId).getChannelSockets(channel).then(sockets => {\n            sockets.forEach((ws) => {\n                if (exceptingId && exceptingId === ws.id) {\n                    return;\n                }\n\n                // Fix race conditions.\n                if (ws.sendJson) {\n                    ws.sendJson(JSON.parse(data));\n                }\n            });\n        });\n    }\n\n    /**\n     * Terminate an User ID's connections.\n     */\n    terminateUserConnections(appId: string, userId: number|string): void {\n        this.getNamespace(appId).terminateUserConnections(userId);\n    }\n\n    /**\n     * Add to the users list the associated socket connection ID.\n     */\n    addUser(ws: WebSocket): Promise<void> {\n        return this.getNamespace(ws.app.id).addUser(ws);\n    }\n\n    /**\n     * Remove the user associated with the connection ID.\n     */\n    removeUser(ws: WebSocket): Promise<void> {\n        return this.getNamespace(ws.app.id).removeUser(ws);\n    }\n\n    /**\n     * Get the sockets associated with an user.\n     */\n    getUserSockets(appId: string, userId: number|string): Promise<Set<WebSocket>> {\n        return this.getNamespace(appId).getUserSockets(userId);\n    }\n\n    /**\n     * Clear the connections.\n     */\n    disconnect(): Promise<void> {\n        return Promise.resolve();\n    }\n\n    /**\n     * Clear the namespace from the local adapter.\n     */\n    clearNamespace(namespaceId: string): Promise<void> {\n        this.namespaces.set(namespaceId, new Namespace(namespaceId));\n\n        return Promise.resolve();\n    }\n\n     /**\n      * Clear all namespaces from the local adapter.\n      */\n    clearNamespaces(): Promise<void> {\n        this.namespaces = new Map<string, Namespace>();\n\n        return Promise.resolve();\n    }\n}\n"
  },
  {
    "path": "src/adapters/nats-adapter.ts",
    "content": "import { AdapterInterface } from './adapter-interface';\nimport { connect, JSONCodec, Msg, NatsConnection, StringCodec } from 'nats';\nimport { HorizontalAdapter, PubsubBroadcastedMessage } from './horizontal-adapter';\nimport { Server } from '../server';\nimport { timeout } from 'nats/lib/nats-base-client/util';\n\nexport class NatsAdapter extends HorizontalAdapter {\n    /**\n     * The channel to broadcast the information.\n     */\n    protected channel = 'nats-adapter';\n\n    /**\n     * The NATS connection.\n     */\n    protected connection: NatsConnection;\n\n    /**\n     * The JSON codec.\n     */\n    protected jc: any;\n\n    /**\n     * The String codec.\n     */\n    protected sc: any;\n\n    /**\n     * Initialize the adapter.\n     */\n    constructor(server: Server) {\n        super(server);\n\n        if (server.options.adapter.nats.prefix) {\n            this.channel = server.options.adapter.nats.prefix + '#' + this.channel;\n        }\n\n        this.requestChannel = `${this.channel}#comms#req`;\n        this.responseChannel = `${this.channel}#comms#res`;\n\n        this.jc = JSONCodec();\n        this.sc = StringCodec();\n\n        this.requestsTimeout = server.options.adapter.nats.requestsTimeout;\n    }\n\n    /**\n     * Initialize the adapter.\n     */\n    async init(): Promise<AdapterInterface> {\n        return new Promise(resolve => {\n            connect({\n                servers: this.server.options.adapter.nats.servers,\n                user: this.server.options.adapter.nats.user,\n                pass: this.server.options.adapter.nats.pass,\n                token: this.server.options.adapter.nats.token,\n                pingInterval: 30_000,\n                timeout: this.server.options.adapter.nats.timeout,\n                reconnect: false,\n            }).then((connection) => {\n                this.connection = connection;\n\n                this.connection.subscribe(this.requestChannel, { callback: (_err, msg) => this.onRequest(msg) });\n                this.connection.subscribe(this.responseChannel, { callback: (_err, msg) => this.onResponse(msg) });\n                this.connection.subscribe(this.channel, { callback: (_err, msg) => this.onMessage(msg) });\n\n                resolve(this);\n            });\n        });\n    }\n\n    /**\n     * Listen for requests coming from other nodes.\n     */\n    protected onRequest(msg: any): void {\n        super.onRequest(this.requestChannel, JSON.stringify(this.jc.decode(msg.data)));\n    }\n\n    /**\n     * Handle a response from another node.\n     */\n    protected onResponse(msg: any): void {\n        super.onResponse(this.responseChannel, JSON.stringify(this.jc.decode(msg.data)));\n    }\n\n    /**\n     * Listen for message coming from other nodes to broadcast\n     * a specific message to the local sockets.\n     */\n    protected onMessage(msg: any): void {\n        let message: PubsubBroadcastedMessage = this.jc.decode(msg.data);\n\n        const { uuid, appId, channel, data, exceptingId } = message;\n\n        if (uuid === this.uuid || !appId || !channel || !data) {\n            return;\n        }\n\n        super.sendLocally(appId, channel, data, exceptingId);\n    }\n\n    /**\n     * Broadcast data to a given channel.\n     */\n    protected broadcastToChannel(channel: string, data: string): void {\n        this.connection.publish(channel, this.jc.encode(JSON.parse(data)));\n    }\n\n    /**\n     * Get the number of Discover nodes.\n     */\n    protected async getNumSub(): Promise<number> {\n        let nodesNumber = this.server.options.adapter.nats.nodesNumber;\n\n        if (nodesNumber && nodesNumber > 0) {\n            return Promise.resolve(nodesNumber);\n        }\n\n        return new Promise(resolve => {\n            let responses: Msg[] = [];\n\n            let calculateResponses = () => responses.reduce((total, response) => {\n                let { data } = JSON.parse(this.sc.decode(response.data)) as any;\n\n                return total += data.total;\n            }, 0);\n\n            let waiter = timeout(1000);\n\n            waiter.finally(() => resolve(calculateResponses()));\n\n            this.connection.request('$SYS.REQ.SERVER.PING.CONNZ').then(response => {\n                responses.push(response);\n                waiter.cancel();\n                waiter = timeout(200);\n                waiter.catch(() => resolve(calculateResponses()));\n            });\n        });\n    }\n\n    /**\n     * Clear the connections.\n     */\n    disconnect(): Promise<void> {\n        return this.connection.close();\n    }\n}\n"
  },
  {
    "path": "src/adapters/redis-adapter.ts",
    "content": "import { AdapterInterface } from './adapter-interface';\nimport { HorizontalAdapter, PubsubBroadcastedMessage } from './horizontal-adapter';\nimport { Log } from '../log';\nimport Redis, { Cluster, ClusterOptions, RedisOptions } from 'ioredis';\nimport { Server } from '../server';\n\nexport class RedisAdapter extends HorizontalAdapter {\n    /**\n     * The channel to broadcast the information.\n     */\n    protected channel = 'redis-adapter';\n\n    /**\n     * The subscription client.\n     */\n    protected subClient: Redis|Cluster;\n\n    /**\n     * The publishing client.\n     */\n    protected pubClient: Redis|Cluster;\n\n    /**\n     * Initialize the adapter.\n     */\n    constructor(server: Server) {\n        super(server);\n\n        if (server.options.adapter.redis.prefix) {\n            this.channel = server.options.adapter.redis.prefix + '#' + this.channel;\n        }\n\n        this.requestChannel = `${this.channel}#comms#req`;\n        this.responseChannel = `${this.channel}#comms#res`;\n\n        this.requestsTimeout = server.options.adapter.redis.requestsTimeout;\n    }\n\n    /**\n     * Initialize the adapter.\n     */\n    async init(): Promise<AdapterInterface> {\n        let redisOptions: RedisOptions|ClusterOptions = {\n            maxRetriesPerRequest: 2,\n            retryStrategy: times => times * 2,\n            ...this.server.options.database.redis,\n        };\n\n        this.subClient = this.server.options.adapter.redis.clusterMode\n            ? new Cluster(this.server.options.database.redis.clusterNodes, { ...redisOptions, ...this.server.options.adapter.redis.redisSubOptions })\n            : new Redis({ ...redisOptions, ...this.server.options.adapter.redis.redisSubOptions });\n\n        this.pubClient = this.server.options.adapter.redis.clusterMode\n            ? new Cluster(this.server.options.database.redis.clusterNodes, { ...redisOptions, ...this.server.options.adapter.redis.redisPubOptions })\n            : new Redis({ ...redisOptions, ...this.server.options.adapter.redis.redisPubOptions });\n\n        const onError = err => {\n            if (err) {\n                Log.warning(err);\n            }\n        };\n\n        this.subClient.psubscribe(`${this.channel}*`, onError);\n\n        this.subClient.on('pmessageBuffer', this.onMessage.bind(this));\n        this.subClient.on('messageBuffer', this.processMessage.bind(this));\n\n        this.subClient.subscribe(this.requestChannel, this.responseChannel, onError);\n\n        this.pubClient.on('error', onError);\n        this.subClient.on('error', onError);\n\n        return this;\n    }\n\n    /**\n     * Broadcast data to a given channel.\n     */\n    protected broadcastToChannel(channel: string, data: string): void {\n        this.pubClient.publish(channel, data);\n    }\n\n    /**\n     * Process the incoming message and redirect it to the right processor.\n     */\n    protected processMessage(redisChannel: string, msg: Buffer|string): void {\n        redisChannel = redisChannel.toString();\n        msg = msg.toString();\n\n        if (redisChannel.startsWith(this.responseChannel)) {\n            this.onResponse(redisChannel, msg);\n        } else if (redisChannel.startsWith(this.requestChannel)) {\n            this.onRequest(redisChannel, msg);\n        }\n    }\n\n    /**\n     * Listen for message coming from other nodes to broadcast\n     * a specific message to the local sockets.\n     */\n    protected onMessage(pattern: string, redisChannel: string, msg: Buffer|string): void {\n        redisChannel = redisChannel.toString();\n        msg = msg.toString();\n\n        // This channel is just for the en-masse broadcasting, not for processing\n        // the request-response cycle to gather info across multiple nodes.\n        if (!redisChannel.startsWith(this.channel)) {\n            return;\n        }\n\n        let decodedMessage: PubsubBroadcastedMessage = JSON.parse(msg);\n\n        if (typeof decodedMessage !== 'object') {\n            return;\n        }\n\n        const { uuid, appId, channel, data, exceptingId } = decodedMessage;\n\n        if (uuid === this.uuid || !appId || !channel || !data) {\n            return;\n        }\n\n        super.sendLocally(appId, channel, data, exceptingId);\n    }\n\n    /**\n     * Get the number of Redis subscribers.\n     */\n    protected getNumSub(): Promise<number> {\n        if (this.server.options.adapter.redis.clusterMode) {\n            const nodes = (this.pubClient as Cluster).nodes();\n\n            return Promise.all(\n                nodes.map((node) =>\n                    node.pubsub('NUMSUB', this.requestChannel)\n                )\n            ).then((values: any[]) => {\n                let number = values.reduce((numSub, value) => {\n                    return numSub += parseInt(value[1], 10);\n                }, 0);\n\n                if (this.server.options.debug) {\n                    Log.info(`Found ${number} subscribers in the Redis cluster.`);\n                }\n\n                return number;\n            });\n        } else {\n            // RedisClient or Redis\n            return new Promise((resolve, reject) => {\n                this.pubClient.pubsub(\n                    'NUMSUB',\n                    this.requestChannel,\n                    (err, numSub: [any, string]) => {\n                        if (err) {\n                            return reject(err);\n                        }\n\n                        let number = parseInt(numSub[1], 10);\n\n                        if (this.server.options.debug) {\n                            Log.info(`Found ${number} subscribers in the Redis cluster.`);\n                        }\n\n                        resolve(number);\n                    }\n                );\n            });\n        }\n    }\n\n    /**\n     * Clear the connections.\n     */\n    disconnect(): Promise<void> {\n        return Promise.all([\n            this.subClient.quit(),\n            this.pubClient.quit(),\n        ]).then(() => {\n            //\n        });\n    }\n}\n"
  },
  {
    "path": "src/app-managers/app-manager-interface.ts",
    "content": "import { App } from '../app';\n\nexport interface AppManagerInterface {\n    /**\n     * The application manager driver.\n     */\n    driver?: AppManagerInterface;\n\n    /**\n     * Find an app by given ID.\n     */\n    findById(id: string): Promise<App|null>;\n\n    /**\n     * Find an app by given key.\n     */\n    findByKey(key: string): Promise<App|null>;\n\n    /**\n     * Get the app secret by ID.\n     */\n    getAppSecret(id: string): Promise<string|null>;\n}\n"
  },
  {
    "path": "src/app-managers/app-manager.ts",
    "content": "import { App } from './../app';\nimport { AppManagerInterface } from './app-manager-interface';\nimport { ArrayAppManager } from './array-app-manager';\nimport { DynamoDbAppManager } from './dynamodb-app-manager';\nimport { Log } from '../log';\nimport { MysqlAppManager } from './mysql-app-manager';\nimport { PostgresAppManager } from './postgres-app-manager';\nimport { Server } from '../server';\n\n/**\n * Class that controls the key/value data store.\n */\nexport class AppManager implements AppManagerInterface {\n    /**\n     * The application manager driver.\n     */\n    public driver: AppManagerInterface;\n\n    /**\n     * Create a new database instance.\n     */\n    constructor(protected server: Server) {\n        if (server.options.appManager.driver === 'array') {\n            this.driver = new ArrayAppManager(server);\n        } else if (server.options.appManager.driver === 'mysql') {\n            this.driver = new MysqlAppManager(server);\n        } else if (server.options.appManager.driver === 'postgres') {\n            this.driver = new PostgresAppManager(server);\n        } else if (server.options.appManager.driver === 'dynamodb') {\n            this.driver = new DynamoDbAppManager(server);\n        } else {\n            Log.error('Clients driver not set.');\n        }\n    }\n\n    /**\n     * Find an app by given ID.\n     */\n    findById(id: string): Promise<App|null> {\n        if (!this.server.options.appManager.cache.enabled) {\n            return this.driver.findById(id);\n        }\n\n        return this.server.cacheManager.get(`app:${id}`).then(appFromCache => {\n            if (appFromCache) {\n                return new App(JSON.parse(appFromCache), this.server);\n            }\n\n            return this.driver.findById(id).then(app => {\n                this.server.cacheManager.set(`app:${id}`, app ? app.toJson() : app, this.server.options.appManager.cache.ttl);\n\n                return app;\n            });\n        });\n    }\n\n    /**\n     * Find an app by given key.\n     */\n    findByKey(key: string): Promise<App|null> {\n        if (!this.server.options.appManager.cache.enabled) {\n            return this.driver.findByKey(key);\n        }\n\n        return this.server.cacheManager.get(`app:${key}`).then(appFromCache => {\n            if (appFromCache) {\n                return new App(JSON.parse(appFromCache), this.server);\n            }\n\n            return this.driver.findByKey(key).then(app => {\n                this.server.cacheManager.set(`app:${key}`, app ? app.toJson() : app, this.server.options.appManager.cache.ttl);\n\n                return app;\n            });\n        });\n    }\n\n    /**\n     * Get the app secret by ID.\n     */\n    getAppSecret(id: string): Promise<string|null> {\n        return this.driver.getAppSecret(id);\n    }\n}\n"
  },
  {
    "path": "src/app-managers/array-app-manager.ts",
    "content": "import { App } from '../app';\nimport { BaseAppManager } from './base-app-manager';\nimport { Log } from '../log';\nimport { Server } from '../server';\n\nexport class ArrayAppManager extends BaseAppManager {\n    /**\n     * Create a new app manager instance.\n     */\n    constructor(protected server: Server) {\n        super();\n    }\n\n    /**\n     * Find an app by given ID.\n     */\n    findById(id: string): Promise<App|null> {\n        return new Promise(resolve => {\n            let app = this.server.options.appManager.array.apps.find(app => app.id == id);\n\n            if (typeof app !== 'undefined') {\n                resolve(new App(app, this.server));\n            } else {\n                if (this.server.options.debug) {\n                    Log.error(`App ID not found: ${id}`);\n                }\n\n                resolve(null);\n            }\n        });\n    }\n\n    /**\n     * Find an app by given key.\n     */\n    findByKey(key: string): Promise<App|null> {\n        return new Promise(resolve => {\n            let app = this.server.options.appManager.array.apps.find(app => app.key == key);\n\n            if (typeof app !== 'undefined') {\n                resolve(new App(app, this.server));\n            } else {\n                if (this.server.options.debug) {\n                    Log.error(`App key not found: ${key}`);\n                }\n\n                resolve(null);\n            }\n        });\n    }\n}\n"
  },
  {
    "path": "src/app-managers/base-app-manager.ts",
    "content": "import { App } from '../app';\nimport { AppManagerInterface } from './app-manager-interface';\n\nexport class BaseAppManager implements AppManagerInterface {\n    /**\n     * Find an app by given ID.\n     */\n    findById(id: string): Promise<App|null> {\n        return Promise.resolve(null);\n    }\n\n    /**\n     * Find an app by given key.\n     */\n    findByKey(key: string): Promise<App|null> {\n        return Promise.resolve(null);\n    }\n\n    /**\n     * Get the app secret by ID.\n     */\n    getAppSecret(id: string): Promise<string|null> {\n        return this.findById(id).then(app => {\n            return app\n                ? app.secret\n                : null;\n        });\n    }\n}\n"
  },
  {
    "path": "src/app-managers/dynamodb-app-manager.ts",
    "content": "import { App } from '../app';\nimport { AttributeMap } from 'aws-sdk/clients/dynamodb';\nimport { BaseAppManager } from './base-app-manager';\nimport { boolean } from 'boolean';\nimport { DynamoDB } from 'aws-sdk';\nimport { Log } from '../log';\nimport { Server } from '../server';\n\nexport class DynamoDbAppManager extends BaseAppManager {\n    /**\n     * The DynamoDB client.\n     */\n    protected dynamodb: DynamoDB;\n\n    /**\n     * Create a new app manager instance.\n     */\n    constructor(protected server: Server) {\n        super();\n\n        this.dynamodb = new DynamoDB({\n            apiVersion: '2012-08-10',\n            region: server.options.appManager.dynamodb.region,\n            endpoint: server.options.appManager.dynamodb.endpoint,\n        });\n    }\n\n    /**\n     * Find an app by given ID.\n     */\n    findById(id: string): Promise<App|null> {\n        return this.dynamodb.getItem({\n            TableName: this.server.options.appManager.dynamodb.table,\n            Key: {\n                AppId: { S: id },\n            },\n        }).promise().then((response) => {\n            let item = response.Item;\n\n            if (!item) {\n                if (this.server.options.debug) {\n                    Log.error(`App ID not found: ${id}`);\n                }\n\n                return null;\n            }\n\n            return new App(this.unmarshallItem(item), this.server);\n        }).catch(err => {\n            if (this.server.options.debug) {\n                Log.error('Error loading app config from dynamodb');\n                Log.error(err);\n            }\n\n            return null;\n        });\n    }\n\n    /**\n     * Find an app by given key.\n     */\n    findByKey(key: string): Promise<App|null> {\n        return this.dynamodb.query({\n            TableName: this.server.options.appManager.dynamodb.table,\n            IndexName: 'AppKeyIndex',\n            ScanIndexForward: false,\n            Limit: 1,\n            KeyConditionExpression: 'AppKey = :app_key',\n            ExpressionAttributeValues: {\n                ':app_key': { S: key },\n            },\n        }).promise().then((response) => {\n            let item = response.Items[0] || null;\n\n            if (!item) {\n                if (this.server.options.debug) {\n                    Log.error(`App key not found: ${key}`);\n                }\n\n                return null;\n            }\n\n            return new App(this.unmarshallItem(item), this.server);\n        }).catch(err => {\n            if (this.server.options.debug) {\n                Log.error('Error loading app config from dynamodb');\n                Log.error(err);\n            }\n\n            return null;\n        });\n    }\n\n    /**\n     * Transform the marshalled item to a key-value pair.\n     */\n    protected unmarshallItem(item: AttributeMap): { [key: string]: any; } {\n        let appObject = DynamoDB.Converter.unmarshall(item);\n\n        // Making sure EnableClientMessages is boolean.\n        if (appObject.EnableClientMessages instanceof Buffer) {\n            appObject.EnableClientMessages = boolean(appObject.EnableClientMessages.toString());\n        }\n\n        // JSON-decoding the Webhooks field.\n        if (typeof appObject.Webhooks === 'string') {\n            try {\n                appObject.Webhooks = JSON.parse(appObject.Webhooks);\n            } catch (e) {\n                appObject.Webhooks = [];\n            }\n        }\n\n        return appObject;\n    }\n}\n"
  },
  {
    "path": "src/app-managers/index.ts",
    "content": "export * from './app-manager';\nexport * from './app-manager-interface';\nexport * from './array-app-manager';\nexport * from './base-app-manager';\nexport * from './dynamodb-app-manager';\nexport * from './mysql-app-manager';\nexport * from './postgres-app-manager';\nexport * from './sql-app-manager';\n"
  },
  {
    "path": "src/app-managers/mysql-app-manager.ts",
    "content": "import { SqlAppManager } from './sql-app-manager';\n\nexport class MysqlAppManager extends SqlAppManager {\n    /**\n     * Get the client name to be used by Knex.\n     */\n    protected knexClientName(): string {\n        return this.server.options.appManager.mysql.useMysql2\n            ? 'mysql2'\n            : 'mysql';\n    }\n\n    /**\n     * Get the object connection details for Knex.\n     */\n    protected knexConnectionDetails(): { [key: string]: any; } {\n        return {\n            ...this.server.options.database.mysql,\n        };\n    }\n\n    /**\n     * Get the connection version for Knex.\n     * For MySQL can be 5.7 or 8.0, etc.\n     */\n    protected knexVersion(): string {\n        return this.server.options.appManager.mysql.version as string;\n    }\n\n    /**\n     * Wether the manager supports pooling. This introduces\n     * additional settings for connection pooling.\n     */\n    protected supportsPooling(): boolean {\n        return true;\n    }\n\n    /**\n     * Get the table name where the apps are stored.\n     */\n    protected appsTableName(): string {\n        return this.server.options.appManager.mysql.table;\n    }\n}\n"
  },
  {
    "path": "src/app-managers/postgres-app-manager.ts",
    "content": "import { SqlAppManager } from './sql-app-manager';\n\nexport class PostgresAppManager extends SqlAppManager {\n    /**\n     * Get the client name to be used by Knex.\n     */\n    protected knexClientName(): string {\n        return 'pg';\n    }\n\n    /**\n     * Get the object connection details for Knex.\n     */\n    protected knexConnectionDetails(): { [key: string]: any; } {\n        return {\n            ...this.server.options.database.postgres,\n        };\n    }\n\n    /**\n     * Get the connection version for Knex.\n     * For MySQL can be 5.7 or 8.0, etc.\n     */\n    protected knexVersion(): string {\n        return this.server.options.appManager.postgres.version as string;\n    }\n\n    /**\n     * Wether the manager supports pooling. This introduces\n     * additional settings for connection pooling.\n     */\n    protected supportsPooling(): boolean {\n        return true;\n    }\n\n    /**\n     * Get the table name where the apps are stored.\n     */\n    protected appsTableName(): string {\n        return this.server.options.appManager.postgres.table;\n    }\n}\n"
  },
  {
    "path": "src/app-managers/sql-app-manager.ts",
    "content": "import { App } from './../app';\nimport { BaseAppManager } from './base-app-manager';\nimport { Log } from '../log';\nimport { Knex, knex } from 'knex';\nimport { Server } from './../server';\n\nexport abstract class SqlAppManager extends BaseAppManager {\n    /**\n     * The Knex connection.\n     *\n     * @type {Knex}\n     */\n    protected connection: Knex;\n\n    /**\n     * Create a new app manager instance.\n     */\n    constructor(protected server: Server) {\n        super();\n\n        let knexConfig = {\n            client: this.knexClientName(),\n            connection: this.knexConnectionDetails(),\n            version: this.knexVersion(),\n        };\n\n        if (this.supportsPooling() && server.options.databasePooling.enabled) {\n            knexConfig = {\n                ...knexConfig,\n                ...{\n                    pool: {\n                        min: server.options.databasePooling.min,\n                        max: server.options.databasePooling.max,\n                    },\n                },\n            };\n        }\n\n        this.connection = knex(knexConfig);\n    }\n\n    /**\n     * Find an app by given ID.\n     */\n    findById(id: string): Promise<App|null> {\n        return this.selectById(id).then(apps => {\n            if (apps.length === 0) {\n                if (this.server.options.debug) {\n                    Log.error(`App ID not found: ${id}`);\n                }\n\n                return null;\n            }\n\n            return new App(apps[0] || apps, this.server);\n        });\n    }\n\n    /**\n     * Find an app by given key.\n     */\n    findByKey(key: string): Promise<App|null> {\n        return this.selectByKey(key).then(apps => {\n            if (apps.length === 0) {\n                if (this.server.options.debug) {\n                    Log.error(`App key not found: ${key}`);\n                }\n\n                return null;\n            }\n\n            return new App(apps[0] || apps, this.server);\n        });\n    }\n\n    /**\n     * Make a Knex selection for the app ID.\n     */\n    protected selectById(id: string): Promise<App[]> {\n        return this.connection<App>(this.appsTableName())\n            .where('id', id)\n            .select('*');\n    }\n\n    /**\n     * Make a Knex selection for the app key.\n     */\n    protected selectByKey(key: string): Promise<App[]> {\n        return this.connection<App>(this.appsTableName())\n            .where('key', key)\n            .select('*');\n    }\n\n    /**\n     * Get the client name to be used by Knex.\n     */\n    protected abstract knexClientName(): string;\n\n    /**\n     * Get the object connection details for Knex.\n     */\n    protected abstract knexConnectionDetails(): { [key: string]: any; };\n\n    /**\n     * Get the connection version for Knex.\n     * For MySQL can be 5.7 or 8.0, etc.\n     */\n    protected abstract knexVersion(): string;\n\n    /**\n     * Wether the manager supports pooling. This introduces\n     * additional settings for connection pooling.\n     */\n    protected abstract supportsPooling(): boolean;\n\n    /**\n     * Get the table name where the apps are stored.\n     */\n    protected abstract appsTableName(): string;\n}\n"
  },
  {
    "path": "src/app.ts",
    "content": "import { HttpResponse } from 'uWebSockets.js';\nimport { Lambda } from 'aws-sdk';\nimport { Server } from './server';\n\nconst Pusher = require('pusher');\nconst pusherUtil = require('pusher/lib/util');\n\nexport interface AppInterface {\n    id: string;\n    key: string;\n    secret: string;\n    maxConnections: string|number;\n    enableClientMessages: boolean;\n    enabled: boolean;\n    maxBackendEventsPerSecond?: string|number;\n    maxClientEventsPerSecond: string|number;\n    maxReadRequestsPerSecond?: string|number;\n    webhooks?: WebhookInterface[];\n    maxPresenceMembersPerChannel?: string|number;\n    maxPresenceMemberSizeInKb?: string|number;\n    maxChannelNameLength?: number;\n    maxEventChannelsAtOnce?: string|number;\n    maxEventNameLength?: string|number;\n    maxEventPayloadInKb?: string|number;\n    maxEventBatchSize?: string|number;\n    enableUserAuthentication?: boolean;\n    hasClientEventWebhooks?: boolean;\n    hasChannelOccupiedWebhooks?: boolean;\n    hasChannelVacatedWebhooks?: boolean;\n    hasMemberAddedWebhooks?: boolean;\n    hasMemberRemovedWebhooks?: boolean;\n}\n\nexport interface WebhookInterface {\n    url?: string;\n    headers?: {\n        [key: string]: string;\n    };\n    lambda_function?: string;\n    event_types: string[];\n    filter?: {\n        channel_name_starts_with?: string;\n        channel_name_ends_with?: string;\n    };\n    lambda: {\n        async?: boolean;\n        region?: string;\n        client_options?: Lambda.Types.ClientConfiguration,\n    };\n}\n\nexport class App implements AppInterface {\n    /**\n     * @type {string|number}\n     */\n    public id: string;\n\n    /**\n     * @type {string|number}\n     */\n    public key: string;\n\n    /**\n     * @type {string}\n     */\n    public secret: string;\n\n    /**\n     * @type {number}\n     */\n    public maxConnections: string|number;\n\n    /**\n     * @type {boolean}\n     */\n    public enableClientMessages: boolean;\n\n    /**\n     * @type {boolean}\n     */\n    public enabled: boolean;\n\n    /**\n     * @type {number}\n     */\n    public maxBackendEventsPerSecond: string|number;\n\n    /**\n     * @type {number}\n     */\n    public maxClientEventsPerSecond: string|number;\n\n    /**\n     * @type {number}\n     */\n    public maxReadRequestsPerSecond: string|number;\n\n    /**\n     * @type {WebhookInterface[]}\n     */\n    public webhooks: WebhookInterface[];\n\n    /**\n     * @type {string|number}\n     */\n    public maxPresenceMembersPerChannel: string|number;\n\n    /**\n     * @type {string|number}\n     */\n    public maxPresenceMemberSizeInKb: string|number;\n\n    /**\n     * @type {number}\n     */\n    public maxChannelNameLength: number;\n\n    /**\n     * @type {string|number}\n     */\n    public maxEventChannelsAtOnce: string|number;\n\n    /**\n     * @type {string|number}\n     */\n    public maxEventNameLength: string|number;\n\n    /**\n     * @type {string|number}\n     */\n    public maxEventPayloadInKb: string|number;\n\n    /**\n     * @type {string|number}\n     */\n    public maxEventBatchSize: string|number;\n\n    /**\n     * @type {boolean}\n     */\n    public enableUserAuthentication = false;\n\n    /**\n     * @type {boolean}\n     */\n    public hasClientEventWebhooks = false;\n\n    /**\n     * @type {boolean}\n     */\n    public hasChannelOccupiedWebhooks = false;\n\n    /**\n     * @type {boolean}\n     */\n    public hasChannelVacatedWebhooks = false;\n\n    /**\n     * @type {boolean}\n     */\n    public hasMemberAddedWebhooks = false;\n\n    /**\n     * @type {boolean}\n     */\n    public hasMemberRemovedWebhooks = false;\n\n    /**\n     * @type {boolean}\n     */\n    public hasCacheMissedWebhooks = false;\n\n    static readonly CLIENT_EVENT_WEBHOOK = 'client_event';\n    static readonly CHANNEL_OCCUPIED_WEBHOOK = 'channel_occupied';\n    static readonly CHANNEL_VACATED_WEBHOOK = 'channel_vacated';\n    static readonly MEMBER_ADDED_WEBHOOK = 'member_added';\n    static readonly MEMBER_REMOVED_WEBHOOK = 'member_removed';\n    static readonly CACHE_MISSED_WEBHOOK = 'cache_miss';\n\n    /**\n     * Create a new app from object.\n     */\n    constructor(public initialApp: { [key: string]: any; }, protected server: Server) {\n        this.id = this.extractFromPassedKeys(initialApp, ['id', 'AppId'], 'app-id');\n        this.key = this.extractFromPassedKeys(initialApp, ['key', 'AppKey'], 'app-key');\n        this.secret = this.extractFromPassedKeys(initialApp, ['secret', 'AppSecret'], 'app-secret');\n        this.maxConnections = this.extractFromPassedKeys(initialApp, ['maxConnections', 'MaxConnections', 'max_connections'], -1);\n        this.enableClientMessages = this.extractFromPassedKeys(initialApp, ['enableClientMessages', 'EnableClientMessages', 'enable_client_messages'], false);\n        this.enabled = this.extractFromPassedKeys(initialApp, ['enabled', 'Enabled'], true);\n        this.maxBackendEventsPerSecond = parseInt(this.extractFromPassedKeys(initialApp, ['maxBackendEventsPerSecond', 'MaxBackendEventsPerSecond', 'max_backend_events_per_sec'], -1));\n        this.maxClientEventsPerSecond = parseInt(this.extractFromPassedKeys(initialApp, ['maxClientEventsPerSecond', 'MaxClientEventsPerSecond', 'max_client_events_per_sec'], -1));\n        this.maxReadRequestsPerSecond = parseInt(this.extractFromPassedKeys(initialApp, ['maxReadRequestsPerSecond', 'MaxReadRequestsPerSecond', 'max_read_req_per_sec'], -1));\n        this.webhooks = this.transformPotentialJsonToArray(this.extractFromPassedKeys(initialApp, ['webhooks', 'Webhooks'], '[]'));\n        this.maxPresenceMembersPerChannel = parseInt(this.extractFromPassedKeys(initialApp, ['maxPresenceMembersPerChannel', 'MaxPresenceMembersPerChannel', 'max_presence_members_per_channel'], server.options.presence.maxMembersPerChannel));\n        this.maxPresenceMemberSizeInKb = parseFloat(this.extractFromPassedKeys(initialApp, ['maxPresenceMemberSizeInKb', 'MaxPresenceMemberSizeInKb', 'max_presence_member_size_in_kb'], server.options.presence.maxMemberSizeInKb));\n        this.maxChannelNameLength = parseInt(this.extractFromPassedKeys(initialApp, ['maxChannelNameLength', 'MaxChannelNameLength', 'max_channel_name_length'], server.options.channelLimits.maxNameLength));\n        this.maxEventChannelsAtOnce = parseInt(this.extractFromPassedKeys(initialApp, ['maxEventChannelsAtOnce', 'MaxEventChannelsAtOnce', 'max_event_channels_at_once'], server.options.eventLimits.maxChannelsAtOnce));\n        this.maxEventNameLength = parseInt(this.extractFromPassedKeys(initialApp, ['maxEventNameLength', 'MaxEventNameLength', 'max_event_name_length'], server.options.eventLimits.maxNameLength));\n        this.maxEventPayloadInKb = parseFloat(this.extractFromPassedKeys(initialApp, ['maxEventPayloadInKb', 'MaxEventPayloadInKb', 'max_event_payload_in_kb'], server.options.eventLimits.maxPayloadInKb));\n        this.maxEventBatchSize = parseInt(this.extractFromPassedKeys(initialApp, ['maxEventBatchSize', 'MaxEventBatchSize', 'max_event_batch_size'], server.options.eventLimits.maxBatchSize));\n        this.enableUserAuthentication = this.extractFromPassedKeys(initialApp, ['enableUserAuthentication', 'EnableUserAuthentication', 'enable_user_authentication'], false);\n\n        this.hasClientEventWebhooks = this.webhooks.filter(webhook => webhook.event_types.includes(App.CLIENT_EVENT_WEBHOOK)).length > 0;\n        this.hasChannelOccupiedWebhooks = this.webhooks.filter(webhook => webhook.event_types.includes(App.CHANNEL_OCCUPIED_WEBHOOK)).length > 0;\n        this.hasChannelVacatedWebhooks = this.webhooks.filter(webhook => webhook.event_types.includes(App.CHANNEL_VACATED_WEBHOOK)).length > 0;\n        this.hasMemberAddedWebhooks = this.webhooks.filter(webhook => webhook.event_types.includes(App.MEMBER_ADDED_WEBHOOK)).length > 0;\n        this.hasMemberRemovedWebhooks = this.webhooks.filter(webhook => webhook.event_types.includes(App.MEMBER_REMOVED_WEBHOOK)).length > 0;\n        this.hasCacheMissedWebhooks = this.webhooks.filter(webhook => webhook.event_types.includes(App.CACHE_MISSED_WEBHOOK)).length > 0;\n    }\n\n    /**\n     * Get the app represented as object.\n     */\n    toObject(): AppInterface {\n        return {\n            id: this.id,\n            key: this.key,\n            secret: this.secret,\n            maxConnections: this.maxConnections,\n            enableClientMessages: this.enableClientMessages,\n            enabled: this.enabled,\n            maxBackendEventsPerSecond: this.maxBackendEventsPerSecond,\n            maxClientEventsPerSecond: this.maxClientEventsPerSecond,\n            maxReadRequestsPerSecond: this.maxReadRequestsPerSecond,\n            webhooks: this.webhooks,\n            maxPresenceMembersPerChannel: this.maxPresenceMembersPerChannel,\n            maxPresenceMemberSizeInKb: this.maxPresenceMemberSizeInKb,\n            maxChannelNameLength: this.maxChannelNameLength,\n            maxEventChannelsAtOnce: this.maxEventChannelsAtOnce,\n            maxEventNameLength: this.maxEventNameLength,\n            maxEventPayloadInKb: this.maxEventPayloadInKb,\n            maxEventBatchSize: this.maxEventBatchSize,\n            enableUserAuthentication: this.enableUserAuthentication,\n        }\n    }\n\n    /**\n     * Get the app represented as JSON.\n     */\n    toJson(): string {\n        return JSON.stringify(this.toObject());\n    }\n\n    /**\n     * Strip data off the app, usually the one that's not needed from the WS's perspective.\n     * Usually used when attached to WS connections, as they don't need these details.\n     */\n    forWebSocket(): App {\n        let app = new App(this.initialApp, this.server);\n\n        // delete app.secret;\n        delete app.maxBackendEventsPerSecond;\n        delete app.maxReadRequestsPerSecond;\n        delete app.webhooks;\n\n        return app;\n    }\n\n    /**\n     * Get the signing token from the request.\n     */\n    signingTokenFromRequest(res: HttpResponse): string {\n        const params = {\n            auth_key: this.key,\n            auth_timestamp: res.query.auth_timestamp,\n            auth_version: res.query.auth_version,\n            ...res.query,\n        };\n\n        delete params['auth_signature'];\n        delete params['body_md5']\n        delete params['appId'];\n        delete params['appKey'];\n        delete params['channelName'];\n\n        if (res.rawBody || res.query['body_md5']) {\n            params['body_md5'] = pusherUtil.getMD5(res.rawBody || '');\n        }\n\n        return this.signingToken(\n            res.method,\n            res.url,\n            pusherUtil.toOrderedArray(params).join('&'),\n        );\n    }\n\n    /**\n     * Get the signing token for the given parameters.\n     */\n    protected signingToken(method: string, path: string, params: string): string {\n        let token = new Pusher.Token(this.key, this.secret);\n\n        return token.sign([method, path, params].join(\"\\n\"));\n    }\n\n    /**\n     * Due to cross-database schema, it's worth to search multiple fields in the app in order to assign it\n     * to the local App object. For example, the local `enableClientMessages` attribute can exist as\n     * enableClientMessages, enable_client_messages, or EnableClientMessages. With this function, we pass\n     * the app, the list of all field posibilities, and a default value.\n     * This check is done with a typeof check over undefined, to make sure that false booleans or 0 values\n     * are being parsed properly and are not being ignored.\n     */\n    protected extractFromPassedKeys(app: { [key: string]: any; }, parameters: string[], defaultValue: any): any {\n        let extractedValue = defaultValue;\n\n        parameters.forEach(param => {\n            if (typeof app[param] !== 'undefined' && !['', null].includes(app[param])) {\n                extractedValue = app[param];\n            }\n        });\n\n        return extractedValue;\n    }\n\n    /**\n     * If it's already an array, it returns the array. For an invalid JSON, it returns an empty array.\n     * If it's a JSON-formatted string, it parses it and returns the value.\n     */\n    protected transformPotentialJsonToArray(potentialJson: any): any {\n        if (potentialJson instanceof Array) {\n            return potentialJson;\n        }\n\n        try {\n            let potentialArray = JSON.parse(potentialJson);\n\n            if (potentialArray instanceof Array) {\n                return potentialArray;\n            }\n        } catch (e) {\n            //\n        }\n\n        return [];\n    }\n}\n"
  },
  {
    "path": "src/cache-managers/cache-manager-interface.ts",
    "content": "import Redis, { Cluster } from 'ioredis';\n\nexport interface CacheManagerInterface {\n    /**\n     * The cache interface manager driver.\n     */\n    driver?: CacheManagerInterface;\n\n    /**\n     * The Redis connection.\n     */\n    redisConnection?: Redis|Cluster;\n\n    /**\n     * Check if the given key exists in cache.\n     */\n    has(key: string): Promise<boolean>;\n\n    /**\n     * Check if the given key exists in cache.\n     * Returns false-returning value if cache does not exist.\n     */\n    get(key: string): Promise<any>;\n\n    /**\n     * Set or overwrite the value in the cache.\n     */\n    set(key: string, value: any, ttlSeconds: number): Promise<any>;\n\n    /**\n     * Disconnect the manager's made connections.\n     */\n    disconnect(): Promise<void>;\n}\n"
  },
  {
    "path": "src/cache-managers/cache-manager.ts",
    "content": "import { CacheManagerInterface } from './cache-manager-interface';\nimport { Log } from '../log';\nimport { MemoryCacheManager } from './memory-cache-manager';\nimport { RedisCacheManager } from './redis-cache-manager';\nimport { Server } from '../server';\n\nexport class CacheManager implements CacheManagerInterface {\n    /**\n     * The cache interface manager driver.\n     */\n    public driver: CacheManagerInterface;\n\n    /**\n     * Create a new cache instance.\n     */\n    constructor(protected server: Server) {\n        if (server.options.cache.driver === 'memory') {\n            this.driver = new MemoryCacheManager(server);\n        } else if (server.options.cache.driver === 'redis') {\n            this.driver = new RedisCacheManager(server);\n        } else {\n            Log.error('Cache driver not set.');\n        }\n    }\n\n    /**\n     * Check if the given key exists in cache.\n     */\n    has(key: string): Promise<boolean> {\n        return this.driver.has(key);\n    }\n\n     /**\n      * Check if the given key exists in cache.\n      * Returns false-returning value if cache does not exist.\n      */\n    get(key: string): Promise<any> {\n        return this.driver.get(key);\n    }\n\n     /**\n      * Set or overwrite the value in the cache.\n      */\n    set(key: string, value: any, ttlSeconds: number): Promise<any> {\n        return this.driver.set(key, value, ttlSeconds);\n    }\n\n    /**\n     * Disconnect the manager's made connections.\n     */\n    disconnect(): Promise<void> {\n        return this.driver.disconnect();\n    }\n}\n"
  },
  {
    "path": "src/cache-managers/index.ts",
    "content": "export * from './cache-manager';\nexport * from './cache-manager-interface';\nexport * from './memory-cache-manager';\nexport * from './redis-cache-manager';\n"
  },
  {
    "path": "src/cache-managers/memory-cache-manager.ts",
    "content": "import { CacheManagerInterface } from './cache-manager-interface';\nimport { Server } from '../server';\n\ninterface Memory {\n    [key: string]: {\n        value: any;\n        ttlSeconds: number;\n        setTime: number;\n    };\n}\n\nexport class MemoryCacheManager implements CacheManagerInterface {\n    /**\n     * The cache storage as in-memory.\n     */\n    protected memory: Memory = {\n        //\n    };\n\n    /**\n     * Create a new memory cache instance.\n     */\n    constructor(protected server: Server) {\n        setInterval(() => {\n            for (let [key, { ttlSeconds, setTime }] of Object.entries(this.memory)) {\n                let currentTime = parseInt((new Date().getTime() / 1000) as unknown as string);\n\n                if (ttlSeconds > 0 && (setTime + ttlSeconds) <= currentTime) {\n                    delete this.memory[key];\n                }\n            }\n        }, 1_000);\n    }\n\n    /**\n     * Check if the given key exists in cache.\n     */\n    has(key: string): Promise<boolean> {\n        return Promise.resolve(typeof this.memory[key] !== 'undefined' ? Boolean(this.memory[key]) : false);\n    }\n\n    /**\n     * Get a key from the cache.\n     * Returns false-returning value if cache does not exist.\n     */\n    get(key: string): Promise<any> {\n        return Promise.resolve(typeof this.memory[key] !== 'undefined' ? this.memory[key].value : null);\n    }\n\n    /**\n     * Set or overwrite the value in the cache.\n     */\n    set(key: string, value: any, ttlSeconds = -1): Promise<any> {\n        this.memory[key] = {\n            value,\n            ttlSeconds,\n            setTime: parseInt((new Date().getTime() / 1000) as unknown as string),\n        };\n\n        return Promise.resolve(true);\n    }\n\n    /**\n     * Disconnect the manager's made connections.\n     */\n    disconnect(): Promise<void> {\n        this.memory = {};\n\n        return Promise.resolve();\n    }\n}\n"
  },
  {
    "path": "src/cache-managers/redis-cache-manager.ts",
    "content": "import { CacheManagerInterface } from './cache-manager-interface';\nimport Redis, { Cluster, ClusterOptions, RedisOptions } from 'ioredis';\nimport { Server } from '../server';\n\nexport class RedisCacheManager implements CacheManagerInterface {\n    /**\n     * The Redis connection.\n     */\n    public redisConnection: Redis|Cluster;\n\n    /**\n     * Create a new Redis cache instance.\n     */\n    constructor(protected server: Server) {\n        let redisOptions: RedisOptions|ClusterOptions = {\n            ...server.options.database.redis,\n            ...server.options.cache.redis.redisOptions,\n        };\n\n        this.redisConnection = server.options.cache.redis.clusterMode\n            ? new Cluster(server.options.database.redis.clusterNodes, {\n                scaleReads: 'slave',\n                ...redisOptions,\n            })\n            : new Redis(redisOptions);\n    }\n\n    /**\n     * Check if the given key exists in cache.\n     */\n    has(key: string): Promise<boolean> {\n        return this.get(key).then(result => {\n            return result ? true : false;\n        });\n    }\n\n    /**\n     * Get a key from the cache.\n     * Returns false-returning value if cache does not exist.\n     */\n    get(key: string): Promise<any> {\n        return this.redisConnection.get(key);\n    }\n\n    /**\n     * Set or overwrite the value in the cache.\n     */\n    set(key: string, value: any, ttlSeconds = -1): Promise<any> {\n        return ttlSeconds > 0\n            ? this.redisConnection.set(key, value, 'EX', ttlSeconds)\n            : this.redisConnection.set(key, value);\n    }\n\n    /**\n     * Disconnect the manager's made connections.\n     */\n    disconnect(): Promise<void> {\n        return this.redisConnection.quit().then(() => {\n            //\n        });\n    }\n}\n"
  },
  {
    "path": "src/channels/encrypted-private-channel-manager.ts",
    "content": "import { PrivateChannelManager } from './private-channel-manager';\n\nexport class EncryptedPrivateChannelManager extends PrivateChannelManager {\n    //\n}\n"
  },
  {
    "path": "src/channels/index.ts",
    "content": "export * from './encrypted-private-channel-manager';\nexport * from './presence-channel-manager';\nexport * from './private-channel-manager';\nexport * from './public-channel-manager';\n"
  },
  {
    "path": "src/channels/presence-channel-manager.ts",
    "content": "import { JoinResponse, LeaveResponse } from './public-channel-manager';\nimport { Log } from '../log';\nimport { PrivateChannelManager } from './private-channel-manager';\nimport { PusherMessage } from '../message';\nimport { Utils } from '../utils';\nimport { WebSocket } from 'uWebSockets.js';\n\nexport interface PresenceMemberInfo {\n    [key: string]: any;\n}\n\nexport interface PresenceMember {\n    user_id: number|string;\n    user_info: PresenceMemberInfo;\n    socket_id?: string;\n}\n\nexport class PresenceChannelManager extends PrivateChannelManager {\n    /**\n     * Join the connection to the channel.\n     */\n    join(ws: WebSocket, channel: string, message?: PusherMessage): Promise<JoinResponse> {\n        return this.server.adapter.getChannelMembersCount(ws.app.id, channel).then(membersCount => {\n            if (membersCount + 1 > ws.app.maxPresenceMembersPerChannel) {\n                return {\n                    success: false,\n                    ws,\n                    errorCode: 4100,\n                    errorMessage: 'The maximum members per presence channel limit was reached',\n                    type: 'LimitReached',\n                };\n            }\n\n            let member: PresenceMember = JSON.parse(message.data.channel_data);\n\n            let memberSizeInKb = Utils.dataToKilobytes(member.user_info);\n\n            if (memberSizeInKb > ws.app.maxPresenceMemberSizeInKb) {\n                return {\n                    success: false,\n                    ws,\n                    errorCode: 4301,\n                    errorMessage: `The maximum size for a channel member is ${ws.app.maxPresenceMemberSizeInKb} KB.`,\n                    type: 'LimitReached',\n                };\n            }\n\n            return super.join(ws, channel, message).then(response => {\n                // Make sure to forward the response in case an error occurs.\n                if (!response.success) {\n                    return response;\n                }\n\n                return {\n                    ...response,\n                    ...{\n                        member,\n                    },\n                };\n            });\n        }).catch(err => {\n            Log.error(err);\n            return {\n                success: false,\n                ws,\n                errorCode: 4302,\n                errorMessage: 'A server error has occured.',\n                type: 'ServerError',\n            };\n        });\n    }\n\n    /**\n     * Mark the connection as closed and unsubscribe it.\n     */\n    leave(ws: WebSocket, channel: string): Promise<LeaveResponse> {\n        return super.leave(ws, channel).then(response => {\n            return {\n                ...response,\n                ...{\n                    member: ws.presence.get(channel),\n                },\n            };\n        });\n    }\n\n    /**\n     * Get the data to sign for the token for specific channel.\n     */\n    protected getDataToSignForSignature(socketId: string, message: PusherMessage): string {\n        return `${socketId}:${message.data.channel}:${message.data.channel_data}`;\n    }\n}\n"
  },
  {
    "path": "src/channels/private-channel-manager.ts",
    "content": "import { App } from '../app';\nimport { JoinResponse, PublicChannelManager } from './public-channel-manager';\nimport { PusherMessage } from '../message';\nimport { WebSocket } from 'uWebSockets.js';\n\nconst Pusher = require('pusher');\n\nexport class PrivateChannelManager extends PublicChannelManager {\n    /**\n     * Join the connection to the channel.\n     */\n    join(ws: WebSocket, channel: string, message?: PusherMessage): Promise<JoinResponse> {\n        let passedSignature = message?.data?.auth;\n\n        return this.signatureIsValid(ws.app, ws.id, message, passedSignature).then(isValid => {\n            if (!isValid) {\n                return {\n                    ws,\n                    success: false,\n                    errorCode: 4009,\n                    errorMessage: 'The connection is unauthorized.',\n                    authError: true,\n                    type: 'AuthError',\n                };\n            }\n\n            return super.join(ws, channel, message).then(joinResponse => {\n                // If the users joined to a private channel with authentication,\n                // proceed clearing the authentication timeout.\n                if (joinResponse.success && ws.userAuthenticationTimeout) {\n                    clearTimeout(ws.userAuthenticationTimeout);\n                }\n\n                return joinResponse;\n            });\n        });\n    }\n\n    /**\n     * Check is an incoming connection can subscribe.\n     */\n    protected signatureIsValid(app: App, socketId: string, message: PusherMessage, signatureToCheck: string): Promise<boolean> {\n        return this.getExpectedSignature(app, socketId, message).then(expectedSignature => {\n            return signatureToCheck === expectedSignature;\n        });\n    }\n\n    /**\n     * Get the signed token from the given message, by the Socket.\n     */\n    protected getExpectedSignature(app: App, socketId: string, message: PusherMessage): Promise<string> {\n        return new Promise(resolve => {\n            let token = new Pusher.Token(app.key, app.secret);\n\n            resolve(\n                app.key + ':' + token.sign(this.getDataToSignForSignature(socketId, message))\n            );\n        });\n    }\n\n    /**\n     * Get the data to sign for the token for specific channel.\n     */\n    protected getDataToSignForSignature(socketId: string, message: PusherMessage): string {\n        return `${socketId}:${message.data.channel}`;\n    }\n}\n"
  },
  {
    "path": "src/channels/public-channel-manager.ts",
    "content": "import { PresenceMember } from '../channels/presence-channel-manager';\nimport { PusherMessage } from '../message';\nimport { Server } from '../server';\nimport { Utils } from '../utils';\nimport { WebSocket } from 'uWebSockets.js';\n\nexport interface JoinResponse {\n    ws: WebSocket;\n    success: boolean;\n    channelConnections?: number;\n    authError?: boolean;\n    member?: PresenceMember;\n    errorMessage?: string;\n    errorCode?: number;\n    type?: string;\n}\n\nexport interface LeaveResponse {\n    left: boolean;\n    remainingConnections?: number;\n    member?: PresenceMember;\n}\n\nexport class PublicChannelManager {\n    constructor(protected server: Server) {\n        //\n    }\n\n    /**\n     * Join the connection to the channel.\n     */\n    join(ws: WebSocket, channel: string, message?: PusherMessage): Promise<JoinResponse> {\n        if (Utils.restrictedChannelName(channel)) {\n            return Promise.resolve({\n                ws,\n                success: false,\n                errorCode: 4009,\n                errorMessage: 'The channel name is not allowed. Read channel conventions: https://pusher.com/docs/channels/using_channels/channels/#channel-naming-conventions',\n            });\n        }\n\n        if (!ws.app) {\n            return Promise.resolve({\n                ws,\n                success: false,\n                errorCode: 4009,\n                errorMessage: 'Subscriptions messages should be sent after the pusher:connection_established event is received.',\n            });\n        }\n\n        return this.server.adapter.addToChannel(ws.app.id, channel, ws).then(connections => {\n            return {\n                ws,\n                success: true,\n                channelConnections: connections,\n            };\n        });\n    }\n\n    /**\n     * Mark the connection as closed and unsubscribe it.\n     */\n    leave(ws: WebSocket, channel: string): Promise<LeaveResponse> {\n        return this.server.adapter.removeFromChannel(ws.app.id, channel, ws.id).then((remainingConnections) => {\n            return {\n                left: true,\n                remainingConnections: remainingConnections as number,\n            };\n        });\n    }\n}\n"
  },
  {
    "path": "src/cli/cli.ts",
    "content": "import { readFileSync } from 'fs';\nimport { Log } from '..';\nimport { Server } from './../server';\n\nexport class Cli {\n    /**\n     * The server to run.\n     */\n    public server: Server;\n\n    /**\n     * Allowed environment variables.\n     *\n     * @type {any}\n     */\n    public envVariables: { [key: string]: string; } = {\n        ADAPTER_DRIVER: 'adapter.driver',\n        ADAPTER_CLUSTER_REQUESTS_TIMEOUT: 'adapter.cluster.requestsTimeout',\n        ADAPTER_REDIS_PREFIX: 'adapter.redis.prefix',\n        ADAPTER_REDIS_CLUSTER_MODE: 'adapter.redis.clusterMode',\n        ADAPTER_REDIS_REQUESTS_TIMEOUT: 'adapter.redis.requestsTimeout',\n        ADAPTER_REDIS_SUB_OPTIONS: 'adapter.redis.redisSubOptions',\n        ADAPTER_REDIS_PUB_OPTIONS: 'adapter.redis.redisPubOptions',\n        ADAPTER_NATS_PREFIX: 'adapter.nats.prefix',\n        ADAPTER_NATS_SERVERS: 'adapter.nats.servers',\n        ADAPTER_NATS_USER: 'adapter.nats.user',\n        ADAPTER_NATS_PASSWORD: 'adapter.nats.pass',\n        ADAPTER_NATS_TOKEN: 'adapter.nats.token',\n        ADAPTER_NATS_TIMEOUT: 'adapter.nats.timeout',\n        ADAPTER_NATS_REQUESTS_TIMEOUT: 'adapter.nats.requestsTimeout',\n        ADAPTER_NATS_NODES_NUMBER: 'adapter.nats.nodesNumber',\n        APP_MANAGER_DRIVER: 'appManager.driver',\n        APP_MANAGER_CACHE_ENABLED: 'appManager.cache.enabled',\n        APP_MANAGER_CACHE_TTL: 'appManager.cache.ttl',\n        APP_MANAGER_DYNAMODB_TABLE: 'appManager.dynamodb.table',\n        APP_MANAGER_DYNAMODB_REGION: 'appManager.dynamodb.region',\n        APP_MANAGER_DYNAMODB_ENDPOINT: 'appManager.dynamodb.endpoint',\n        APP_MANAGER_MYSQL_TABLE: 'appManager.mysql.table',\n        APP_MANAGER_MYSQL_VERSION: 'appManager.mysql.version',\n        APP_MANAGER_POSTGRES_TABLE: 'appManager.postgres.table',\n        APP_MANAGER_POSTGRES_VERSION: 'appManager.postgres.version',\n        APP_MANAGER_MYSQL_USE_V2: 'appManager.mysql.useMysql2',\n        CHANNEL_LIMITS_MAX_NAME_LENGTH: 'channelLimits.maxNameLength',\n        CHANNEL_CACHE_TTL: 'channelLimits.cacheTtl',\n        CACHE_DRIVER: 'cache.driver',\n        CACHE_REDIS_CLUSTER_MODE: 'cache.redis.clusterMode',\n        CACHE_REDIS_OPTIONS: 'cache.redis.redisOptions',\n        CLUSTER_CHECK_INTERVAL: 'cluster.checkInterval',\n        CLUSTER_HOST: 'cluster.hostname',\n        CLUSTER_IGNORE_PROCESS: 'cluster.ignoreProcess',\n        CLUSTER_BROADCAST_ADDRESS: 'cluster.broadcast',\n        CLUSTER_KEEPALIVE_INTERVAL: 'cluster.helloInterval',\n        CLUSTER_MASTER_TIMEOUT: 'cluster.masterTimeout',\n        CLUSTER_MULTICAST_ADDRESS: 'cluster.multicast',\n        CLUSTER_NODE_TIMEOUT: 'cluster.nodeTimeout',\n        CLUSTER_PORT: 'cluster.port',\n        CLUSTER_PREFIX: 'cluster.prefix',\n        CLUSTER_UNICAST_ADDRESSES: 'cluster.unicast',\n        DEBUG: 'debug',\n        DEFAULT_APP_ID: 'appManager.array.apps.0.id',\n        DEFAULT_APP_KEY: 'appManager.array.apps.0.key',\n        DEFAULT_APP_SECRET: 'appManager.array.apps.0.secret',\n        DEFAULT_APP_MAX_CONNS: 'appManager.array.apps.0.maxConnections',\n        DEFAULT_APP_ENABLE_CLIENT_MESSAGES: 'appManager.array.apps.0.enableClientMessages',\n        DEFAULT_APP_ENABLED: 'appManager.array.apps.0.enabled',\n        DEFAULT_APP_MAX_BACKEND_EVENTS_PER_SEC: 'appManager.array.apps.0.maxBackendEventsPerSecond',\n        DEFAULT_APP_MAX_CLIENT_EVENTS_PER_SEC: 'appManager.array.apps.0.maxClientEventsPerSecond',\n        DEFAULT_APP_MAX_READ_REQ_PER_SEC: 'appManager.array.apps.0.maxReadRequestsPerSecond',\n        DEFAULT_APP_USER_AUTHENTICATION: 'appManager.array.apps.0.enableUserAuthentication',\n        DEFAULT_APP_WEBHOOKS: 'appManager.array.apps.0.webhooks',\n        DB_POOLING_ENABLED: 'databasePooling.enabled',\n        DB_POOLING_MIN: 'databasePooling.min',\n        DB_POOLING_MAX: 'databasePooling.max',\n        DB_MYSQL_HOST: 'database.mysql.host',\n        DB_MYSQL_PORT: 'database.mysql.port',\n        DB_MYSQL_USERNAME: 'database.mysql.user',\n        DB_MYSQL_PASSWORD: 'database.mysql.password',\n        DB_MYSQL_DATABASE: 'database.mysql.database',\n        DB_POSTGRES_HOST: 'database.postgres.host',\n        DB_POSTGRES_PORT: 'database.postgres.port',\n        DB_POSTGRES_USERNAME: 'database.postgres.user',\n        DB_POSTGRES_PASSWORD: 'database.postgres.password',\n        DB_POSTGRES_DATABASE: 'database.postgres.database',\n        DB_REDIS_HOST: 'database.redis.host',\n        DB_REDIS_PORT: 'database.redis.port',\n        DB_REDIS_DB: 'database.redis.db',\n        DB_REDIS_USERNAME: 'database.redis.username',\n        DB_REDIS_PASSWORD: 'database.redis.password',\n        DB_REDIS_KEY_PREFIX: 'database.redis.keyPrefix',\n        DB_REDIS_SENTINELS: 'database.redis.sentinels',\n        DB_REDIS_SENTINEL_PASSWORD: 'database.redis.sentinelPassword',\n        DB_REDIS_CLUSTER_NODES: 'database.redis.clusterNodes',\n        DB_REDIS_INSTANCE_NAME: 'database.redis.name',\n        EVENT_MAX_BATCH_SIZE: 'eventLimits.maxBatchSize',\n        EVENT_MAX_CHANNELS_AT_ONCE: 'eventLimits.maxChannelsAtOnce',\n        EVENT_MAX_NAME_LENGTH: 'eventLimits.maxNameLength',\n        EVENT_MAX_SIZE_IN_KB: 'eventLimits.maxPayloadInKb',\n        HOST: 'host',\n        HTTP_ACCEPT_TRAFFIC_MEMORY_THRESHOLD: 'httpApi.acceptTraffic.memoryThreshold',\n        METRICS_ENABLED: 'metrics.enabled',\n        METRICS_DRIVER: 'metrics.driver',\n        METRICS_HOST: 'metrics.host',\n        METRICS_PROMETHEUS_PREFIX: 'metrics.prometheus.prefix',\n        METRICS_SERVER_PORT: 'metrics.port',\n        MODE: 'mode',\n        PORT: 'port',\n        PATH_PREFIX: 'pathPrefix',\n        PRESENCE_MAX_MEMBER_SIZE: 'presence.maxMemberSizeInKb',\n        PRESENCE_MAX_MEMBERS: 'presence.maxMembersPerChannel',\n        QUEUE_DRIVER: 'queue.driver',\n        QUEUE_REDIS_CONCURRENCY: 'queue.redis.concurrency',\n        QUEUE_REDIS_OPTIONS: 'queue.redis.redisOptions',\n        QUEUE_REDIS_CLUSTER_MODE: 'queue.redis.clusterMode',\n        QUEUE_SQS_REGION: 'queue.sqs.region',\n        QUEUE_SQS_CLIENT_OPTIONS: 'queue.sqs.clientOptions',\n        QUEUE_SQS_URL: 'queue.sqs.queueUrl',\n        QUEUE_SQS_ENDPOINT: 'queue.sqs.endpoint',\n        QUEUE_SQS_PROCESS_BATCH: 'queue.sqs.processBatch',\n        QUEUE_SQS_BATCH_SIZE: 'queue.sqs.batchSize',\n        QUEUE_SQS_POLLING_WAIT_TIME_MS: 'queue.sqs.pollingWaitTimeMs',\n        RATE_LIMITER_DRIVER: 'rateLimiter.driver',\n        RATE_LIMITER_REDIS_OPTIONS: 'rateLimiter.redis.redisOptions',\n        RATE_LIMITER_REDIS_CLUSTER_MODE: 'rateLimiter.redis.clusterMode',\n        SHUTDOWN_GRACE_PERIOD: 'shutdownGracePeriod',\n        SSL_CERT: 'ssl.certPath',\n        SSL_KEY: 'ssl.keyPath',\n        SSL_PASS: 'ssl.passphrase',\n        SSL_CA: 'ssl.caPath',\n        USER_AUTHENTICATION_TIMEOUT: 'userAuthenticationTimeout',\n        WEBHOOKS_BATCHING: 'webhooks.batching.enabled',\n        WEBHOOKS_BATCHING_DURATION: 'webhooks.batching.duration',\n    };\n\n    /**\n     * Create new CLI instance.\n     */\n    constructor(protected pm2 = false) {\n        this.server = new Server;\n        this.server.pm2 = pm2;\n    }\n\n    /**\n     * Inject the .env vars into options if they exist.\n     */\n    protected overwriteOptionsFromEnv(): void {\n        require('dotenv').config();\n\n        for (let envVar in this.envVariables) {\n            let value = process.env[`SOKETI_${envVar}`] || null;\n            let optionKey = this.envVariables[envVar.replace('SOKETI_', '')];\n\n            if (value !== null) {\n                let json = null;\n\n                if (typeof value === 'string') {\n                    try {\n                        json = JSON.parse(value);\n                    } catch (e) {\n                        json = null;\n                    }\n\n                    if (json !== null) {\n                        value = json;\n                    }\n                }\n\n                let settingObject = {};\n                settingObject[optionKey] = value;\n\n                this.server.setOptions(settingObject);\n            }\n        }\n    }\n\n    /**\n     * Inject the variables from a config file.\n     */\n    protected overwriteOptionsFromConfig(path?: string): void {\n        if (!path) {\n            return;\n        }\n\n        try {\n            let config = JSON.parse(readFileSync(path, { encoding: 'utf-8' }));\n\n            for (let optionKey in config) {\n                let value = config[optionKey];\n                let settingObject = {};\n\n                settingObject[optionKey] = value;\n\n                this.server.setOptions(settingObject);\n            }\n        } catch (e) {\n            Log.errorTitle('There was an error while parsing the JSON in your config file. It has not been loaded.');\n        }\n    }\n\n    /**\n     * Start the server.\n     */\n    static async start(cliArgs: any): Promise<any> {\n        return (new Cli).start(cliArgs);\n    }\n\n    /**\n     * Start the server with PM2 support.\n     */\n    static async startWithPm2(cliArgs: any): Promise<any> {\n        return (new Cli(true)).start(cliArgs);\n    }\n\n    /**\n     * Start the server.\n     */\n    async start(cliArgs: any): Promise<any> {\n        this.overwriteOptionsFromConfig(cliArgs ? cliArgs.config : null);\n        this.overwriteOptionsFromEnv();\n\n        const handleFailure = () => {\n            this.server.stop().then(() => {\n                process.exit();\n            });\n        }\n\n        process.on('SIGINT', handleFailure);\n        process.on('SIGHUP', handleFailure);\n        process.on('SIGTERM', handleFailure);\n\n        process.on('uncaughtException', (err, origin) => {\n            Log.error('process uncaughtException');\n            Log.error({ err, origin });\n            handleFailure();\n        });\n\n        return this.server.start();\n    }\n}\n"
  },
  {
    "path": "src/cli/index.ts",
    "content": "import { Cli } from './cli';\n\nlet yargs = require('yargs')\n    .usage('Usage: soketi <command> [options]')\n    .command('start', 'Start the server.', yargs => {\n        return yargs.option('config', { describe: 'The path for the config file. (optional)'});\n    }, (argv) => Cli.start(argv))\n    .demandCommand(1, 'Please provide a valid command.')\n    .help('help')\n    .alias('help', 'h');\n\nyargs.$0 = '';\n\nlet argv = yargs.argv;\n"
  },
  {
    "path": "src/http-handler.ts",
    "content": "import { App } from './app';\nimport async from 'async';\nimport { HttpResponse, RecognizedString } from 'uWebSockets.js';\nimport { PusherApiMessage } from './message';\nimport { Server } from './server';\nimport { Utils } from './utils';\nimport { Log } from './log';\n\nconst v8 = require('v8');\n\nexport interface ChannelResponse {\n    subscription_count: number;\n    user_count?: number;\n    occupied: boolean;\n}\n\nexport interface MessageCheckError {\n    message: string;\n    code: number;\n}\n\nexport class HttpHandler {\n    /**\n     * Initialize the HTTP handler.\n     */\n    constructor(protected server: Server) {\n        //\n    }\n\n    ready(res: HttpResponse) {\n        this.attachMiddleware(res, [\n            this.corkMiddleware,\n            this.corsMiddleware,\n        ]).then(res => {\n            if (this.server.closing) {\n                this.serverErrorResponse(res, 'The server is closing. Choose another server. :)');\n            } else {\n                this.send(res, 'OK');\n            }\n        });\n    }\n\n    acceptTraffic(res: HttpResponse) {\n        this.attachMiddleware(res, [\n            this.corsMiddleware,\n        ]).then(res => {\n            if (this.server.closing) {\n                return this.serverErrorResponse(res, 'The server is closing. Choose another server. :)');\n            }\n\n            let threshold = this.server.options.httpApi.acceptTraffic.memoryThreshold;\n\n            let {\n                rss,\n                heapTotal,\n                external,\n                arrayBuffers,\n            } = process.memoryUsage();\n\n            let totalSize = v8.getHeapStatistics().total_available_size;\n            let usedSize = rss + heapTotal + external + arrayBuffers;\n            let percentUsage = (usedSize / totalSize) * 100;\n\n            if (threshold < percentUsage) {\n                return this.serverErrorResponse(res, 'Low on memory here. Choose another server. :)');\n            }\n\n            this.sendJson(res, {\n                memory: {\n                    usedSize,\n                    totalSize,\n                    percentUsage,\n                },\n            });\n        });\n    }\n\n    healthCheck(res: HttpResponse) {\n        this.attachMiddleware(res, [\n            this.corkMiddleware,\n            this.corsMiddleware,\n        ]).then(res => {\n            this.send(res, 'OK');\n        });\n    }\n\n    usage(res: HttpResponse) {\n        this.attachMiddleware(res, [\n            this.corkMiddleware,\n            this.corsMiddleware,\n        ]).then(res => {\n            let {\n                rss,\n                heapTotal,\n                external,\n                arrayBuffers,\n            } = process.memoryUsage();\n\n            let totalSize = v8.getHeapStatistics().total_available_size;\n            let usedSize = rss + heapTotal + external + arrayBuffers;\n            let freeSize = totalSize - usedSize;\n            let percentUsage = (usedSize / totalSize) * 100;\n\n            return this.sendJson(res, {\n                memory: {\n                    free: freeSize,\n                    used: usedSize,\n                    total: totalSize,\n                    percent: percentUsage,\n                },\n            });\n        });\n    }\n\n    metrics(res: HttpResponse) {\n        this.attachMiddleware(res, [\n            this.corkMiddleware,\n            this.corsMiddleware,\n        ]).then(res => {\n            let handleError = err => {\n                this.serverErrorResponse(res, 'A server error has occurred.');\n            }\n\n            if (res.query.json) {\n                this.server.metricsManager\n                    .getMetricsAsJson()\n                    .then(metrics => {\n                        this.sendJson(res, metrics);\n                    })\n                    .catch(handleError);\n            } else {\n                this.server.metricsManager\n                    .getMetricsAsPlaintext()\n                    .then(metrics => {\n                        this.send(res, metrics);\n                    })\n                    .catch(handleError);\n            }\n        });\n    }\n\n    channels(res: HttpResponse) {\n        this.attachMiddleware(res, [\n            this.corkMiddleware,\n            this.corsMiddleware,\n            this.appMiddleware,\n            this.authMiddleware,\n            this.readRateLimitingMiddleware,\n        ]).then(res => {\n            this.server.adapter.getChannelsWithSocketsCount(res.params.appId).then(channels => {\n                let response: { [channel: string]: ChannelResponse } = [...channels].reduce((channels, [channel, connections]) => {\n                    if (connections === 0) {\n                        return channels;\n                    }\n\n                    // In case ?filter_by_prefix= is specified, the channel must start with that prefix.\n                    if (res.query.filter_by_prefix && !channel.startsWith(res.query.filter_by_prefix)) {\n                        return channels;\n                    }\n\n                    channels[channel] = {\n                        subscription_count: connections,\n                        occupied: true,\n                    };\n\n                    return channels;\n                }, {});\n\n                return response;\n            }).catch(err => {\n                Log.error(err);\n\n                return this.serverErrorResponse(res, 'A server error has occurred.');\n            }).then(channels => {\n                let broadcastMessage = { channels };\n\n                this.server.metricsManager.markApiMessage(res.params.appId, {}, broadcastMessage);\n\n                this.sendJson(res, broadcastMessage);\n            });\n        });\n    }\n\n    channel(res: HttpResponse) {\n        this.attachMiddleware(res, [\n            this.corkMiddleware,\n            this.corsMiddleware,\n            this.appMiddleware,\n            this.authMiddleware,\n            this.readRateLimitingMiddleware,\n        ]).then(res => {\n            let response: ChannelResponse;\n\n            this.server.adapter.getChannelSocketsCount(res.params.appId, res.params.channel).then(socketsCount => {\n                response = {\n                    subscription_count: socketsCount,\n                    occupied: socketsCount > 0,\n                };\n\n                // For presence channels, attach an user_count.\n                // Avoid extra call to get channel members if there are no sockets.\n                if (res.params.channel.startsWith('presence-')) {\n                    response.user_count = 0;\n\n                    if (response.subscription_count > 0) {\n                        this.server.adapter.getChannelMembersCount(res.params.appId, res.params.channel).then(membersCount => {\n                            let broadcastMessage = {\n                                ...response,\n                                ...{\n                                    user_count: membersCount,\n                                },\n                            };\n\n                            this.server.metricsManager.markApiMessage(res.params.appId, {}, broadcastMessage);\n\n                            this.sendJson(res, broadcastMessage);\n                        }).catch(err => {\n                            Log.error(err);\n\n                            return this.serverErrorResponse(res, 'A server error has occurred.');\n                        });\n\n                        return;\n                    }\n                }\n\n                this.server.metricsManager.markApiMessage(res.params.appId, {}, response);\n\n                return this.sendJson(res, response);\n            }).catch(err => {\n                Log.error(err);\n\n                return this.serverErrorResponse(res, 'A server error has occurred.');\n            });\n        });\n    }\n\n    channelUsers(res: HttpResponse) {\n        this.attachMiddleware(res, [\n            this.corkMiddleware,\n            this.corsMiddleware,\n            this.appMiddleware,\n            this.authMiddleware,\n            this.readRateLimitingMiddleware,\n        ]).then(res => {\n            if (!res.params.channel.startsWith('presence-')) {\n                return this.badResponse(res, 'The channel must be a presence channel.');\n            }\n\n            this.server.adapter.getChannelMembers(res.params.appId, res.params.channel).then(members => {\n                let broadcastMessage = {\n                    users: [...members].map(([user_id, user_info]) => {\n                        return res.query.with_user_info === '1'\n                            ? { id: user_id, user_info }\n                            : { id: user_id };\n                    }),\n                };\n\n                this.server.metricsManager.markApiMessage(res.params.appId, {}, broadcastMessage);\n\n                this.sendJson(res, broadcastMessage);\n            });\n        });\n    }\n\n    events(res: HttpResponse) {\n        this.attachMiddleware(res, [\n            this.corkMiddleware,\n            this.jsonBodyMiddleware,\n            this.corsMiddleware,\n            this.appMiddleware,\n            this.authMiddleware,\n            this.broadcastEventRateLimitingMiddleware,\n        ]).then(res => {\n            this.checkMessageToBroadcast(res.body as PusherApiMessage, res.app as App).then(message => {\n                this.broadcastMessage(message, res.app.id);\n                this.server.metricsManager.markApiMessage(res.app.id, res.body, { ok: true });\n                this.sendJson(res, { ok: true });\n            }).catch(error => {\n                if (error.code === 400) {\n                    this.badResponse(res, error.message);\n                } else if (error.code === 413) {\n                    this.entityTooLargeResponse(res, error.message);\n                }\n            });\n        });\n    }\n\n    batchEvents(res: HttpResponse) {\n        this.attachMiddleware(res, [\n            this.jsonBodyMiddleware,\n            this.corsMiddleware,\n            this.appMiddleware,\n            this.authMiddleware,\n            this.broadcastBatchEventsRateLimitingMiddleware,\n        ]).then(res => {\n            let batch = res.body.batch as PusherApiMessage[];\n\n            // Make sure the batch size is not too big.\n            if (batch.length > res.app.maxEventBatchSize) {\n                return this.badResponse(res, `Cannot batch-send more than ${res.app.maxEventBatchSize} messages at once`);\n            }\n\n            Promise.all(batch.map(message => this.checkMessageToBroadcast(message, res.app as App))).then(messages => {\n                messages.forEach(message => this.broadcastMessage(message, res.app.id));\n                this.server.metricsManager.markApiMessage(res.app.id, res.body, { ok: true });\n                this.sendJson(res, { ok: true });\n            }).catch((error: MessageCheckError) => {\n                if (error.code === 400) {\n                    this.badResponse(res, error.message);\n                } else if (error.code === 413) {\n                    this.entityTooLargeResponse(res, error.message);\n                }\n            });\n        });\n    }\n\n    terminateUserConnections(res: HttpResponse) {\n        this.attachMiddleware(res, [\n            this.jsonBodyMiddleware,\n            this.corsMiddleware,\n            this.appMiddleware,\n            this.authMiddleware,\n        ]).then(res => {\n            this.server.adapter.terminateUserConnections(res.app.id, res.params.userId);\n            this.sendJson(res, { ok: true });\n        });\n    }\n\n    protected checkMessageToBroadcast(message: PusherApiMessage, app: App): Promise<PusherApiMessage> {\n        return new Promise((resolve, reject) => {\n            if (\n                (!message.channels && !message.channel) ||\n                !message.name ||\n                !message.data\n            ) {\n                return reject({\n                    message: 'The received data is incorrect',\n                    code: 400,\n                });\n            }\n\n            let channels: string[] = message.channels || [message.channel];\n\n            message.channels = channels;\n\n            // Make sure the channels length is not too big.\n            if (channels.length > app.maxEventChannelsAtOnce) {\n                return reject({\n                    message: `Cannot broadcast to more than ${app.maxEventChannelsAtOnce} channels at once`,\n                    code: 400,\n                });\n            }\n\n            // Make sure the event name length is not too big.\n            if (message.name.length > app.maxEventNameLength) {\n                return reject({\n                    message: `Event name is too long. Maximum allowed size is ${app.maxEventNameLength}.`,\n                    code: 400,\n                });\n            }\n\n            let payloadSizeInKb = Utils.dataToKilobytes(message.data);\n\n            // Make sure the total payload of the message body is not too big.\n            if (payloadSizeInKb > parseFloat(app.maxEventPayloadInKb as string)) {\n                return reject({\n                    message: `The event data should be less than ${app.maxEventPayloadInKb} KB.`,\n                    code: 413,\n                });\n            }\n\n            resolve(message);\n        });\n    }\n\n    protected broadcastMessage(message: PusherApiMessage, appId: string): void {\n        message.channels.forEach(channel => {\n            let msg = {\n                event: message.name,\n                channel,\n                data: message.data,\n            };\n\n            this.server.adapter.send(appId, channel, JSON.stringify(msg), message.socket_id);\n\n            if (Utils.isCachingChannel(channel)) {\n                this.server.cacheManager.set(\n                    `app:${appId}:channel:${channel}:cache_miss`,\n                    JSON.stringify({ event: msg.event, data: msg.data }),\n                    this.server.options.channelLimits.cacheTtl,\n                );\n            }\n        });\n    }\n\n    notFound(res: HttpResponse) {\n        try {\n            res.writeStatus('404 Not Found');\n\n            this.attachMiddleware(res, [\n                this.corkMiddleware,\n                this.corsMiddleware,\n            ]).then(res => {\n                this.send(res, '', '404 Not Found');\n            });\n        } catch (e) {\n            Log.warningTitle('Response could not be sent');\n            Log.warning(e);\n        }\n    }\n\n    protected badResponse(res: HttpResponse, error: string) {\n        return this.sendJson(res, { error, code: 400 }, '400 Invalid Request');\n    }\n\n    protected notFoundResponse(res: HttpResponse, error: string) {\n        return this.sendJson(res, { error, code: 404 }, '404 Not Found');\n    }\n\n    protected unauthorizedResponse(res: HttpResponse, error: string) {\n        return this.sendJson(res, { error, code: 401 }, '401 Authorization Required');\n    }\n\n    protected entityTooLargeResponse(res: HttpResponse, error: string) {\n        return this.sendJson(res, { error, code: 413 }, '413 Payload Too Large');\n    }\n\n    protected tooManyRequestsResponse(res: HttpResponse) {\n        return this.sendJson(res, { error: 'Too many requests.', code: 429 }, '429 Too Many Requests');\n    }\n\n    protected serverErrorResponse(res: HttpResponse, error: string) {\n        return this.sendJson(res, { error, code: 500 }, '500 Internal Server Error');\n    }\n\n    protected jsonBodyMiddleware(res: HttpResponse, next: CallableFunction): any {\n        this.readJson(res, (body, rawBody) => {\n            res.body = body;\n            res.rawBody = rawBody;\n\n            let requestSizeInMb = Utils.dataToMegabytes(rawBody);\n\n            if (requestSizeInMb > this.server.options.httpApi.requestLimitInMb) {\n                return this.entityTooLargeResponse(res, 'The payload size is too big.');\n            }\n\n            next(null, res);\n        }, err => {\n            return this.badResponse(res, 'The received data is incorrect.');\n        });\n    }\n\n    protected corkMiddleware(res: HttpResponse, next: CallableFunction): any {\n        res.cork(() => next(null, res));\n    }\n\n    protected corsMiddleware(res: HttpResponse, next: CallableFunction): any {\n        res.writeHeader('Access-Control-Allow-Origin', this.server.options.cors.origin.join(', '));\n        res.writeHeader('Access-Control-Allow-Methods', this.server.options.cors.methods.join(', '));\n        res.writeHeader('Access-Control-Allow-Headers', this.server.options.cors.allowedHeaders.join(', '));\n\n        next(null, res);\n    }\n\n    protected appMiddleware(res: HttpResponse, next: CallableFunction): any {\n        return this.server.appManager.findById(res.params.appId).then(validApp => {\n            if (!validApp) {\n                return this.notFoundResponse(res, `The app ${res.params.appId} could not be found.`);\n            }\n\n            res.app = validApp;\n\n            next(null, res);\n        });\n    }\n\n    protected authMiddleware(res: HttpResponse, next: CallableFunction): any {\n        this.signatureIsValid(res).then(valid => {\n            if (valid) {\n                return next(null, res);\n            }\n\n            return this.unauthorizedResponse(res, 'The secret authentication failed');\n        });\n    }\n\n    protected readRateLimitingMiddleware(res: HttpResponse, next: CallableFunction): any {\n        this.server.rateLimiter.consumeReadRequestsPoints(1, res.app).then(response => {\n            if (response.canContinue) {\n                for (let header in response.headers) {\n                    res.writeHeader(header, '' + response.headers[header]);\n                }\n\n                return next(null, res);\n            }\n\n            this.tooManyRequestsResponse(res);\n        });\n    }\n\n    protected broadcastEventRateLimitingMiddleware(res: HttpResponse, next: CallableFunction): any {\n        let channels = res.body.channels || [res.body.channel];\n\n        this.server.rateLimiter.consumeBackendEventPoints(Math.max(channels.length, 1), res.app).then(response => {\n            if (response.canContinue) {\n                for (let header in response.headers) {\n                    res.writeHeader(header, '' + response.headers[header]);\n                }\n\n                return next(null, res);\n            }\n\n            this.tooManyRequestsResponse(res);\n        });\n    }\n\n    protected broadcastBatchEventsRateLimitingMiddleware(res: HttpResponse, next: CallableFunction): any {\n        let rateLimiterPoints = res.body.batch.reduce((rateLimiterPoints, event) => {\n            let channels: string[] = event.channels || [event.channel];\n\n            return rateLimiterPoints += channels.length;\n        }, 0);\n\n        this.server.rateLimiter.consumeBackendEventPoints(rateLimiterPoints, res.app).then(response => {\n            if (response.canContinue) {\n                for (let header in response.headers) {\n                    res.writeHeader(header, '' + response.headers[header]);\n                }\n\n                return next(null, res);\n            }\n\n            this.tooManyRequestsResponse(res);\n        });\n    }\n\n    protected attachMiddleware(res: HttpResponse, functions: any[]): Promise<HttpResponse> {\n        return new Promise((resolve, reject) => {\n            let waterfallInit = callback => callback(null, res);\n\n            let abortHandlerMiddleware = (res, callback) => {\n                res.onAborted(() => {\n                    Log.warning({ message: 'Aborted request.', res });\n                    // this.serverErrorResponse(res, 'Aborted request.');\n                });\n\n                callback(null, res);\n            };\n\n            async.waterfall([\n                waterfallInit.bind(this),\n                abortHandlerMiddleware.bind(this),\n                ...functions.map(fn => fn.bind(this)),\n            ], (err, res) => {\n                if (err) {\n                    this.serverErrorResponse(res, 'A server error has occurred.');\n                    Log.error(err);\n\n                    return reject({ res, err });\n                }\n\n                resolve(res);\n            });\n        });\n    }\n\n    /**\n     * Read the JSON content of a request.\n     */\n    protected readJson(res: HttpResponse, cb: CallableFunction, err: any) {\n        let buffer;\n\n        let loggingAction = (payload) => {\n            if (this.server.options.debug) {\n                Log.httpTitle('⚡ HTTP Payload received');\n                Log.http(payload);\n            }\n        };\n\n        res.onData((ab, isLast) => {\n            let chunk = Buffer.from(ab);\n\n            if (isLast) {\n                let json = {};\n                let raw = '{}';\n\n                if (buffer) {\n                    try {\n                        // @ts-ignore\n                        json = JSON.parse(Buffer.concat([buffer, chunk]));\n                    } catch (e) {\n                        //\n                    }\n\n                    try {\n                        raw = Buffer.concat([buffer, chunk]).toString();\n                    } catch (e) {\n                        //\n                    }\n\n                    cb(json, raw);\n                    loggingAction(json);\n                } else {\n                    try {\n                        // @ts-ignore\n                        json = JSON.parse(chunk);\n                        raw = chunk.toString();\n                    } catch (e) {\n                        //\n                    }\n\n                    cb(json, raw);\n                    loggingAction(json);\n                }\n            } else {\n                if (buffer) {\n                    buffer = Buffer.concat([buffer, chunk]);\n                } else {\n                    buffer = Buffer.concat([chunk]);\n                }\n            }\n        });\n\n        res.onAborted(err);\n    }\n\n    /**\n     * Check is an incoming request can access the api.\n     */\n    protected signatureIsValid(res: HttpResponse): Promise<boolean> {\n        return this.getSignedToken(res).then(token => {\n            return token === res.query.auth_signature;\n        });\n    }\n\n    protected sendJson(res: HttpResponse, data: any, status: RecognizedString = '200 OK') {\n        try {\n            return res.writeStatus(status)\n                .writeHeader('Content-Type', 'application/json')\n                .end(JSON.stringify(data), true);\n        } catch (e) {\n            Log.warningTitle('Response could not be sent');\n            Log.warning(e);\n        }\n    }\n\n    protected send(res: HttpResponse, data: RecognizedString, status: RecognizedString = '200 OK') {\n        try {\n            return res.writeStatus(status).end(data, true);\n        } catch (e) {\n            Log.warningTitle('Response could not be sent');\n            Log.warning(e);\n        }\n    }\n\n    /**\n     * Get the signed token from the given request.\n     */\n    protected getSignedToken(res: HttpResponse): Promise<string> {\n        return Promise.resolve(res.app.signingTokenFromRequest(res));\n    }\n}\n"
  },
  {
    "path": "src/index.ts",
    "content": "export * from './app';\nexport * from './http-handler';\nexport * from './job';\nexport * from './log';\nexport * from './namespace';\nexport * from './options';\nexport * from './server';\nexport * from './utils';\nexport * from './webhook-sender';\nexport * from './ws-handler';\n"
  },
  {
    "path": "src/job.ts",
    "content": "import { v4 as uuidv4 } from 'uuid';\n\nexport class Job {\n    /**\n     * Create a new job instance.\n     */\n    constructor(public id: string = uuidv4(), public data: { [key: string]: any; } = {}) {\n        //\n    }\n}\n"
  },
  {
    "path": "src/log.ts",
    "content": "const colors = require('colors');\n\nexport class Log {\n    static infoTitle(message: any): void {\n        this.log(message, 'bold', 'black', 'bgCyan', 'mx-2', 'px-1');\n    }\n\n    static successTitle(message: any): void {\n        this.log(message, 'bold', 'black', 'bgGreen', 'mx-2', 'px-1');\n    }\n\n    static errorTitle(message: any): void {\n        this.log(this.prefixWithTime(message), 'bold', 'black', 'bgRed', 'mx-2', 'px-1');\n    }\n\n    static warningTitle(message: any): void {\n        this.log(this.prefixWithTime(message), 'bold', 'black', 'bgYellow', 'mx-2', 'px-1');\n    }\n\n    static clusterTitle(message: any): void {\n        this.log(this.prefixWithTime(message), 'bold', 'yellow', 'bgMagenta', 'mx-2', 'px-1');\n    }\n\n    static httpTitle(message: any): void {\n        this.infoTitle(this.prefixWithTime(message));\n    }\n\n    static discoverTitle(message: any): void {\n        this.log(this.prefixWithTime(message), 'bold', 'gray', 'bgBrightCyan', 'mx-2', 'px-1');\n    }\n\n    static websocketTitle(message: any): void {\n        this.successTitle(this.prefixWithTime(message));\n    }\n\n    static webhookSenderTitle(message: any): void {\n        this.log(this.prefixWithTime(message), 'bold', 'blue', 'bgWhite', 'mx-2', 'px-1');\n    }\n\n    static info(message: any): void {\n        this.log(message, 'cyan', 'mx-2');\n    }\n\n    static success(message: any): void {\n        this.log(message, 'green', 'mx-2');\n    }\n\n    static error(message: any): void {\n        this.log(message, 'red', 'mx-2');\n    }\n\n    static warning(message: any): void {\n        this.log(message, 'yellow', 'mx-2');\n    }\n\n    static cluster(message: any): void {\n        this.log(message, 'bold', 'magenta', 'mx-2');\n    }\n\n    static http(message: any): void {\n        this.info(message);\n    }\n\n    static discover(message: any): void {\n        this.log(message, 'bold', 'brightCyan', 'mx-2');\n    }\n\n    static websocket(message: any): void {\n        this.success(message);\n    }\n\n    static webhookSender(message: any): void {\n        this.log(message, 'bold', 'white', 'mx-2');\n    }\n\n    static br(): void {\n        console.log('');\n    }\n\n    protected static prefixWithTime(message: any): any {\n        if (typeof message === 'string') {\n            return '[' + (new Date).toString() + '] ' + message;\n        }\n\n        return message;\n    }\n\n    protected static log(message: any, ...styles: string[]): void {\n        let withColor = colors;\n\n        if (typeof message !== 'string') {\n            return console.log(message);\n        }\n\n        styles\n            .filter(style => ! /^[m|p]x-/.test(style))\n            .forEach((style) => withColor = withColor[style]);\n\n        const applyMargins = (message: string): string => {\n            const spaces = styles\n                .filter(style => /^mx-/.test(style))\n                .map(style => ' '.repeat(parseInt(style.substr(3))))\n                .join('');\n\n            return spaces + message + spaces;\n        }\n\n        const applyPadding = (message: string): string => {\n            const spaces = styles\n                .filter(style => /^px-/.test(style))\n                .map(style => ' '.repeat(parseInt(style.substr(3))))\n                .join('');\n\n            return spaces + message + spaces;\n        }\n\n        console.log(applyMargins(withColor(applyPadding(message))));\n    }\n}\n"
  },
  {
    "path": "src/message.ts",
    "content": "export interface MessageData {\n    channel_data?: string;\n    channel?: string;\n    user_data?: string;\n    [key: string]: any;\n}\n\nexport interface PusherMessage {\n    channel?: string;\n    name?: string;\n    event?: string;\n    data?: MessageData;\n}\n\nexport interface PusherApiMessage {\n    name?: string;\n    data?: string|{ [key: string]: any };\n    channel?: string;\n    channels?: string[];\n    socket_id?: string;\n}\n\nexport interface SentPusherMessage {\n    channel?: string;\n    event?: string;\n    data?: MessageData|string;\n}\n\nexport type uWebSocketMessage = ArrayBuffer|PusherMessage;\n"
  },
  {
    "path": "src/metrics/index.ts",
    "content": "export * from './metrics';\nexport * from './metrics-interface';\nexport * from './prometheus-metrics-driver';\n"
  },
  {
    "path": "src/metrics/metrics-interface.ts",
    "content": "import * as prom from 'prom-client';\nimport { WebSocket } from 'uWebSockets.js';\n\nexport interface MetricsInterface {\n    /**\n     * The Metrics driver.\n     */\n    driver?: MetricsInterface;\n\n    /**\n     * Handle a new connection.\n     */\n    markNewConnection(ws: WebSocket): void;\n\n    /**\n     * Handle a disconnection.\n     */\n    markDisconnection(ws: WebSocket): void;\n\n    /**\n     * Handle a new API message event being received and sent out.\n     */\n    markApiMessage(appId: string, incomingMessage: any, sentMessage: any): void;\n\n    /**\n     * Handle a new WS client message event being sent.\n     */\n    markWsMessageSent(appId: string, sentMessage: any): void;\n\n    /**\n     * Handle a new WS client message being received.\n     */\n    markWsMessageReceived(appId: string, message: any): void;\n\n    /**\n     * Track the time in which horizontal adapter resolves requests from other nodes.\n     */\n    trackHorizontalAdapterResolveTime(appId: string, time: number): void;\n\n    /**\n     * Track the fulfillings in which horizontal adapter resolves requests from other nodes.\n     */\n    trackHorizontalAdapterResolvedPromises(appId: string, resolved?: boolean): void;\n\n    /**\n     * Handle a new horizontal adapter request sent.\n     */\n    markHorizontalAdapterRequestSent(appId: string): void;\n\n    /**\n     * Handle a new horizontal adapter request that was marked as received.\n     */\n    markHorizontalAdapterRequestReceived(appId: string): void;\n\n    /**\n     * Handle a new horizontal adapter response from other node.\n     */\n    markHorizontalAdapterResponseReceived(appId: string): void;\n\n    /**\n     * Get the stored metrics as plain text, if possible.\n     */\n    getMetricsAsPlaintext(): Promise<string>;\n\n    /**\n     * Get the stored metrics as JSON.\n     */\n    getMetricsAsJson(): Promise<prom.metric[]|void>;\n\n    /**\n     * Reset the metrics at the server level.\n     */\n    clear(): Promise<void>;\n}\n"
  },
  {
    "path": "src/metrics/metrics.ts",
    "content": "import * as prom from 'prom-client';\nimport { WebSocket } from 'uWebSockets.js';\nimport { Log } from './../log';\nimport { MetricsInterface } from './metrics-interface';\nimport { PrometheusMetricsDriver } from './prometheus-metrics-driver';\nimport { Server } from '../server';\n\nexport class Metrics implements MetricsInterface {\n    /**\n     * The Metrics driver.\n     */\n    public driver: MetricsInterface;\n\n    /**\n     * Initialize the Prometheus exporter.\n     */\n    constructor(protected server: Server) {\n        if (server.options.metrics.driver === 'prometheus') {\n            this.driver = new PrometheusMetricsDriver(server);\n        } else {\n            Log.error('No metrics driver specified.');\n        }\n    }\n\n    /**\n     * Handle a new connection.\n     */\n    markNewConnection(ws: WebSocket): void {\n        if (this.server.options.metrics.enabled) {\n            this.driver.markNewConnection(ws);\n        }\n    }\n\n    /**\n     * Handle a disconnection.\n     */\n    markDisconnection(ws: WebSocket): void {\n        if (this.server.options.metrics.enabled) {\n            this.driver.markDisconnection(ws);\n        }\n    }\n\n    /**\n     * Handle a new API message event being received and sent out.\n     */\n    markApiMessage(appId: string, incomingMessage: any, sentMessage: any): void {\n        if (this.server.options.metrics.enabled) {\n            this.driver.markApiMessage(appId, incomingMessage, sentMessage);\n        }\n    }\n\n    /**\n     * Handle a new WS client message event being sent.\n     */\n    markWsMessageSent(appId: string, sentMessage: any): void {\n        if (this.server.options.metrics.enabled) {\n            this.driver.markWsMessageSent(appId, sentMessage);\n        }\n    }\n\n    /**\n     * Handle a new WS client message being received.\n     */\n    markWsMessageReceived(appId: string, message: any): void {\n        if (this.server.options.metrics.enabled) {\n            this.driver.markWsMessageReceived(appId, message);\n        }\n    }\n\n    /**\n     * Track the time in which horizontal adapter resolves requests from other nodes.\n     */\n    trackHorizontalAdapterResolveTime(appId: string, time: number): void {\n        this.driver.trackHorizontalAdapterResolveTime(appId, time);\n    }\n\n    /**\n     * Track the fulfillings in which horizontal adapter resolves requests from other nodes.\n     */\n    trackHorizontalAdapterResolvedPromises(appId: string, resolved = true): void {\n        this.driver.trackHorizontalAdapterResolvedPromises(appId, resolved);\n    }\n\n    /**\n     * Handle a new horizontal adapter request sent.\n     */\n    markHorizontalAdapterRequestSent(appId: string): void {\n        this.driver.markHorizontalAdapterRequestSent(appId);\n    }\n\n     /**\n      * Handle a new horizontal adapter request that was marked as received.\n      */\n    markHorizontalAdapterRequestReceived(appId: string): void {\n        this.driver.markHorizontalAdapterRequestReceived(appId);\n    }\n\n     /**\n      * Handle a new horizontal adapter response from other node.\n      */\n    markHorizontalAdapterResponseReceived(appId: string): void {\n        this.driver.markHorizontalAdapterResponseReceived(appId);\n    }\n\n    /**\n     * Get the stored metrics as plain text, if possible.\n     */\n    getMetricsAsPlaintext(): Promise<string> {\n        if (!this.server.options.metrics.enabled) {\n            return Promise.resolve('');\n        }\n\n        return this.driver.getMetricsAsPlaintext();\n    }\n\n    /**\n     * Get the stored metrics as JSON.\n     */\n    getMetricsAsJson(): Promise<prom.metric[]|void> {\n        if (!this.server.options.metrics.enabled) {\n            return Promise.resolve();\n        }\n\n        return this.driver.getMetricsAsJson();\n    }\n\n    /**\n     * Reset the metrics at the server level.\n     */\n    clear(): Promise<void> {\n        return this.driver.clear();\n    }\n}\n"
  },
  {
    "path": "src/metrics/prometheus-metrics-driver.ts",
    "content": "import * as prom from 'prom-client';\nimport { WebSocket } from 'uWebSockets.js';\nimport { MetricsInterface } from './metrics-interface';\nimport { Server } from '../server';\nimport { Utils } from '../utils';\n\ninterface PrometheusMetrics {\n    connectedSockets?: prom.Gauge<'app_id'|'port'>;\n    newConnectionsTotal?: prom.Counter<'app_id'|'port'>;\n    newDisconnectionsTotal?: prom.Counter<'app_id'|'port'>;\n    socketBytesReceived?: prom.Counter<'app_id'|'port'>;\n    socketBytesTransmitted?: prom.Counter<'app_id'|'port'>;\n    wsMessagesReceived?: prom.Counter<'app_id'|'port'>;\n    wsMessagesSent?: prom.Counter<'app_id'|'port'>;\n    httpBytesReceived?: prom.Counter<'app_id'|'port'>;\n    httpBytesTransmitted?: prom.Counter<'app_id'|'port'>;\n    httpCallsReceived?: prom.Counter<'app_id'|'port'>;\n    horizontalAdapterResolveTime?: prom.Histogram<'app_id'|'port'>;\n    horizontalAdapterResolvedPromises?: prom.Counter<'app_id'|'port'>;\n    horizontalAdapterUncompletePromises?: prom.Counter<'app_id'|'port'>;\n    horizontalAdapterSentRequests?: prom.Counter<'app_id'|'port'>;\n    horizontalAdapterReceivedRequests?: prom.Counter<'app_id'|'port'>;\n    horizontalAdapterReceivedResponses?: prom.Counter<'app_id'|'port'>;\n}\n\ninterface InfraMetadata {\n    [key: string]: any;\n}\n\ninterface NamespaceTags {\n    app_id: string;\n    [key: string]: any;\n}\n\nexport class PrometheusMetricsDriver implements MetricsInterface {\n    /**\n     * The list of metrics that will register.\n     *\n     * @type {PrometheusMetrics}\n     */\n    protected metrics: PrometheusMetrics = {\n        // TODO: Metrics for subscribes/unsubscribes/client events?\n    };\n\n    /**\n     * Prometheus register repo.\n     *\n     * @type {prom.Registry}\n     */\n    register: prom.Registry;\n\n    /**\n     * The infra-related metadata.\n     *\n     * @type {InfraMetadata}\n     */\n    protected infraMetadata: InfraMetadata = {\n        //\n    };\n\n    /**\n     * Initialize the Prometheus exporter.\n     */\n    constructor(protected server: Server) {\n        this.register = new prom.Registry();\n\n        this.registerMetrics();\n\n        this.infraMetadata = {\n            port: server.options.port\n        };\n\n        prom.collectDefaultMetrics({\n            prefix: server.options.metrics.prometheus.prefix,\n            register: this.register,\n            labels: this.infraMetadata,\n        });\n    }\n\n    /**\n     * Handle a new connection.\n     */\n    markNewConnection(ws: WebSocket): void {\n        this.metrics.connectedSockets.inc(this.getTags(ws.app.id));\n        this.metrics.newConnectionsTotal.inc(this.getTags(ws.app.id));\n    }\n\n    /**\n     * Handle a disconnection.\n     */\n    markDisconnection(ws: WebSocket): void {\n        this.metrics.connectedSockets.dec(this.getTags(ws.app.id));\n        this.metrics.newDisconnectionsTotal.inc(this.getTags(ws.app.id));\n    }\n\n    /**\n     * Handle a new API message event being received and sent out.\n     */\n    markApiMessage(appId: string, incomingMessage: any, sentMessage: any): void {\n        this.metrics.httpBytesReceived.inc(this.getTags(appId), Utils.dataToBytes(incomingMessage));\n        this.metrics.httpBytesTransmitted.inc(this.getTags(appId), Utils.dataToBytes(sentMessage));\n        this.metrics.httpCallsReceived.inc(this.getTags(appId));\n    }\n\n    /**\n     * Handle a new WS client message event being sent.\n     */\n    markWsMessageSent(appId: string, sentMessage: any): void {\n        this.metrics.socketBytesTransmitted.inc(this.getTags(appId), Utils.dataToBytes(sentMessage));\n        this.metrics.wsMessagesSent.inc(this.getTags(appId), 1);\n    }\n\n    /**\n     * Handle a new WS client message being received.\n     */\n    markWsMessageReceived(appId: string, message: any): void {\n        this.metrics.socketBytesReceived.inc(this.getTags(appId), Utils.dataToBytes(message));\n        this.metrics.wsMessagesReceived.inc(this.getTags(appId), 1);\n    }\n\n    /**\n     * Track the time in which horizontal adapter resolves requests from other nodes.\n     */\n    trackHorizontalAdapterResolveTime(appId: string, time: number): void {\n        this.metrics.horizontalAdapterResolveTime.observe(this.getTags(appId), time);\n    }\n\n    /**\n     * Track the fulfillings in which horizontal adapter resolves requests from other nodes.\n     */\n    trackHorizontalAdapterResolvedPromises(appId: string, resolved = true): void {\n        if (resolved) {\n            this.metrics.horizontalAdapterResolvedPromises.inc(this.getTags(appId));\n        } else {\n            this.metrics.horizontalAdapterUncompletePromises.inc(this.getTags(appId));\n        }\n    }\n\n    /**\n     * Handle a new horizontal adapter request sent.\n     */\n    markHorizontalAdapterRequestSent(appId: string): void {\n        this.metrics.horizontalAdapterSentRequests.inc(this.getTags(appId));\n    }\n\n     /**\n      * Handle a new horizontal adapter request that was marked as received.\n      */\n    markHorizontalAdapterRequestReceived(appId: string): void {\n        this.metrics.horizontalAdapterReceivedRequests.inc(this.getTags(appId));\n    }\n\n     /**\n      * Handle a new horizontal adapter response from other node.\n      */\n    markHorizontalAdapterResponseReceived(appId: string): void {\n        this.metrics.horizontalAdapterReceivedResponses.inc(this.getTags(appId));\n    }\n\n    /**\n     * Get the stored metrics as plain text, if possible.\n     */\n    getMetricsAsPlaintext(): Promise<string> {\n        return this.register.metrics();\n    }\n\n    /**\n     * Get the stored metrics as JSON.\n     */\n    getMetricsAsJson(): Promise<prom.metric[]|void> {\n        return this.register.getMetricsAsJSON();\n    }\n\n    /**\n     * Reset the metrics at the server level.\n     */\n    clear(): Promise<void> {\n        return Promise.resolve(this.register.clear());\n    }\n\n    /**\n     * Get the tags for Prometheus.\n     */\n    protected getTags(appId: string): NamespaceTags {\n        return {\n            app_id: appId,\n            ...this.infraMetadata,\n        };\n    }\n\n    protected registerMetrics(): void {\n        let prefix = this.server.options.metrics.prometheus.prefix;\n\n        this.metrics = {\n            connectedSockets: new prom.Gauge({\n                name: `${prefix}connected`,\n                help: 'The number of currently connected sockets.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            newConnectionsTotal: new prom.Counter({\n                name: `${prefix}new_connections_total`,\n                help: 'Total amount of soketi connection requests.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            newDisconnectionsTotal: new prom.Counter({\n                name: `${prefix}new_disconnections_total`,\n                help: 'Total amount of soketi disconnections.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            socketBytesReceived: new prom.Counter({\n                name: `${prefix}socket_received_bytes`,\n                help: 'Total amount of bytes that soketi received.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            socketBytesTransmitted: new prom.Counter({\n                name: `${prefix}socket_transmitted_bytes`,\n                help: 'Total amount of bytes that soketi transmitted.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            wsMessagesReceived: new prom.Counter({\n                name: `${prefix}ws_messages_received_total`,\n                help: 'The total amount of WS messages received from connections by the server.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            wsMessagesSent: new prom.Counter({\n                name: `${prefix}ws_messages_sent_total`,\n                help: 'The total amount of WS messages sent to the connections from the server.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            httpBytesReceived: new prom.Counter({\n                name: `${prefix}http_received_bytes`,\n                help: 'Total amount of bytes that soketi\\'s REST API received.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            httpBytesTransmitted: new prom.Counter({\n                name: `${prefix}http_transmitted_bytes`,\n                help: 'Total amount of bytes that soketi\\'s REST API sent back.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            httpCallsReceived: new prom.Counter({\n                name: `${prefix}http_calls_received_total`,\n                help: 'Total amount of received REST API calls.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            horizontalAdapterResolveTime: new prom.Histogram({\n                name: `${prefix}horizontal_adapter_resolve_time`,\n                help: 'The average resolve time for requests to other nodes.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            horizontalAdapterResolvedPromises: new prom.Counter({\n                name: `${prefix}horizontal_adapter_resolved_promises`,\n                help: 'The total amount of promises that were fulfilled by other nodes.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            horizontalAdapterUncompletePromises: new prom.Counter({\n                name: `${prefix}horizontal_adapter_uncomplete_promises`,\n                help: 'The total amount of promises that were not fulfilled entirely by other nodes.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            horizontalAdapterSentRequests: new prom.Counter({\n                name: `${prefix}horizontal_adapter_sent_requests`,\n                help: 'The total amount of sent requests to other nodes.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            horizontalAdapterReceivedRequests: new prom.Counter({\n                name: `${prefix}horizontal_adapter_received_requests`,\n                help: 'The total amount of received requests from other nodes.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n            horizontalAdapterReceivedResponses: new prom.Counter({\n                name: `${prefix}horizontal_adapter_received_responses`,\n                help: 'The total amount of received responses from other nodes.',\n                labelNames: ['app_id', 'port'],\n                registers: [this.register],\n            }),\n        };\n    }\n}\n"
  },
  {
    "path": "src/namespace.ts",
    "content": "import { PresenceMember, PresenceMemberInfo } from './channels/presence-channel-manager';\nimport { WebSocket } from 'uWebSockets.js';\n\nexport class Namespace {\n    /**\n     * The list of channel connections for the current app.\n     */\n    public channels: Map<string, Set<string>> = new Map();\n\n    /**\n     * The list of sockets connected to the namespace.\n     */\n    public sockets: Map<string, WebSocket> = new Map();\n\n    /**\n     * The list of user IDs and their associated socket ids.\n     */\n    public users: Map<number|string, Set<string>> = new Map();\n\n    /**\n     * Initialize the namespace for an app.\n     */\n    constructor(protected appId: string) {\n        //\n    }\n\n    /**\n     * Get all sockets from this namespace.\n     */\n    getSockets(): Promise<Map<string, WebSocket>> {\n        return Promise.resolve(this.sockets);\n    }\n\n    /**\n     * Add a new socket to the namespace.\n     */\n    addSocket(ws: WebSocket): Promise<boolean> {\n        return new Promise(resolve => {\n            this.sockets.set(ws.id, ws);\n            resolve(true);\n        });\n    }\n\n    /**\n     * Remove a socket from the namespace.\n     */\n    async removeSocket(wsId: string): Promise<boolean> {\n        this.removeFromChannel(wsId, [...this.channels.keys()]);\n\n        return this.sockets.delete(wsId);\n    }\n\n    /**\n     * Add a socket ID to the channel identifier.\n     * Return the total number of connections after the connection.\n     */\n    addToChannel(ws: WebSocket, channel: string): Promise<number> {\n        return new Promise(resolve => {\n            if (!this.channels.has(channel)) {\n                this.channels.set(channel, new Set);\n            }\n\n            this.channels.get(channel).add(ws.id);\n\n            resolve(this.channels.get(channel).size);\n        });\n    }\n\n    /**\n     * Remove a socket ID from the channel identifier.\n     * Return the total number of connections remaining to the channel.\n     */\n    async removeFromChannel(wsId: string, channel: string|string[]): Promise<number|void> {\n        let remove = (channel) => {\n            if (this.channels.has(channel)) {\n                this.channels.get(channel).delete(wsId);\n\n                if (this.channels.get(channel).size === 0) {\n                    this.channels.delete(channel);\n                }\n            }\n        };\n\n        return new Promise(resolve => {\n            if (Array.isArray(channel)) {\n                channel.forEach(ch => remove(ch));\n\n                return resolve();\n            }\n\n            remove(channel);\n\n            resolve(this.channels.has(channel) ? this.channels.get(channel).size : 0);\n        });\n    }\n\n    /**\n     * Check if a socket ID is joined to the channel.\n     */\n    isInChannel(wsId: string, channel: string): Promise<boolean> {\n        return new Promise(resolve => {\n            if (!this.channels.has(channel)) {\n                return resolve(false);\n            }\n\n            resolve(this.channels.get(channel).has(wsId));\n        });\n    }\n\n    /**\n     * Get the list of channels with the websocket IDs.\n     */\n    getChannels(): Promise<Map<string, Set<string>>> {\n        return Promise.resolve(this.channels);\n    }\n\n    /**\n     * Get the list of channels with the websocket IDs.\n     */\n    getChannelsWithSocketsCount(): Promise<Map<string, number>> {\n        return this.getChannels().then((channels) => {\n            let list = new Map<string, number>();\n\n            for (let [channel, connections] of [...channels]) {\n                list.set(channel, connections.size);\n            }\n\n            return list;\n        });\n    }\n\n    /**\n     * Get all the channel sockets associated with this namespace.\n     */\n    getChannelSockets(channel: string): Promise<Map<string, WebSocket>> {\n        return new Promise(resolve => {\n            if (!this.channels.has(channel)) {\n                return resolve(new Map<string, WebSocket>());\n            }\n\n            let wsIds = this.channels.get(channel);\n\n            resolve(\n                Array.from(wsIds).reduce((sockets, wsId) => {\n                    if (!this.sockets.has(wsId)) {\n                        return sockets;\n                    }\n\n                    return sockets.set(wsId, this.sockets.get(wsId));\n                }, new Map<string, WebSocket>())\n            );\n        });\n    }\n\n    /**\n     * Get a given presence channel's members.\n     */\n    getChannelMembers(channel: string): Promise<Map<string, PresenceMemberInfo>> {\n        return this.getChannelSockets(channel).then(sockets => {\n            return Array.from(sockets).reduce((members, [wsId, ws]) => {\n                let member: PresenceMember = ws.presence ? ws.presence.get(channel) : null;\n\n                if (member) {\n                    members.set(member.user_id as string, member.user_info);\n                }\n\n                return members;\n            }, new Map<string, PresenceMemberInfo>());\n        });\n    }\n\n    /**\n     * Terminate the user's connections.\n     */\n    terminateUserConnections(userId: number|string): void {\n        this.getSockets().then(sockets => {\n            [...sockets].forEach(([wsId, ws]) => {\n                if (ws.user && ws.user.id == userId) {\n                    ws.sendJson({\n                        event: 'pusher:error',\n                        data: {\n                            code: 4009,\n                            message: 'You got disconnected by the app.',\n                        },\n                    });\n\n                    try {\n                        ws.end(4009);\n                    } catch (e) {\n                        //\n                    }\n                }\n            });\n        });\n    }\n\n    /**\n     * Add to the users list the associated socket connection ID.\n     */\n    addUser(ws: WebSocket): Promise<void> {\n        if (!ws.user) {\n            return Promise.resolve();\n        }\n\n        if (!this.users.has(ws.user.id)) {\n            this.users.set(ws.user.id, new Set());\n        }\n\n        if (!this.users.get(ws.user.id).has(ws.id)) {\n            this.users.get(ws.user.id).add(ws.id);\n        }\n\n        return Promise.resolve();\n    }\n\n    /**\n     * Remove the user associated with the connection ID.\n     */\n    removeUser(ws: WebSocket): Promise<void> {\n        if (!ws.user) {\n            return Promise.resolve();\n        }\n\n        if (this.users.has(ws.user.id)) {\n            this.users.get(ws.user.id).delete(ws.id);\n        }\n\n        if (this.users.get(ws.user.id) && this.users.get(ws.user.id).size === 0) {\n            this.users.delete(ws.user.id);\n        }\n\n        return Promise.resolve();\n    }\n\n    /**\n     * Get the sockets associated with an user.\n     */\n    getUserSockets(userId: string|number): Promise<Set<WebSocket>> {\n        let wsIds = this.users.get(userId);\n\n        if (!wsIds || wsIds.size === 0) {\n            return Promise.resolve(new Set());\n        }\n\n        return Promise.resolve(\n            [...wsIds].reduce((sockets, wsId) => {\n                sockets.add(this.sockets.get(wsId));\n\n                return sockets;\n            }, new Set<WebSocket>())\n        );\n    }\n}\n"
  },
  {
    "path": "src/node.ts",
    "content": "export interface Node {\n    isMaster: boolean;\n    address: string;\n    port: number;\n    lastSeen: number;\n    id: string;\n}\n"
  },
  {
    "path": "src/options.ts",
    "content": "import { AppInterface } from './app';\nimport { ClusterOptions, RedisOptions } from 'ioredis';\nimport { ConsumerOptions } from 'sqs-consumer';\nimport { SQS } from 'aws-sdk';\n\ninterface Redis {\n    host: string;\n    port: number;\n    db: number;\n    username: string|null;\n    password: string|null;\n    keyPrefix: string;\n    sentinels: RedisSentinel[];\n    sentinelPassword: string|null;\n    name: string;\n    clusterNodes: ClusterNode[];\n}\n\ninterface RedisSentinel {\n    host: string;\n    port: number;\n}\n\ninterface ClusterNode {\n    host: string;\n    port: number;\n}\n\ninterface KnexConnection {\n    host: string;\n    port: number;\n    user: string;\n    password: string;\n    database: string;\n}\n\nexport interface Options {\n    adapter: {\n        driver: string;\n        redis: {\n            requestsTimeout: number;\n            prefix: string;\n            redisPubOptions: any;\n            redisSubOptions: any;\n            clusterMode: boolean;\n        };\n        cluster: {\n            requestsTimeout: 5_000,\n        },\n        nats: {\n            requestsTimeout: number;\n            prefix: string;\n            servers: string[];\n            user?: string;\n            pass?: string|null;\n            token: string|null;\n            timeout: number;\n            nodesNumber: number|null;\n        };\n    };\n    appManager: {\n        driver: string;\n        array: {\n            apps: AppInterface[];\n        };\n        cache: {\n            enabled: boolean;\n            ttl: number;\n        };\n        dynamodb: {\n            table: string;\n            region: string;\n            endpoint?: string;\n        };\n        mysql: {\n            table: string;\n            version: string|number;\n            useMysql2: boolean;\n        };\n        postgres: {\n            table: string;\n            version: string|number;\n        };\n    };\n    cache: {\n        driver: string;\n        redis: {\n            redisOptions: RedisOptions|ClusterOptions;\n            clusterMode: boolean;\n        };\n    };\n    channelLimits: {\n        maxNameLength: number;\n        cacheTtl: number;\n    };\n    cluster: {\n        hostname: string;\n        helloInterval: number;\n        checkInterval: number;\n        nodeTimeout: number,\n        masterTimeout: number;\n        port: number;\n        prefix: string;\n        ignoreProcess: boolean;\n        broadcast: string;\n        unicast: string|null;\n        multicast: string|null;\n    };\n    cors: {\n        credentials: boolean;\n        origin: string[];\n        methods: string[];\n        allowedHeaders: string[];\n    };\n    database: {\n        mysql: KnexConnection;\n        postgres: KnexConnection;\n        redis: Redis;\n    };\n    databasePooling: {\n        enabled: boolean;\n        min: number;\n        max: number;\n    };\n    debug: boolean;\n    eventLimits: {\n        maxChannelsAtOnce: string|number;\n        maxNameLength: string|number;\n        maxPayloadInKb: string|number;\n        maxBatchSize: string|number;\n    };\n    host: string;\n    httpApi: {\n        requestLimitInMb: string|number;\n        acceptTraffic: {\n            memoryThreshold: number;\n        };\n    };\n    instance: {\n        process_id: string|number;\n    };\n    metrics: {\n        enabled: boolean;\n        driver: string;\n        host: string;\n        prometheus: {\n            prefix: string;\n        };\n        port: number;\n    };\n    mode: string;\n    port: number;\n    pathPrefix: string;\n    presence: {\n        maxMembersPerChannel: string|number;\n        maxMemberSizeInKb: string|number;\n    };\n    queue: {\n        driver: string;\n        redis: {\n            concurrency: number;\n            redisOptions: RedisOptions|ClusterOptions;\n            clusterMode: boolean;\n        };\n        sqs: {\n            region?: string;\n            endpoint?: string;\n            clientOptions?: SQS.Types.ClientConfiguration;\n            consumerOptions?: ConsumerOptions;\n            queueUrl: string;\n            processBatch: boolean;\n            batchSize: number;\n            pollingWaitTimeMs: number;\n        };\n    };\n    rateLimiter: {\n        driver: string;\n        redis: {\n            redisOptions: RedisOptions|ClusterOptions;\n            clusterMode: boolean;\n        };\n    };\n    shutdownGracePeriod: number;\n    ssl: {\n        certPath: string;\n        keyPath: string;\n        passphrase: string;\n        caPath: string;\n    };\n    userAuthenticationTimeout: number;\n    webhooks: {\n        batching: {\n            enabled: boolean;\n            duration: number;\n        };\n    };\n}\n"
  },
  {
    "path": "src/queues/index.ts",
    "content": "export * from './queue-interface';\nexport * from './queue';\nexport * from './redis-queue-driver';\nexport * from './sqs-queue-driver';\nexport * from './sync-queue-driver';\n"
  },
  {
    "path": "src/queues/queue-interface.ts",
    "content": "import { JobData } from '../webhook-sender';\n\nexport interface QueueInterface {\n    /**\n     * The Queue driver.\n     */\n    driver?: QueueInterface;\n\n    /**\n     * Add a new event with data to queue.\n     */\n    addToQueue(queueName: string, data?: JobData): Promise<void>;\n\n    /**\n     * Register the code to run when handing the queue.\n     */\n    processQueue(queueName: string, callback: CallableFunction): Promise<void>;\n\n    /**\n     * Clear the queues for a graceful shutdown.\n     */\n    disconnect(): Promise<void>;\n}\n"
  },
  {
    "path": "src/queues/queue.ts",
    "content": "import { JobData } from '../webhook-sender';\nimport { Log } from '../log';\nimport { QueueInterface } from './queue-interface';\nimport { RedisQueueDriver } from './redis-queue-driver';\nimport { SqsQueueDriver } from './sqs-queue-driver';\nimport { SyncQueueDriver } from './sync-queue-driver';\nimport { Server } from '../server';\n\nexport class Queue implements QueueInterface {\n    /**\n     * The Queue driver.\n     */\n    public driver: QueueInterface;\n\n    /**\n     * Initialize the queue.\n     */\n    constructor(protected server: Server) {\n        if (server.options.queue.driver === 'sync') {\n            this.driver = new SyncQueueDriver(server);\n        } else if (server.options.queue.driver === 'redis') {\n            this.driver = new RedisQueueDriver(server);\n        } else if (server.options.queue.driver === 'sqs') {\n            this.driver = new SqsQueueDriver(server);\n        } else {\n            Log.error('No valid queue driver specified.');\n        }\n    }\n\n    /**\n     * Add a new event with data to queue.\n     */\n    addToQueue(queueName: string, data?: JobData): Promise<void> {\n        return this.driver.addToQueue(queueName, data);\n    }\n\n    /**\n     * Register the code to run when handing the queue.\n     */\n    processQueue(queueName: string, callback: CallableFunction): Promise<void> {\n        return this.driver.processQueue(queueName, callback);\n    }\n\n    /**\n     * Clear the queues for a graceful shutdown.\n     */\n    disconnect(): Promise<void> {\n        return this.driver.disconnect();\n    }\n}\n"
  },
  {
    "path": "src/queues/redis-queue-driver.ts",
    "content": "import async from 'async';\nimport { JobData } from '../webhook-sender';\nimport { Queue, Worker, QueueScheduler } from 'bullmq'\nimport { QueueInterface } from './queue-interface';\nimport Redis, { Cluster, ClusterOptions, RedisOptions } from 'ioredis';\nimport { Server } from '../server';\n\ninterface QueueWithWorker {\n    queue: Queue;\n    worker: Worker;\n    scheduler: QueueScheduler;\n}\n\nexport class RedisQueueDriver implements QueueInterface {\n    /**\n     * The queues with workers list.\n     */\n    protected queueWithWorker: Map<string, QueueWithWorker> = new Map();\n\n    /**\n     * Initialize the Redis Queue Driver.\n     */\n    constructor(protected server: Server) {\n        //\n    }\n\n    /**\n     * Add a new event with data to queue.\n     */\n    addToQueue(queueName: string, data: JobData): Promise<void> {\n        return new Promise(resolve => {\n            let queueWithWorker = this.queueWithWorker.get(queueName);\n\n            if (!queueWithWorker) {\n                return resolve();\n            }\n\n            queueWithWorker.queue.add('webhook', data).then(() => resolve());\n        });\n    }\n\n    /**\n     * Register the code to run when handing the queue.\n     */\n    processQueue(queueName: string, callback: CallableFunction): Promise<void> {\n        return new Promise(resolve => {\n            if (!this.queueWithWorker.has(queueName)) {\n                let redisOptions: RedisOptions|ClusterOptions = {\n                    maxRetriesPerRequest: null,\n                    enableReadyCheck: false,\n                    ...this.server.options.database.redis,\n                    ...this.server.options.queue.redis.redisOptions,\n                    // We set the key prefix on the queue, worker and scheduler instead of on the connection itself\n                    keyPrefix: undefined,\n                };\n\n                const connection = this.server.options.queue.redis.clusterMode\n                    ? new Cluster(this.server.options.database.redis.clusterNodes, { scaleReads: 'slave', ...redisOptions })\n                    : new Redis(redisOptions);\n\n                const queueSharedOptions = {\n                    // We remove a trailing `:` from the prefix because BullMQ adds that already\n                    prefix: this.server.options.database.redis.keyPrefix.replace(/:$/, ''),\n                    connection,\n                };\n\n                this.queueWithWorker.set(queueName, {\n                    queue: new Queue(queueName, {\n                        ...queueSharedOptions,\n                        defaultJobOptions: {\n                            attempts: 6,\n                            backoff: {\n                                type: 'exponential',\n                                delay: 1000,\n                            },\n                            removeOnComplete: true,\n                            removeOnFail: true,\n                        },\n                    }),\n                    // TODO: Sandbox the worker? https://docs.bullmq.io/guide/workers/sandboxed-processors\n                    worker: new Worker(queueName, callback as any, {\n                        ...queueSharedOptions,\n                        concurrency: this.server.options.queue.redis.concurrency,\n                    }),\n                    // TODO: Seperate this from the queue with worker when multipe workers are supported.\n                    //       A single scheduler per queue is needed: https://docs.bullmq.io/guide/queuescheduler\n                    scheduler: new QueueScheduler(queueName, queueSharedOptions),\n                });\n            }\n\n            resolve();\n        });\n    }\n\n    /**\n     * Clear the queues for a graceful shutdown.\n     */\n    disconnect(): Promise<void> {\n        return async.each([...this.queueWithWorker], ([queueName, { queue, worker, scheduler }]: [string, QueueWithWorker], callback) => {\n            scheduler.close().then(() => {\n                worker.close().then(() => callback());\n            });\n        });\n    }\n}\n"
  },
  {
    "path": "src/queues/sqs-queue-driver.ts",
    "content": "import async from 'async';\nimport { Consumer } from 'sqs-consumer';\nimport { createHash } from 'crypto';\nimport { Job } from '../job';\nimport { JobData } from '../webhook-sender';\nimport { Log } from '../log';\nimport { QueueInterface } from './queue-interface';\nimport { Server } from '../server';\nimport { SQS } from 'aws-sdk';\nimport { v4 as uuidv4 } from 'uuid';\n\nexport class SqsQueueDriver implements QueueInterface {\n    /**\n     * The list of consumers with their instance.\n     */\n    protected queueWithConsumer: Map<string, Consumer> = new Map();\n\n    /**\n     * Initialize the Prometheus exporter.\n     */\n    constructor(protected server: Server) {\n        //\n    }\n\n    /**\n     * Add a new event with data to queue.\n     */\n    addToQueue(queueName: string, data: JobData): Promise<void> {\n        return new Promise(resolve => {\n            let message = JSON.stringify(data);\n\n            let params = {\n                MessageBody: message,\n                MessageDeduplicationId: createHash('sha256').update(message).digest('hex'),\n                MessageGroupId: `${data.appId}_${queueName}`,\n                QueueUrl: this.server.options.queue.sqs.queueUrl,\n            };\n\n            this.sqsClient().sendMessage(params, (err, data) => {\n                if (err) {\n                    Log.errorTitle('❎ SQS client could not publish to the queue.');\n                    Log.error({ data, err, params, queueName });\n                }\n\n                if (this.server.options.debug && !err) {\n                    Log.successTitle('✅ SQS client publsihed message to the queue.');\n                    Log.success({ data, err, params, queueName });\n                }\n\n                resolve();\n            });\n        });\n    }\n\n    /**\n     * Register the code to run when handing the queue.\n     */\n    processQueue(queueName: string, callback: CallableFunction): Promise<void> {\n        return new Promise(resolve => {\n            let handleMessage = ({ Body }: { Body: string; }) => {\n                return new Promise<void>(resolve => {\n                    callback(\n                        new Job(uuidv4(), JSON.parse(Body)),\n                        () => {\n                            if (this.server.options.debug) {\n                                Log.successTitle('✅ SQS message processed.');\n                                Log.success({ Body, queueName });\n                            }\n\n                            resolve();\n                        },\n                    );\n                });\n            };\n\n            let consumerOptions = {\n                queueUrl: this.server.options.queue.sqs.queueUrl,\n                sqs: this.sqsClient(),\n                batchSize: this.server.options.queue.sqs.batchSize,\n                pollingWaitTimeMs: this.server.options.queue.sqs.pollingWaitTimeMs,\n                ...this.server.options.queue.sqs.consumerOptions,\n            };\n\n            if (this.server.options.queue.sqs.processBatch) {\n                consumerOptions.handleMessageBatch = (messages) => {\n                    return Promise.all(messages.map(({ Body }) => handleMessage({ Body }))).then(() => {\n                        //\n                    });\n            };\n            } else {\n                consumerOptions.handleMessage = handleMessage;\n            }\n\n            let consumer = Consumer.create(consumerOptions);\n\n            consumer.start();\n\n            this.queueWithConsumer.set(queueName, consumer);\n\n            resolve();\n        });\n    }\n\n    /**\n     * Clear the queues for a graceful shutdown.\n     */\n    disconnect(): Promise<void> {\n        return async.each([...this.queueWithConsumer], ([queueName, consumer]: [string, Consumer], callback) => {\n            if (consumer.isRunning) {\n                consumer.stop();\n                callback();\n            }\n        });\n    }\n\n    /**\n     * Get the SQS client.\n     */\n    protected sqsClient(): SQS {\n        let sqsOptions = this.server.options.queue.sqs;\n\n        return new SQS({\n            apiVersion: '2012-11-05',\n            region: sqsOptions.region || 'us-east-1',\n            endpoint: sqsOptions.endpoint,\n            ...sqsOptions.clientOptions,\n        });\n    }\n}\n"
  },
  {
    "path": "src/queues/sync-queue-driver.ts",
    "content": "import { Job } from '../job';\nimport { JobData } from '../webhook-sender';\nimport { QueueInterface } from './queue-interface';\nimport { Server } from '../server';\nimport { v4 as uuidv4 } from 'uuid';\n\nexport class SyncQueueDriver implements QueueInterface {\n    /**\n     * The list of queues with their code.\n     */\n    protected queues: Map<string, CallableFunction> = new Map();\n\n    /**\n     * Initialize the Sync Queue Driver.\n     */\n    constructor(protected server: Server) {\n        //\n    }\n\n    /**\n     * Add a new event with data to queue.\n     */\n    addToQueue(queueName: string, data: JobData): Promise<void> {\n        return new Promise(resolve => {\n            let jobCallback = this.queues.get(queueName);\n\n            if (!jobCallback) {\n                return resolve();\n            }\n\n            let jobId = uuidv4();\n\n            jobCallback(new Job(jobId, data), resolve);\n        });\n    }\n\n    /**\n     * Register the code to run when handing the queue.\n     */\n    processQueue(queueName: string, callback: CallableFunction): Promise<void> {\n        return new Promise(resolve => {\n            this.queues.set(queueName, callback);\n            resolve();\n        });\n    }\n\n    /**\n     * Clear the queues for a graceful shutdown.\n     */\n    disconnect(): Promise<void> {\n        return Promise.resolve();\n    }\n}\n"
  },
  {
    "path": "src/rate-limiters/cluster-rate-limiter.ts",
    "content": "import { App } from './../app';\nimport { ConsumptionResponse } from './rate-limiter-interface';\nimport { LocalRateLimiter } from './local-rate-limiter';\nimport { RateLimiterAbstract, RateLimiterClusterMasterPM2 } from 'rate-limiter-flexible';\nimport { Server } from '../server';\n\nconst cluster = require('cluster');\nconst pm2 = require('pm2');\n\nexport interface ConsumptionMessage {\n    app: App;\n    eventKey: string;\n    points: number;\n    maxPoints: number;\n}\n\nexport class ClusterRateLimiter extends LocalRateLimiter {\n    /**\n     * Initialize the local rate limiter driver.\n     */\n    constructor(protected server: Server) {\n        super(server);\n\n        if (cluster.isPrimary || typeof cluster.isPrimary === 'undefined') {\n            if (server.pm2) {\n                // With PM2, discovery is not needed.\n                new RateLimiterClusterMasterPM2(pm2);\n            } else {\n                // When a new master is demoted, the rate limiters it has become the pivot points of the real, synced\n                // rate limiter instances. Just trust this value.\n                server.discover.join('rate_limiter:limiters', (rateLimiters: { [key: string]: RateLimiterAbstract }) => {\n                    this.rateLimiters = Object.fromEntries(\n                        Object.entries(rateLimiters).map(([key, rateLimiterObject]: [string, any]) => {\n                            return [\n                                key,\n                                this.createNewRateLimiter(key.split(':')[0], rateLimiterObject._points),\n                            ];\n                        })\n                    );\n                });\n\n                // All nodes need to know when other nodes consumed from the rate limiter.\n                server.discover.join('rate_limiter:consume', ({ app, eventKey, points, maxPoints }: ConsumptionMessage) => {\n                    super.consume(app, eventKey, points, maxPoints);\n                });\n\n                server.discover.on('added', () => {\n                    if (server.nodes.get('self').isMaster) {\n                        // When a new node is added, just send the rate limiters this master instance has.\n                        // This value is the true value of the rate limiters.\n                        this.sendRateLimiters();\n                    }\n                });\n            }\n        }\n    }\n\n    /**\n     * Consume points for a given key, then\n     * return a response object with headers and the success indicator.\n     */\n    protected consume(app: App, eventKey: string, points: number, maxPoints: number): Promise<ConsumptionResponse> {\n        return super.consume(app, eventKey, points, maxPoints).then((response) => {\n            if (response.canContinue) {\n                this.server.discover.send('rate_limiter:consume', {\n                    app, eventKey, points, maxPoints,\n                });\n            }\n\n            return response;\n        });\n    }\n\n    /**\n     * Clear the rate limiter or active connections.\n     */\n    disconnect(): Promise<void> {\n        return super.disconnect().then(() => {\n            // If the current instance is the master and the server is closing,\n            // demote and send the rate limiter of the current instance to the new master.\n            if (this.server.nodes.get('self').isMaster) {\n                this.server.discover.demote();\n                this.server.discover.send('rate_limiter:limiters', this.rateLimiters);\n            }\n        });\n    }\n\n    /**\n     * Send the stored rate limiters this instance currently have.\n     */\n    protected sendRateLimiters(): void {\n        this.server.discover.send('rate_limiter:limiters', this.rateLimiters);\n    }\n}\n"
  },
  {
    "path": "src/rate-limiters/index.ts",
    "content": "export * from './cluster-rate-limiter';\nexport * from './local-rate-limiter';\nexport * from './rate-limiter-interface';\nexport * from './rate-limiter';\nexport * from './redis-rate-limiter';\n"
  },
  {
    "path": "src/rate-limiters/local-rate-limiter.ts",
    "content": "import { App } from './../app';\nimport { ConsumptionResponse, RateLimiterInterface } from './rate-limiter-interface';\nimport { RateLimiterAbstract, RateLimiterMemory, RateLimiterRes } from 'rate-limiter-flexible';\nimport { Server } from '../server';\nimport { WebSocket } from 'uWebSockets.js';\n\nexport class LocalRateLimiter implements RateLimiterInterface {\n    /**\n     * The list of rate limiters bound to each apps that interacts.\n     */\n    protected rateLimiters: { [appId: string]: RateLimiterAbstract } = {\n        //\n    };\n\n    /**\n     * Initialize the local rate limiter driver.\n     */\n    constructor(protected server: Server) {\n        //\n    }\n\n    /**\n     * Consume the points for backend-received events.\n     */\n    consumeBackendEventPoints(points: number, app?: App, ws?: WebSocket): Promise<ConsumptionResponse> {\n        return this.consume(\n            app,\n            `${app.id}:backend:events`,\n            points,\n            app.maxBackendEventsPerSecond as number,\n        );\n    }\n\n    /**\n     * Consume the points for frontend-received events.\n     */\n    consumeFrontendEventPoints(points: number, app?: App, ws?: WebSocket): Promise<ConsumptionResponse> {\n        return this.consume(\n            app,\n            `${app.id}:frontend:events:${ws.id}`,\n            points,\n            app.maxClientEventsPerSecond as number,\n        );\n    }\n\n    /**\n     * Consume the points for HTTP read requests.\n     */\n    consumeReadRequestsPoints(points: number, app?: App, ws?: WebSocket): Promise<ConsumptionResponse> {\n        return this.consume(\n            app,\n            `${app.id}:backend:request_read`,\n            points,\n            app.maxReadRequestsPerSecond as number,\n        );\n    }\n\n    /**\n     * Create a new rate limiter instance.\n     */\n    createNewRateLimiter(appId: string, maxPoints: number): RateLimiterAbstract {\n        return new RateLimiterMemory({\n            points: maxPoints,\n            duration: 1,\n            keyPrefix: `app:${appId}`,\n        });\n    }\n\n    /**\n     * Clear the rate limiter or active connections.\n     */\n    disconnect(): Promise<void> {\n        return Promise.resolve();\n    }\n\n    /**\n     * Initialize a new rate limiter for the given app and event key.\n     */\n    protected initializeRateLimiter(appId: string, eventKey: string, maxPoints: number): Promise<RateLimiterAbstract> {\n        if (this.rateLimiters[`${appId}:${eventKey}`]) {\n            return new Promise(resolve => {\n                this.rateLimiters[`${appId}:${eventKey}`].points = maxPoints;\n\n                resolve(this.rateLimiters[`${appId}:${eventKey}`]);\n            });\n        }\n\n        this.rateLimiters[`${appId}:${eventKey}`] = this.createNewRateLimiter(appId, maxPoints);\n\n        return Promise.resolve(this.rateLimiters[`${appId}:${eventKey}`]);\n    }\n\n    /**\n     * Consume points for a given key, then\n     * return a response object with headers and the success indicator.\n     */\n    protected consume(app: App, eventKey: string, points: number, maxPoints: number): Promise<ConsumptionResponse> {\n        if (maxPoints < 0) {\n            return Promise.resolve({\n                canContinue: true,\n                rateLimiterRes: null,\n                headers: {\n                    //\n                },\n            });\n        }\n\n        let calculateHeaders = (rateLimiterRes: RateLimiterRes) => ({\n            'Retry-After': rateLimiterRes.msBeforeNext / 1000,\n            'X-RateLimit-Limit': maxPoints,\n            'X-RateLimit-Remaining': rateLimiterRes.remainingPoints,\n        });\n\n        return this.initializeRateLimiter(app.id, eventKey, maxPoints).then(rateLimiter => {\n            return rateLimiter.consume(eventKey, points).then((rateLimiterRes: RateLimiterRes) => {\n                return {\n                    canContinue: true,\n                    rateLimiterRes,\n                    headers: calculateHeaders(rateLimiterRes),\n                };\n            }).catch((rateLimiterRes: RateLimiterRes) => {\n                return {\n                    canContinue: false,\n                    rateLimiterRes,\n                    headers: calculateHeaders(rateLimiterRes),\n                };\n            });\n        });\n    }\n}\n"
  },
  {
    "path": "src/rate-limiters/rate-limiter-interface.ts",
    "content": "import { App } from './../app';\nimport { RateLimiterAbstract, RateLimiterRes } from 'rate-limiter-flexible';\nimport { WebSocket } from 'uWebSockets.js';\n\nexport interface ConsumptionResponse {\n    canContinue: boolean;\n    rateLimiterRes: RateLimiterRes|null;\n    headers: {\n        'Retry-After'?: number;\n        'X-RateLimit-Limit'?: number;\n        'X-RateLimit-Remaining'?: number;\n    };\n}\n\nexport interface RateLimiterInterface {\n    /**\n     * Rate Limiter driver.\n     */\n    driver?: RateLimiterInterface;\n\n    /**\n     * Consume the points for backend-received events.\n     */\n    consumeBackendEventPoints(points: number, app?: App, ws?: WebSocket): Promise<ConsumptionResponse>;\n\n    /**\n     * Consume the points for frontend-received events.\n     */\n    consumeFrontendEventPoints(points: number, app?: App, ws?: WebSocket): Promise<ConsumptionResponse>;\n\n    /**\n     * Consume the points for HTTP read requests.\n     */\n    consumeReadRequestsPoints(points: number, app?: App, ws?: WebSocket): Promise<ConsumptionResponse>;\n\n    /**\n     * Create a new rate limiter instance.\n     */\n    createNewRateLimiter(appId: string, maxPoints: number): RateLimiterAbstract;\n\n    /**\n     * Clear the rate limiter or active connections.\n     */\n    disconnect(): Promise<void>;\n}\n"
  },
  {
    "path": "src/rate-limiters/rate-limiter.ts",
    "content": "import { App } from './../app';\nimport { ClusterRateLimiter } from './cluster-rate-limiter';\nimport { ConsumptionResponse, RateLimiterInterface } from './rate-limiter-interface';\nimport { LocalRateLimiter } from './local-rate-limiter';\nimport { Log } from './../log';\nimport { RateLimiterAbstract } from 'rate-limiter-flexible';\nimport { RedisRateLimiter } from './redis-rate-limiter';\nimport { Server } from '../server';\nimport { WebSocket } from 'uWebSockets.js';\n\nexport class RateLimiter implements RateLimiterInterface {\n    /**\n     * Rate Limiter driver.\n     */\n    public driver: RateLimiterInterface;\n\n    /**\n     * Initialize the rate limiter driver.\n     */\n    constructor(server: Server) {\n        if (server.options.rateLimiter.driver === 'local') {\n            this.driver = new LocalRateLimiter(server);\n        } else if (server.options.rateLimiter.driver === 'redis') {\n            this.driver = new RedisRateLimiter(server);\n        } else if (server.options.rateLimiter.driver === 'cluster') {\n            this.driver = new ClusterRateLimiter(server);\n        } else {\n            Log.error('No stats driver specified.');\n        }\n    }\n\n    /**\n     * Consume the points for backend-received events.\n     */\n    consumeBackendEventPoints(points: number, app?: App, ws?: WebSocket): Promise<ConsumptionResponse> {\n        return this.driver.consumeBackendEventPoints(points, app, ws);\n    }\n\n    /**\n     * Consume the points for frontend-received events.\n     */\n    consumeFrontendEventPoints(points: number, app?: App, ws?: WebSocket): Promise<ConsumptionResponse> {\n        return this.driver.consumeFrontendEventPoints(points, app, ws);\n    }\n\n    /**\n     * Consume the points for HTTP read requests.\n     */\n    consumeReadRequestsPoints(points: number, app?: App, ws?: WebSocket): Promise<ConsumptionResponse> {\n        return this.driver.consumeReadRequestsPoints(points, app, ws);\n    }\n\n    /**\n     * Create a new rate limiter instance.\n     */\n    createNewRateLimiter(appId: string, maxPoints: number): RateLimiterAbstract {\n        return this.driver.createNewRateLimiter(appId, maxPoints);\n    }\n\n    /**\n     * Clear the rate limiter or active connections.\n     */\n     disconnect(): Promise<void> {\n        return this.driver.disconnect();\n    }\n}\n"
  },
  {
    "path": "src/rate-limiters/redis-rate-limiter.ts",
    "content": "import { LocalRateLimiter } from './local-rate-limiter';\nimport { RateLimiterAbstract, RateLimiterRedis } from 'rate-limiter-flexible';\nimport Redis, { Cluster, ClusterOptions, RedisOptions } from 'ioredis';\nimport { Server } from '../server';\n\nexport class RedisRateLimiter extends LocalRateLimiter {\n    /**\n     * The Redis connection.\n     */\n    protected redisConnection: Redis|Cluster;\n\n    /**\n     * Initialize the Redis rate limiter driver.\n     */\n    constructor(protected server: Server) {\n        super(server);\n\n        let redisOptions: ClusterOptions|RedisOptions = {\n            ...server.options.database.redis,\n            ...server.options.rateLimiter.redis.redisOptions,\n        };\n\n        this.redisConnection = server.options.rateLimiter.redis.clusterMode\n            ? new Cluster(server.options.database.redis.clusterNodes, {\n                scaleReads: 'slave',\n                ...redisOptions,\n            })\n            : new Redis(redisOptions);\n    }\n\n    /**\n     * Initialize a new rate limiter for the given app and event key.\n     */\n    protected initializeRateLimiter(appId: string, eventKey: string, maxPoints: number): Promise<RateLimiterAbstract> {\n        return Promise.resolve(new RateLimiterRedis({\n            points: maxPoints,\n            duration: 1,\n            storeClient: this.redisConnection,\n            keyPrefix: `app:${appId}`,\n            // TODO: Insurance limiter?\n            // insuranceLimiter: super.createNewRateLimiter(appId, maxPoints),\n        }));\n    }\n\n    /**\n     * Clear the rate limiter or active connections.\n     */\n    disconnect(): Promise<void> {\n        return this.redisConnection.quit().then(() => {\n            //\n        });\n    }\n}\n"
  },
  {
    "path": "src/server.ts",
    "content": "import * as dot from 'dot-wild';\nimport { Adapter, AdapterInterface } from './adapters';\nimport { AppManager, AppManagerInterface } from './app-managers';\nimport { CacheManager } from './cache-managers/cache-manager';\nimport { CacheManagerInterface } from './cache-managers/cache-manager-interface';\nimport { HttpHandler } from './http-handler';\nimport { HttpRequest, HttpResponse, TemplatedApp } from 'uWebSockets.js';\nimport { Log } from './log';\nimport { Metrics, MetricsInterface } from './metrics';\nimport { Node } from './node';\nimport { Options } from './options';\nimport { Queue } from './queues/queue';\nimport { QueueInterface } from './queues/queue-interface';\nimport { RateLimiter } from './rate-limiters/rate-limiter';\nimport { RateLimiterInterface } from './rate-limiters/rate-limiter-interface';\nimport { uWebSocketMessage } from './message';\nimport { v4 as uuidv4 } from 'uuid';\nimport { WebhookSender } from './webhook-sender';\nimport { WebSocket } from 'uWebSockets.js';\nimport { WsHandler } from './ws-handler';\n\nconst Discover = require('node-discover');\nconst queryString = require('query-string');\nconst uWS = require('uWebSockets.js');\n\nexport class Server {\n    /**\n     * The list of options for the server.\n     */\n    public options: Options = {\n        adapter: {\n            driver: 'local',\n            redis: {\n                requestsTimeout: 5_000,\n                prefix: '',\n                redisPubOptions: {\n                    //\n                },\n                redisSubOptions: {\n                    //\n                },\n                clusterMode: false,\n            },\n            cluster: {\n                requestsTimeout: 5_000,\n            },\n            nats: {\n                requestsTimeout: 5_000,\n                prefix: '',\n                servers: ['127.0.0.1:4222'],\n                user: null,\n                pass: null,\n                token: null,\n                timeout: 10_000,\n                nodesNumber: null,\n            },\n        },\n        appManager: {\n            driver: 'array',\n            cache: {\n                enabled: false,\n                ttl: -1,\n            },\n            array: {\n                apps: [\n                    {\n                        id: 'app-id',\n                        key: 'app-key',\n                        secret: 'app-secret',\n                        maxConnections: -1,\n                        enableClientMessages: false,\n                        enabled: true,\n                        maxBackendEventsPerSecond: -1,\n                        maxClientEventsPerSecond: -1,\n                        maxReadRequestsPerSecond: -1,\n                        webhooks: [],\n                    },\n                ],\n            },\n            dynamodb: {\n                table: 'apps',\n                region: 'us-east-1',\n                endpoint: null,\n            },\n            mysql: {\n                table: 'apps',\n                version: '8.0',\n                useMysql2: false,\n            },\n            postgres: {\n                table: 'apps',\n                version: '13.3',\n            },\n        },\n        cache: {\n            driver: 'memory',\n            redis: {\n                redisOptions: {\n                    //\n                },\n                clusterMode: false,\n            },\n        },\n        channelLimits: {\n            maxNameLength: 200,\n            cacheTtl: 3600,\n        },\n        cluster: {\n            hostname: '0.0.0.0',\n            helloInterval: 500,\n            checkInterval: 500,\n            nodeTimeout: 2000,\n            masterTimeout: 2000,\n            port: 11002,\n            prefix: '',\n            ignoreProcess: true,\n            broadcast: '255.255.255.255',\n            unicast: null,\n            multicast: null,\n        },\n        cors: {\n            credentials: true,\n            origin: ['*'],\n            methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],\n            allowedHeaders: [\n                'Origin',\n                'Content-Type',\n                'X-Auth-Token',\n                'X-Requested-With',\n                'Accept',\n                'Authorization',\n                'X-CSRF-TOKEN',\n                'XSRF-TOKEN',\n                'X-Socket-Id',\n            ],\n        },\n        database: {\n            mysql: {\n                host: '127.0.0.1',\n                port: 3306,\n                user: 'root',\n                password: 'password',\n                database: 'main',\n            },\n            postgres: {\n                host: '127.0.0.1',\n                port: 5432,\n                user: 'postgres',\n                password: 'password',\n                database: 'main',\n            },\n            redis: {\n                host: '127.0.0.1',\n                port: 6379,\n                db: 0,\n                username: null,\n                password: null,\n                keyPrefix: '',\n                sentinels: null,\n                sentinelPassword: null,\n                name: 'mymaster',\n                clusterNodes: [],\n            },\n        },\n        databasePooling: {\n            enabled: false,\n            min: 0,\n            max: 7,\n        },\n        debug: false,\n        eventLimits: {\n            maxChannelsAtOnce: 100,\n            maxNameLength: 200,\n            maxPayloadInKb: 100,\n            maxBatchSize: 10,\n        },\n        host: '0.0.0.0',\n        httpApi: {\n            requestLimitInMb: 100,\n            acceptTraffic: {\n                memoryThreshold: 85,\n            },\n        },\n        instance: {\n            process_id: process.pid || uuidv4(),\n        },\n        metrics: {\n            enabled: false,\n            driver: 'prometheus',\n            host: '0.0.0.0',\n            prometheus: {\n                prefix: 'soketi_',\n            },\n            port: 9601,\n        },\n        mode: 'full',\n        port: 6001,\n        pathPrefix: '',\n        presence: {\n            maxMembersPerChannel: 100,\n            maxMemberSizeInKb: 2,\n        },\n        queue: {\n            driver: 'sync',\n            redis: {\n                concurrency: 1,\n                redisOptions: {\n                    //\n                },\n                clusterMode: false,\n            },\n            sqs: {\n                region: 'us-east-1',\n                endpoint: null,\n                clientOptions: {},\n                consumerOptions: {},\n                queueUrl: '',\n                processBatch: false,\n                batchSize: 1,\n                pollingWaitTimeMs: 0,\n            },\n        },\n        rateLimiter: {\n            driver: 'local',\n            redis: {\n                redisOptions: {\n                    //\n                },\n                clusterMode: false,\n            },\n        },\n        shutdownGracePeriod: 3_000,\n        ssl: {\n            certPath: '',\n            keyPath: '',\n            passphrase: '',\n            caPath: '',\n        },\n        userAuthenticationTimeout: 30_000,\n        webhooks: {\n            batching: {\n                enabled: false,\n                duration: 50,\n            },\n        },\n    };\n\n    /**\n     * Wether the server is closing or not.\n     */\n    public closing = false;\n\n    /**\n     * The server process.\n     */\n    private serverProcess;\n\n    /**\n     * The metrics server process.\n     */\n    private metricsServerProcess;\n\n    /**\n     * The WS handler for the incoming connections.\n     */\n    public wsHandler: WsHandler;\n\n    /**\n     * The HTTP handler for the REST API.\n     */\n    public httpHandler: HttpHandler;\n\n    /**\n     * The app manager used for retrieving apps.\n     */\n    public appManager: AppManagerInterface;\n\n    /**\n     * The metrics handler.\n     */\n    public metricsManager: MetricsInterface;\n\n    /**\n     * The adapter used to interact with the socket storage.\n     */\n    public adapter: AdapterInterface;\n\n    /**\n     * The rate limiter handler for the server.\n     */\n    public rateLimiter: RateLimiterInterface;\n\n    /**\n     * The queue manager.\n     */\n    public queueManager: QueueInterface;\n\n    /**\n     * The cache manager.\n     */\n    public cacheManager: CacheManagerInterface;\n\n    /**\n     * The sender for webhooks.\n     */\n    public webhookSender: WebhookSender;\n\n    /**\n     * Wether the server is running under PM2.\n     */\n    public pm2 = false;\n\n    /**\n     * The list of nodes in the current private network.\n     */\n    public nodes: Map<string, Node> = new Map<string, Node>();\n\n    /**\n     * The Discover instance.\n     */\n    public discover: typeof Discover;\n\n    /**\n     * Initialize the server.\n     */\n    constructor(options = {}) {\n        this.setOptions(options);\n    }\n\n    /**\n     * Start the server statically.\n     */\n    static async start(options: any = {}, callback?: CallableFunction) {\n        return (new Server(options)).start(callback);\n    }\n\n    /**\n     * Start the server.\n     */\n    async start(callback?: CallableFunction) {\n        Log.br();\n\n        this.configureDiscovery().then(() => {\n            this.initializeDrivers().then(() => {\n\n                if (this.options.debug) {\n                    console.dir(this.options, { depth: 100 });\n                }\n\n                this.wsHandler = new WsHandler(this);\n                this.httpHandler = new HttpHandler(this);\n\n                if (this.options.debug) {\n                    Log.info('📡 soketi initialization....');\n                    Log.info('⚡ Initializing the HTTP API & Websockets Server...');\n                }\n\n                let server: TemplatedApp = this.shouldConfigureSsl()\n                    ? uWS.SSLApp({\n                        key_file_name: this.options.ssl.keyPath,\n                        cert_file_name: this.options.ssl.certPath,\n                        passphrase: this.options.ssl.passphrase,\n                        ca_file_name: this.options.ssl.caPath,\n                    })\n                    : uWS.App();\n\n                let metricsServer: TemplatedApp = uWS.App();\n\n                if (this.options.debug) {\n                    Log.info('⚡ Initializing the Websocket listeners and channels...');\n                }\n\n                this.configureWebsockets(server).then(server => {\n                    if (this.options.debug) {\n                        Log.info('⚡ Initializing the HTTP webserver...');\n                    }\n\n                    this.configureHttp(server).then(server => {\n                        this.configureMetricsServer(metricsServer).then(metricsServer => {\n                            metricsServer.listen(this.options.metrics.host, this.options.metrics.port, metricsServerProcess => {\n                                this.metricsServerProcess = metricsServerProcess;\n\n                                server.listen(this.options.host, this.options.port, serverProcess => {\n                                    this.serverProcess = serverProcess;\n\n                                    Log.successTitle('🎉 Server is up and running!');\n                                    Log.successTitle(`📡 The Websockets server is available at 127.0.0.1:${this.options.port}`);\n                                    Log.successTitle(`🔗 The HTTP API server is available at http://127.0.0.1:${this.options.port}`);\n                                    Log.successTitle(`🎊 The /usage endpoint is available on port ${this.options.metrics.port}.`);\n\n                                    if (this.options.metrics.enabled) {\n                                        Log.successTitle(`🌠 Prometheus /metrics endpoint is available on port ${this.options.metrics.port}.`);\n                                    }\n\n                                    Log.br();\n\n                                    if (callback) {\n                                        callback(this);\n                                    }\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    }\n\n    /**\n     * Stop the server.\n     */\n    stop(): Promise<void> {\n        this.closing = true;\n\n        Log.br();\n        Log.warning('🚫 New users cannot connect to this instance anymore. Preparing for signaling...');\n        Log.warning('⚡ The server is closing and signaling the existing connections to terminate.');\n        Log.br();\n\n        return this.wsHandler.closeAllLocalSockets().then(() => {\n            return new Promise(resolve => {\n                if (this.options.debug) {\n                    Log.warningTitle('⚡ All sockets were closed. Now closing the server.');\n                }\n\n                setTimeout(() => {\n                    Promise.all([\n                        this.metricsManager.clear(),\n                        this.queueManager.disconnect(),\n                        this.rateLimiter.disconnect(),\n                        this.cacheManager.disconnect(),\n                    ]).then(() => {\n                        this.adapter.disconnect().then(() => {\n                            if (this.serverProcess) {\n                                uWS.us_listen_socket_close(this.serverProcess);\n                            }\n\n                            if (this.metricsServerProcess) {\n                                uWS.us_listen_socket_close(this.metricsServerProcess);\n                            }\n                        }).then(() => resolve());\n                    });\n                }, this.options.shutdownGracePeriod);\n            });\n        });\n    }\n\n    /**\n     * Set the options for the server. The key should be string.\n     * For nested values, use the dot notation.\n     */\n    setOptions(options: { [key: string]: any; }): void {\n        for (let optionKey in options) {\n            // Make sure none of the id's are int.\n            if (optionKey.match(\"^appManager.array.apps.\\\\d+.id\")) {\n                if (Number.isInteger(options[optionKey])) {\n                    options[optionKey] = options[optionKey].toString();\n                }\n            }\n\n            this.options = dot.set(this.options, optionKey, options[optionKey]);\n        }\n    }\n\n    /**\n     * Initialize the drivers for the server.\n     */\n    initializeDrivers(): Promise<any> {\n        return Promise.all([\n            this.setAppManager(new AppManager(this)),\n            this.setAdapter(new Adapter(this)),\n            this.setMetricsManager(new Metrics(this)),\n            this.setRateLimiter(new RateLimiter(this)),\n            this.setQueueManager(new Queue(this)),\n            this.setCacheManager(new CacheManager(this)),\n            this.setWebhookSender(),\n        ]);\n    }\n\n    /**\n     * Set the app manager.\n     */\n    setAppManager(instance: AppManagerInterface): void {\n        this.appManager = instance;\n    }\n\n    /**\n     * Set the adapter.\n     */\n    setAdapter(instance: AdapterInterface): Promise<void> {\n        return new Promise(resolve => {\n            instance.init().then(() => {\n                this.adapter = instance;\n                resolve();\n            });\n        });\n    }\n\n    /**\n     * Set the metrics manager.\n     */\n    setMetricsManager(instance: MetricsInterface): Promise<void> {\n        return new Promise(resolve => {\n            this.metricsManager = instance;\n            resolve();\n        });\n    }\n\n    /**\n     * Set the rate limiter.\n     */\n    setRateLimiter(instance: RateLimiterInterface): Promise<void> {\n        return new Promise(resolve => {\n            this.rateLimiter = instance;\n            resolve();\n        });\n    }\n\n    /**\n     * Set the queue manager.\n     */\n    setQueueManager(instance: QueueInterface): Promise<void> {\n        return new Promise(resolve => {\n            this.queueManager = instance;\n            resolve();\n        });\n    }\n\n    /**\n     * Set the cache manager.\n     */\n    setCacheManager(instance: CacheManagerInterface): Promise<void> {\n        return new Promise(resolve => {\n            this.cacheManager = instance;\n            resolve();\n        });\n    }\n\n    /**\n     * Set the webhook sender.\n     */\n    setWebhookSender(): Promise<void> {\n        return new Promise(resolve => {\n            this.webhookSender = new WebhookSender(this);\n            resolve();\n        });\n    }\n\n    /**\n     * Generates the URL with the set pathPrefix from options.\n     */\n    protected url(path: string): string {\n        return this.options.pathPrefix + path;\n    }\n\n    /**\n     * Get the cluster prefix name for discover.\n     */\n    clusterPrefix(channel: string): string {\n        if (this.options.cluster.prefix) {\n            channel = this.options.cluster.prefix + '#' + channel;\n        }\n\n        return channel;\n    }\n\n    /**\n     * Configure the private network discovery for this node.\n     */\n    protected configureDiscovery(): Promise<void> {\n        return new Promise(resolve => {\n            this.discover = Discover(this.options.cluster, () => {\n                this.nodes.set('self', this.discover.me);\n\n                this.discover.on('promotion', () => {\n                    this.nodes.set('self', this.discover.me);\n\n                    if (this.options.debug) {\n                        Log.discoverTitle('Promoted from node to master.');\n                        Log.discover(this.discover.me);\n                    }\n                });\n\n                this.discover.on('demotion', () => {\n                    this.nodes.set('self', this.discover.me);\n\n                    if (this.options.debug) {\n                        Log.discoverTitle('Demoted from master to node.');\n                        Log.discover(this.discover.me);\n                    }\n                });\n\n                this.discover.on('added', (node: Node) => {\n                    this.nodes.set('self', this.discover.me);\n                    this.nodes.set(node.id, node);\n\n                    if (this.options.debug) {\n                        Log.discoverTitle('New node added.');\n                        Log.discover(node);\n                    }\n                });\n\n                this.discover.on('removed', (node: Node) => {\n                    this.nodes.set('self', this.discover.me);\n                    this.nodes.delete(node.id);\n\n                    if (this.options.debug) {\n                        Log.discoverTitle('Node removed.');\n                        Log.discover(node);\n                    }\n                });\n\n                this.discover.on('master', (node: Node) => {\n                    this.nodes.set('self', this.discover.me);\n                    this.nodes.set(node.id, node);\n\n                    if (this.options.debug) {\n                        Log.discoverTitle('New master.');\n                        Log.discover(node);\n                    }\n                });\n\n                resolve();\n            });\n        });\n    }\n\n    /**\n     * Configure the WebSocket logic.\n     */\n    protected configureWebsockets(server: TemplatedApp): Promise<TemplatedApp> {\n        return new Promise(resolve => {\n            if (this.canProcessRequests()) {\n                server = server.ws(this.url('/app/:id'), {\n                    idleTimeout: 120, // According to protocol\n                    maxBackpressure: 1024 * 1024,\n                    maxPayloadLength: 100 * 1024 * 1024, // 100 MB\n                    message: (ws: WebSocket, message: uWebSocketMessage, isBinary: boolean) => this.wsHandler.onMessage(ws, message, isBinary),\n                    open: (ws: WebSocket) => this.wsHandler.onOpen(ws),\n                    close: (ws: WebSocket, code: number, message: uWebSocketMessage) => this.wsHandler.onClose(ws, code, message),\n                    upgrade: (res: HttpResponse, req: HttpRequest, context) => this.wsHandler.handleUpgrade(res, req, context),\n                });\n            }\n\n            resolve(server);\n        });\n    }\n\n    /**\n     * Configure the HTTP REST API server.\n     */\n    protected configureHttp(server: TemplatedApp): Promise<TemplatedApp> {\n        return new Promise(resolve => {\n            server.get(this.url('/'), (res, req) => this.httpHandler.healthCheck(res));\n            server.get(this.url('/ready'), (res, req) => this.httpHandler.ready(res));\n\n            if (this.canProcessRequests()) {\n                server.get(this.url('/accept-traffic'), (res, req) => this.httpHandler.acceptTraffic(res));\n\n                server.get(this.url('/apps/:appId/channels'), (res, req) => {\n                    res.params = { appId: req.getParameter(0) };\n                    res.query = queryString.parse(req.getQuery());\n                    res.method = req.getMethod().toUpperCase();\n                    res.url = req.getUrl();\n\n                    return this.httpHandler.channels(res);\n                });\n\n                server.get(this.url('/apps/:appId/channels/:channelName'), (res, req) => {\n                    res.params = { appId: req.getParameter(0), channel: req.getParameter(1) };\n                    res.query = queryString.parse(req.getQuery());\n                    res.method = req.getMethod().toUpperCase();\n                    res.url = req.getUrl();\n\n                    return this.httpHandler.channel(res);\n                });\n\n                server.get(this.url('/apps/:appId/channels/:channelName/users'), (res, req) => {\n                    res.params = { appId: req.getParameter(0), channel: req.getParameter(1) };\n                    res.query = queryString.parse(req.getQuery());\n                    res.method = req.getMethod().toUpperCase();\n                    res.url = req.getUrl();\n\n                    return this.httpHandler.channelUsers(res);\n                });\n\n                server.post(this.url('/apps/:appId/events'), (res, req) => {\n                    res.params = { appId: req.getParameter(0) };\n                    res.query = queryString.parse(req.getQuery());\n                    res.method = req.getMethod().toUpperCase();\n                    res.url = req.getUrl();\n\n                    return this.httpHandler.events(res);\n                });\n\n                server.post(this.url('/apps/:appId/batch_events'), (res, req) => {\n                    res.params = { appId: req.getParameter(0) };\n                    res.query = queryString.parse(req.getQuery());\n                    res.method = req.getMethod().toUpperCase();\n                    res.url = req.getUrl();\n\n                    return this.httpHandler.batchEvents(res);\n                });\n\n                server.post(this.url('/apps/:appId/users/:userId/terminate_connections'), (res, req) => {\n                    res.params = { appId: req.getParameter(0), userId: req.getParameter(1) };\n                    res.query = queryString.parse(req.getQuery());\n                    res.method = req.getMethod().toUpperCase();\n                    res.url = req.getUrl();\n\n                    return this.httpHandler.terminateUserConnections(res);\n                });\n            }\n\n            server.any(this.url('/*'), (res, req) => {\n                return this.httpHandler.notFound(res);\n            });\n\n            resolve(server);\n        });\n    }\n\n    /**\n     * Configure the metrics server at a separate port for under-the-firewall access.\n     */\n    protected configureMetricsServer(metricsServer: TemplatedApp): Promise<TemplatedApp> {\n        return new Promise(resolve => {\n            Log.info('🕵️‍♂️ Initiating metrics endpoints...');\n            Log.br();\n\n            metricsServer.get(this.url('/'), (res, req) => this.httpHandler.healthCheck(res));\n            metricsServer.get(this.url('/ready'), (res, req) => this.httpHandler.ready(res));\n            metricsServer.get(this.url('/usage'), (res, req) => this.httpHandler.usage(res));\n\n            if (this.options.metrics.enabled) {\n                metricsServer.get(this.url('/metrics'), (res, req) => {\n                    res.query = queryString.parse(req.getQuery());\n\n                    return this.httpHandler.metrics(res);\n                });\n            }\n\n            resolve(metricsServer);\n        });\n    }\n\n    /**\n     * Wether the server should start in SSL mode.\n     */\n    protected shouldConfigureSsl(): boolean {\n        return this.options.ssl.certPath !== '' ||\n            this.options.ssl.keyPath !== '';\n    }\n\n    /**\n     * Check if the server instance can process queues.\n     */\n    public canProcessQueues(): boolean {\n        return ['worker', 'full'].includes(this.options.mode);\n    }\n\n    /**\n     * Check if the server instance can process requests\n     * for the Pusher protocol API (both REST and WebSockets).\n     */\n    public canProcessRequests(): boolean {\n        return ['server', 'full'].includes(this.options.mode);\n    }\n}\n"
  },
  {
    "path": "src/utils.ts",
    "content": "export class Utils {\n    /**\n     * Allowed client events patterns.\n     *\n     * @type {string[]}\n     */\n    protected static _clientEventPatterns: string[] = [\n        'client-*',\n    ];\n\n    /**\n     * Channels and patters for private channels.\n     *\n     * @type {string[]}\n     */\n    protected static _privateChannelPatterns: string[] = [\n        'private-*',\n        'private-encrypted-*',\n        'presence-*',\n    ];\n\n    /**\n     * Channels with patters for caching channels.\n     *\n     * @type {string[]}\n     */\n    protected static _cachingChannelPatterns: string[] = [\n        'cache-*',\n        'private-cache-*',\n        'private-encrypted-cache-*',\n        'presence-cache-*',\n    ];\n\n    /**\n     * Get the amount of bytes from given parameters.\n     */\n    static dataToBytes(...data: any): number {\n        return data.reduce((totalBytes, element) => {\n            element = typeof element === 'string' ? element : JSON.stringify(element);\n\n            try {\n                return totalBytes += Buffer.byteLength(element, 'utf8');\n            } catch (e) {\n                return totalBytes;\n            }\n        }, 0);\n    }\n\n    /**\n     * Get the amount of kilobytes from given parameters.\n     */\n    static dataToKilobytes(...data: any): number {\n        return this.dataToBytes(...data) / 1024;\n    }\n\n    /**\n     * Get the amount of megabytes from given parameters.\n     */\n    static dataToMegabytes(...data: any): number {\n        return this.dataToKilobytes(...data) / 1024;\n    }\n\n    /**\n     * Check if the given channel name is private.\n     */\n    static isPrivateChannel(channel: string): boolean {\n        let isPrivate = false;\n\n        this._privateChannelPatterns.forEach(pattern => {\n            let regex = new RegExp(pattern.replace('*', '.*'));\n\n            if (regex.test(channel)) {\n                isPrivate = true;\n            }\n        });\n\n        return isPrivate;\n    }\n\n    /**\n     * Check if the given channel name is a presence channel.\n     */\n    static isPresenceChannel(channel: string): boolean {\n        return channel.lastIndexOf('presence-', 0) === 0;\n    }\n\n    /**\n     * Check if the given channel name is a encrypted private channel.\n     */\n    static isEncryptedPrivateChannel(channel: string): boolean {\n        return channel.lastIndexOf('private-encrypted-', 0) === 0;\n    }\n\n    /**\n     * Check if the given channel accepts caching.\n     */\n    static isCachingChannel(channel: string): boolean {\n        let isCachingChannel = false;\n\n        this._cachingChannelPatterns.forEach(pattern => {\n            let regex = new RegExp(pattern.replace('*', '.*'));\n\n            if (regex.test(channel)) {\n                isCachingChannel = true;\n            }\n        });\n\n        return isCachingChannel;\n    }\n\n    /**\n     * Check if client is a client event.\n     */\n    static isClientEvent(event: string): boolean {\n        let isClientEvent = false;\n\n        this._clientEventPatterns.forEach(pattern => {\n            let regex = new RegExp(pattern.replace('*', '.*'));\n\n            if (regex.test(event)) {\n                isClientEvent = true;\n            }\n        });\n\n        return isClientEvent;\n    }\n\n    /**\n     * Check if the channel name is restricted for connections from the client.\n     * Read: https://pusher.com/docs/channels/using_channels/channels/#channel-naming-conventions\n     */\n    static restrictedChannelName(name: string) {\n        return /^#?[-a-zA-Z0-9_=@,.;]+$/.test(name) === false;\n    }\n}\n"
  },
  {
    "path": "src/webhook-sender.ts",
    "content": "import { App, WebhookInterface } from './app';\nimport async from 'async';\nimport axios from 'axios';\nimport { createHmac } from 'crypto';\nimport { Utils } from './utils';\nimport { Lambda } from 'aws-sdk';\nimport { Log } from './log';\nimport { Server } from './server';\n\nexport interface ClientEventData {\n    name: string;\n    channel: string;\n    event?: string,\n    data?: {\n        [key: string]: any;\n    };\n    socket_id?: string;\n    user_id?: string;\n    time_ms?: number;\n}\n\nexport interface JobData {\n    appKey: string;\n    appId: string;\n    payload: {\n        time_ms: number;\n        events: ClientEventData[];\n    },\n    originalPusherSignature: string;\n}\n\n/**\n * Create the HMAC for the given data.\n */\nexport function createWebhookHmac(data: string, secret: string): string {\n    return createHmac('sha256', secret)\n        .update(data)\n        .digest('hex');\n}\n\nexport class WebhookSender {\n    /**\n     * Batch of ClientEventData, to be sent as one webhook.\n     */\n    public batch: ClientEventData[]  = [];\n\n    /**\n     * Whether current process has nominated batch handler.\n     */\n    public batchHasLeader = false;\n\n    /**\n     * Initialize the Webhook sender.\n     */\n    constructor(protected server: Server) {\n        let queueProcessor = (job, done) => {\n            let rawData: JobData = job.data;\n\n            const { appKey, payload, originalPusherSignature } = rawData;\n\n            server.appManager.findByKey(appKey).then(app => {\n                // Ensure the payload hasn't been tampered with between the job being dispatched\n                // and here, as we may need to recalculate the signature post filtration.\n                if (originalPusherSignature !== createWebhookHmac(JSON.stringify(payload), app.secret)) {\n                    return;\n                }\n\n                async.each(app.webhooks, (webhook: WebhookInterface, resolveWebhook) => {\n                    const originalEventsLength = payload.events.length;\n                    let filteredPayloadEvents = payload.events;\n\n                    filteredPayloadEvents = filteredPayloadEvents.filter(event => {\n                        if (!webhook.event_types.includes(event.name)) {\n                            return false;\n                        }\n\n                        if (webhook.filter) {\n                            if (webhook.filter.channel_name_starts_with && !event.channel.startsWith(webhook.filter.channel_name_starts_with)) {\n                                return false;\n                            }\n\n                            if (webhook.filter.channel_name_ends_with && !event.channel.endsWith(webhook.filter.channel_name_ends_with)) {\n                                return false;\n                            }\n                        }\n\n                        return true;\n                    });\n\n                    // If there's no webhooks to send after filtration, we should resolve early.\n                    if (filteredPayloadEvents.length === 0) {\n                        return resolveWebhook();\n                    }\n\n                    // If any events have been filtered out, regenerate the signature\n                    let pusherSignature = (originalEventsLength !== filteredPayloadEvents.length)\n                        ? createWebhookHmac(JSON.stringify(payload), app.secret)\n                        : originalPusherSignature;\n\n                    if (this.server.options.debug) {\n                        Log.webhookSenderTitle('🚀 Processing webhook from queue.');\n                        Log.webhookSender({ appKey, payload, pusherSignature });\n                    }\n\n                    const headers = {\n                        'Accept': 'application/json',\n                        'Content-Type': 'application/json',\n                        'User-Agent': `SoketiWebhooksAxiosClient/1.0 (Process: ${this.server.options.instance.process_id})`,\n                        // We specifically merge in the custom headers here so the headers below cannot be overwritten\n                        ...webhook.headers ?? {},\n                        'X-Pusher-Key': appKey,\n                        'X-Pusher-Signature': pusherSignature,\n                    };\n\n                    // Send HTTP POST to the target URL\n                    if (webhook.url) {\n                        axios.post(webhook.url, payload, { headers }).then((res) => {\n                            if (this.server.options.debug) {\n                                Log.webhookSenderTitle('✅ Webhook sent.');\n                                Log.webhookSender({ webhook, payload });\n                            }\n                        }).catch(err => {\n                            // TODO: Maybe retry exponentially?\n\n                            if (this.server.options.debug) {\n                                Log.webhookSenderTitle('❎ Webhook could not be sent.');\n                                Log.webhookSender({ err, webhook, payload });\n                            }\n                        }).then(() => resolveWebhook());\n                    } else if (webhook.lambda_function) {\n                        // Invoke a Lambda function\n                        const params = {\n                            FunctionName: webhook.lambda_function,\n                            InvocationType: webhook.lambda.async ? 'Event' : 'RequestResponse',\n                            Payload: Buffer.from(JSON.stringify({ payload, headers })),\n                        };\n\n                        let lambda = new Lambda({\n                            apiVersion: '2015-03-31',\n                            region: webhook.lambda.region || 'us-east-1',\n                            ...(webhook.lambda.client_options || {}),\n                        });\n\n                        lambda.invoke(params, (err, data) => {\n                            if (err) {\n                                if (this.server.options.debug) {\n                                    Log.webhookSenderTitle('❎ Lambda trigger failed.');\n                                    Log.webhookSender({ webhook, err, data });\n                                }\n                            } else {\n                                if (this.server.options.debug) {\n                                    Log.webhookSenderTitle('✅ Lambda triggered.');\n                                    Log.webhookSender({ webhook, payload });\n                                }\n                            }\n\n                            resolveWebhook();\n                        });\n                    }\n                }).then(() => {\n                    if (typeof done === 'function') {\n                        done();\n                    }\n                });\n            });\n        };\n\n        // TODO: Maybe have one queue per app to reserve queue thresholds?\n        if (server.canProcessQueues()) {\n            server.queueManager.processQueue('client_event_webhooks', queueProcessor);\n            server.queueManager.processQueue('member_added_webhooks', queueProcessor);\n            server.queueManager.processQueue('member_removed_webhooks', queueProcessor);\n            server.queueManager.processQueue('channel_vacated_webhooks', queueProcessor);\n            server.queueManager.processQueue('channel_occupied_webhooks', queueProcessor);\n            server.queueManager.processQueue('cache_miss_webhooks', queueProcessor);\n        }\n    }\n\n    /**\n     * Send a webhook for the client event.\n     */\n    public sendClientEvent(app: App, channel: string, event: string, data: any, socketId?: string, userId?: string) {\n        if (!app.hasClientEventWebhooks) {\n            return;\n        }\n\n        let formattedData: ClientEventData = {\n            name: App.CLIENT_EVENT_WEBHOOK,\n            channel,\n            event,\n            data,\n        };\n\n        if (socketId) {\n            formattedData.socket_id = socketId;\n        }\n\n        if (userId && Utils.isPresenceChannel(channel)) {\n            formattedData.user_id = userId;\n        }\n\n        this.send(app, formattedData, 'client_event_webhooks');\n    }\n\n    /**\n     * Send a member_added event.\n     */\n    public sendMemberAdded(app: App, channel: string, userId: string): void {\n        if (!app.hasMemberAddedWebhooks) {\n            return;\n        }\n\n        this.send(app, {\n            name: App.MEMBER_ADDED_WEBHOOK,\n            channel,\n            user_id: userId,\n        }, 'member_added_webhooks');\n    }\n\n    /**\n     * Send a member_removed event.\n     */\n    public sendMemberRemoved(app: App, channel: string, userId: string): void {\n        if (!app.hasMemberRemovedWebhooks) {\n            return;\n        }\n\n        this.send(app, {\n            name: App.MEMBER_REMOVED_WEBHOOK,\n            channel,\n            user_id: userId,\n        }, 'member_removed_webhooks');\n    }\n\n    /**\n     * Send a channel_vacated event.\n     */\n    public sendChannelVacated(app: App, channel: string): void {\n        if (!app.hasChannelVacatedWebhooks) {\n            return;\n        }\n\n        this.send(app, {\n            name: App.CHANNEL_VACATED_WEBHOOK,\n            channel,\n        }, 'channel_vacated_webhooks');\n    }\n\n    /**\n     * Send a channel_occupied event.\n     */\n    public sendChannelOccupied(app: App, channel: string): void {\n        if (!app.hasChannelOccupiedWebhooks) {\n            return;\n        }\n\n        this.send(app, {\n            name: App.CHANNEL_OCCUPIED_WEBHOOK,\n            channel,\n        }, 'channel_occupied_webhooks');\n    }\n\n    /**\n     * Send a cache_missed event.\n     */\n    public sendCacheMissed(app: App, channel: string): void {\n        if (!app.hasCacheMissedWebhooks) {\n            return;\n        }\n\n        this.send(app, {\n            name: App.CACHE_MISSED_WEBHOOK,\n            channel,\n        }, 'cache_miss_webhooks');\n    }\n\n    /**\n     * Send a webhook for the app with the given data.\n     */\n    protected send(app: App, data: ClientEventData, queueName: string): void {\n        if (this.server.options.webhooks.batching.enabled) {\n            this.sendWebhookByBatching(app, data, queueName);\n        } else {\n            this.sendWebhook(app, data, queueName)\n        }\n    }\n\n    /**\n     * Send a webhook for the app with the given data, without batching.\n     */\n    protected sendWebhook(app: App, data: ClientEventData|ClientEventData[], queueName: string): void {\n        let events = data instanceof Array ? data : [data];\n\n        if (events.length === 0) {\n            return;\n        }\n\n        // According to the Pusher docs: The time_ms key provides the unix timestamp in milliseconds when the webhook was created.\n        // So we set the time here instead of creating a new one in the queue handler so you can detect delayed webhooks when the queue is busy.\n        let time = (new Date).getTime();\n\n        let payload = {\n            time_ms: time,\n            events,\n        };\n\n        let originalPusherSignature = createWebhookHmac(JSON.stringify(payload), app.secret);\n\n        this.server.queueManager.addToQueue(queueName, {\n            appKey: app.key,\n            appId: app.id,\n            payload,\n            originalPusherSignature,\n        });\n    }\n\n    /**\n     * Send a webhook for the app with the given data, with batching enabled.\n     */\n    protected sendWebhookByBatching(app: App, data: ClientEventData, queueName: string): void {\n        this.batch.push(data);\n\n        // If there's no batch leader, elect itself as the batch leader, then wait an arbitrary time using\n        // setTimeout to build up a batch, before firing off the full batch of events in one webhook.\n        if (!this.batchHasLeader) {\n            this.batchHasLeader = true;\n\n            setTimeout(() => {\n                if (this.batch.length > 0) {\n                    this.sendWebhook(app, this.batch.splice(0, this.batch.length), queueName);\n                }\n\n                this.batchHasLeader = false;\n            }, this.server.options.webhooks.batching.duration);\n        }\n    }\n}\n"
  },
  {
    "path": "src/ws-handler.ts",
    "content": "import { App } from './app';\nimport async from 'async';\nimport { EncryptedPrivateChannelManager } from './channels';\nimport { HttpRequest, HttpResponse } from 'uWebSockets.js';\nimport { Log } from './log';\nimport { Namespace } from './namespace';\nimport { PresenceChannelManager } from './channels';\nimport { PresenceMemberInfo } from './channels/presence-channel-manager';\nimport { PrivateChannelManager } from './channels';\nimport { PublicChannelManager } from './channels';\nimport { PusherMessage, uWebSocketMessage } from './message';\nimport { Server } from './server';\nimport { Utils } from './utils';\nimport { WebSocket } from 'uWebSockets.js';\n\nconst ab2str = require('arraybuffer-to-string');\nconst Pusher = require('pusher');\n\nexport class WsHandler {\n    /**\n     * The manager for the public channels.\n     */\n    protected publicChannelManager: PublicChannelManager;\n\n    /**\n     * The manager for the private channels.\n     */\n    protected privateChannelManager: PrivateChannelManager;\n\n    /**\n     * The manager for the encrypted private channels.\n     */\n    protected encryptedPrivateChannelManager: EncryptedPrivateChannelManager;\n\n    /**\n     * The manager for the presence channels.\n     */\n    protected presenceChannelManager: PresenceChannelManager;\n\n    /**\n     * Initialize the Websocket connections handler.\n     */\n    constructor(protected server: Server) {\n        this.publicChannelManager = new PublicChannelManager(server);\n        this.privateChannelManager = new PrivateChannelManager(server);\n        this.encryptedPrivateChannelManager = new EncryptedPrivateChannelManager(server);\n        this.presenceChannelManager = new PresenceChannelManager(server);\n    }\n\n    /**\n     * Handle a new open connection.\n     */\n    onOpen(ws: WebSocket): any {\n        if (this.server.options.debug) {\n            Log.websocketTitle('👨‍🔬 New connection:');\n            Log.websocket({ ws });\n        }\n\n        ws.sendJson = (data) => {\n            try {\n                ws.send(JSON.stringify(data));\n\n                this.updateTimeout(ws);\n\n                if (ws.app) {\n                    this.server.metricsManager.markWsMessageSent(ws.app.id, data);\n                }\n\n                if (this.server.options.debug) {\n                    Log.websocketTitle('✈ Sent message to client:');\n                    Log.websocket({ ws, data });\n                }\n            } catch (e) {\n                //\n            }\n        }\n\n        ws.id = this.generateSocketId();\n        ws.subscribedChannels = new Set();\n        ws.presence = new Map<string, PresenceMemberInfo>();\n\n        if (this.server.closing) {\n            ws.sendJson({\n                event: 'pusher:error',\n                data: {\n                    code: 4200,\n                    message: 'Server is closing. Please reconnect shortly.',\n                },\n            });\n\n            return ws.end(4200);\n        }\n\n        this.checkForValidApp(ws).then(validApp => {\n            if (!validApp) {\n                ws.sendJson({\n                    event: 'pusher:error',\n                    data: {\n                        code: 4001,\n                        message: `App key ${ws.appKey} does not exist.`,\n                    },\n                });\n\n                return ws.end(4001);\n            }\n\n            ws.app = validApp.forWebSocket();\n\n            this.checkIfAppIsEnabled(ws).then(enabled => {\n                if (!enabled) {\n                    ws.sendJson({\n                        event: 'pusher:error',\n                        data: {\n                            code: 4003,\n                            message: 'The app is not enabled.',\n                        },\n                    });\n\n                    return ws.end(4003);\n                }\n\n                this.checkAppConnectionLimit(ws).then(canConnect => {\n                    if (!canConnect) {\n                        ws.sendJson({\n                            event: 'pusher:error',\n                            data: {\n                                code: 4100,\n                                message: 'The current concurrent connections quota has been reached.',\n                            },\n                        });\n\n                        ws.end(4100);\n                    } else {\n                        // Make sure to update the socket after new data was pushed in.\n                        this.server.adapter.addSocket(ws.app.id, ws);\n\n                        let broadcastMessage = {\n                            event: 'pusher:connection_established',\n                            data: JSON.stringify({\n                                socket_id: ws.id,\n                                activity_timeout: 30,\n                            }),\n                        };\n\n                        ws.sendJson(broadcastMessage);\n\n                        if (ws.app.enableUserAuthentication) {\n                            this.setUserAuthenticationTimeout(ws);\n                        }\n\n                        this.server.metricsManager.markNewConnection(ws);\n                    }\n                });\n            });\n        });\n    }\n\n    /**\n     * Handle a received message from the client.\n     */\n    onMessage(ws: WebSocket, message: uWebSocketMessage, isBinary: boolean): any {\n        if (message instanceof ArrayBuffer) {\n            try {\n                message = JSON.parse(ab2str(message)) as PusherMessage;\n            } catch (err) {\n                return;\n            }\n        }\n\n        if (this.server.options.debug) {\n            Log.websocketTitle('⚡ New message received:');\n            Log.websocket({ message, isBinary });\n        }\n\n        if (message) {\n            if (message.event === 'pusher:ping') {\n                this.handlePong(ws);\n            } else if (message.event === 'pusher:subscribe') {\n                this.subscribeToChannel(ws, message);\n            } else if (message.event === 'pusher:unsubscribe') {\n                this.unsubscribeFromChannel(ws, message.data.channel);\n            } else if (Utils.isClientEvent(message.event)) {\n                this.handleClientEvent(ws, message);\n            } else if (message.event === 'pusher:signin') {\n                this.handleSignin(ws, message);\n            } else {\n                Log.warning({\n                    info: 'Message event handler not implemented.',\n                    message,\n                });\n            }\n        }\n\n        if (ws.app) {\n            this.server.metricsManager.markWsMessageReceived(ws.app.id, message);\n        }\n    }\n\n    /**\n     * Handle the event of the client closing the connection.\n     */\n    onClose(ws: WebSocket, code: number, message: uWebSocketMessage): any {\n        if (this.server.options.debug) {\n            Log.websocketTitle('❌ Connection closed:');\n            Log.websocket({ ws, code, message });\n        }\n\n        // If code 4200 (reconnect immediately) is called, it means the `closeAllLocalSockets()` was called.\n        if (code !== 4200) {\n            this.evictSocketFromMemory(ws);\n        }\n    }\n\n    /**\n     * Evict the local socket.\n     */\n    evictSocketFromMemory(ws: WebSocket): Promise<void> {\n        return this.unsubscribeFromAllChannels(ws, true).then(() => {\n            if (ws.app) {\n                this.server.adapter.removeSocket(ws.app.id, ws.id);\n                this.server.metricsManager.markDisconnection(ws);\n            }\n\n            this.clearTimeout(ws);\n        });\n    }\n\n    /**\n     * Handle the event to close all existing sockets.\n     */\n    async closeAllLocalSockets(): Promise<void> {\n        let namespaces = this.server.adapter.getNamespaces();\n\n        if (namespaces.size === 0) {\n            return Promise.resolve();\n        }\n\n        return async.each([...namespaces], ([namespaceId, namespace]: [string, Namespace], nsCallback) => {\n            namespace.getSockets().then(sockets => {\n                async.each([...sockets], ([wsId, ws]: [string, WebSocket], wsCallback) => {\n                    try {\n                        ws.sendJson({\n                            event: 'pusher:error',\n                            data: {\n                                code: 4200,\n                                message: 'Server closed. Please reconnect shortly.',\n                            },\n                        });\n\n                        ws.end(4200);\n                    } catch (e) {\n                        //\n                    }\n\n                    this.evictSocketFromMemory(ws).then(() => {\n                        wsCallback();\n                    });\n                }).then(() => {\n                    this.server.adapter.clearNamespace(namespaceId).then(() => {\n                        nsCallback();\n                    });\n                });\n            });\n        }).then(() => {\n            // One last clear to make sure everything went away.\n            return this.server.adapter.clearNamespaces();\n        });\n    }\n\n    /**\n     * Mutate the upgrade request.\n     */\n    handleUpgrade(res: HttpResponse, req: HttpRequest, context): any {\n        res.upgrade(\n            {\n                ip: ab2str(res.getRemoteAddressAsText()),\n                ip2: ab2str(res.getProxiedRemoteAddressAsText()),\n                appKey: req.getParameter(0),\n            },\n            req.getHeader('sec-websocket-key'),\n            req.getHeader('sec-websocket-protocol'),\n            req.getHeader('sec-websocket-extensions'),\n            context,\n        );\n    }\n\n    /**\n     * Send back the pong response.\n     */\n    handlePong(ws: WebSocket): any {\n        ws.sendJson({\n            event: 'pusher:pong',\n            data: {},\n        });\n\n        if (this.server.closing) {\n            ws.sendJson({\n                event: 'pusher:error',\n                data: {\n                    code: 4200,\n                    message: 'Server closed. Please reconnect shortly.',\n                },\n            });\n\n            ws.end(4200);\n\n            this.evictSocketFromMemory(ws);\n        }\n    }\n\n    /**\n     * Instruct the server to subscribe the connection to the channel.\n     */\n    subscribeToChannel(ws: WebSocket, message: PusherMessage): any {\n        if (this.server.closing) {\n            ws.sendJson({\n                event: 'pusher:error',\n                data: {\n                    code: 4200,\n                    message: 'Server closed. Please reconnect shortly.',\n                },\n            });\n\n            ws.end(4200);\n\n            this.evictSocketFromMemory(ws);\n\n            return;\n        }\n\n        let channel = message.data.channel;\n        let channelManager = this.getChannelManagerFor(channel);\n\n        if (channel.length > ws.app.maxChannelNameLength) {\n            let broadcastMessage = {\n                event: 'pusher:subscription_error',\n                channel,\n                data: {\n                    type: 'LimitReached',\n                    error: `The channel name is longer than the allowed ${ws.app.maxChannelNameLength} characters.`,\n                    status: 4009,\n                },\n            };\n\n            ws.sendJson(broadcastMessage);\n\n            return;\n        }\n\n        channelManager.join(ws, channel, message).then((response) => {\n            if (!response.success) {\n                let { authError, type, errorMessage, errorCode } = response;\n\n                // For auth errors, send pusher:subscription_error\n                if (authError) {\n                    return ws.sendJson({\n                        event: 'pusher:subscription_error',\n                        channel,\n                        data: {\n                            type: 'AuthError',\n                            error: errorMessage,\n                            status: 401,\n                        },\n                    });\n                }\n\n                // Otherwise, catch any non-auth related errors.\n                return ws.sendJson({\n                    event: 'pusher:subscription_error',\n                    channel,\n                    data: {\n                        type: type,\n                        error: errorMessage,\n                        status: errorCode,\n                    },\n                });\n            }\n\n            if (!ws.subscribedChannels.has(channel)) {\n                ws.subscribedChannels.add(channel);\n            }\n\n            // Make sure to update the socket after new data was pushed in.\n            this.server.adapter.addSocket(ws.app.id, ws);\n\n            // If the connection freshly joined, send the webhook:\n            if (response.channelConnections === 1) {\n                this.server.webhookSender.sendChannelOccupied(ws.app, channel);\n            }\n\n            // For non-presence channels, end with subscription succeeded.\n            if (!(channelManager instanceof PresenceChannelManager)) {\n                let broadcastMessage = {\n                    event: 'pusher_internal:subscription_succeeded',\n                    channel,\n                };\n\n                ws.sendJson(broadcastMessage);\n\n                if (Utils.isCachingChannel(channel)) {\n                    this.sendMissedCacheIfExists(ws, channel);\n                }\n\n                return;\n            }\n\n            // Otherwise, prepare a response for the presence channel.\n            this.server.adapter.getChannelMembers(ws.app.id, channel, false).then(members => {\n                let { user_id, user_info } = response.member;\n\n                ws.presence.set(channel, response.member);\n\n                // Make sure to update the socket after new data was pushed in.\n                this.server.adapter.addSocket(ws.app.id, ws);\n\n                // If the member already exists in the channel, don't resend the member_added event.\n                if (!members.has(user_id as string)) {\n                    this.server.webhookSender.sendMemberAdded(ws.app, channel, user_id as string);\n\n                    this.server.adapter.send(ws.app.id, channel, JSON.stringify({\n                        event: 'pusher_internal:member_added',\n                        channel,\n                        data: JSON.stringify({\n                            user_id: user_id,\n                            user_info: user_info,\n                        }),\n                    }), ws.id);\n\n                    members.set(user_id as string, user_info);\n                }\n\n                let broadcastMessage = {\n                    event: 'pusher_internal:subscription_succeeded',\n                    channel,\n                    data: JSON.stringify({\n                        presence: {\n                            ids: Array.from(members.keys()),\n                            hash: Object.fromEntries(members),\n                            count: members.size,\n                        },\n                    }),\n                };\n\n                ws.sendJson(broadcastMessage);\n\n                if (Utils.isCachingChannel(channel)) {\n                    this.sendMissedCacheIfExists(ws, channel);\n                }\n            }).catch(err => {\n                Log.error(err);\n\n                ws.sendJson({\n                    event: 'pusher:error',\n                    channel,\n                    data: {\n                        type: 'ServerError',\n                        error: 'A server error has occured.',\n                        code: 4302,\n                    },\n                });\n            });\n        });\n    }\n\n    /**\n     * Instruct the server to unsubscribe the connection from the channel.\n     */\n    unsubscribeFromChannel(ws: WebSocket, channel: string, closing = false): Promise<void> {\n        let channelManager = this.getChannelManagerFor(channel);\n\n        return channelManager.leave(ws, channel).then(response => {\n            let member = ws.presence.get(channel);\n\n            if (response.left) {\n                // Send presence channel-speific events and delete specific data.\n                // This can happen only if the user is connected to the presence channel.\n                if (channelManager instanceof PresenceChannelManager && ws.presence.has(channel)) {\n                    ws.presence.delete(channel);\n\n                    // Make sure to update the socket after new data was pushed in.\n                    this.server.adapter.addSocket(ws.app.id, ws);\n\n                    this.server.adapter.getChannelMembers(ws.app.id, channel, false).then(members => {\n                        if (!members.has(member.user_id as string)) {\n                            this.server.webhookSender.sendMemberRemoved(ws.app, channel, member.user_id);\n\n                            this.server.adapter.send(ws.app.id, channel, JSON.stringify({\n                                event: 'pusher_internal:member_removed',\n                                channel,\n                                data: JSON.stringify({\n                                    user_id: member.user_id,\n                                }),\n                            }), ws.id);\n                        }\n                    });\n                }\n\n                ws.subscribedChannels.delete(channel);\n\n                // Make sure to update the socket after new data was pushed in,\n                // but only if the user is not closing the connection.\n                if (!closing) {\n                    this.server.adapter.addSocket(ws.app.id, ws);\n                }\n\n                if (response.remainingConnections === 0) {\n                    this.server.webhookSender.sendChannelVacated(ws.app, channel);\n                }\n            }\n\n            // ws.send(JSON.stringify({\n            //     event: 'pusher_internal:unsubscribed',\n            //     channel,\n            // }));\n\n            return;\n        });\n    }\n\n    /**\n     * Unsubscribe the connection from all channels.\n     */\n    unsubscribeFromAllChannels(ws: WebSocket, closing = true): Promise<void> {\n        if (!ws.subscribedChannels) {\n            return Promise.resolve();\n        }\n\n        return Promise.all([\n            async.each(ws.subscribedChannels, (channel, callback) => {\n                this.unsubscribeFromChannel(ws, channel, closing).then(() => callback());\n            }),\n            ws.app && ws.user ? this.server.adapter.removeUser(ws) : new Promise<void>(resolve => resolve()),\n        ]).then(() => {\n            return;\n        })\n    }\n\n    /**\n     * Handle the events coming from the client.\n     */\n    handleClientEvent(ws: WebSocket, message: PusherMessage): any {\n        let { event, data, channel } = message;\n\n        if (!ws.app.enableClientMessages) {\n            return ws.sendJson({\n                event: 'pusher:error',\n                channel,\n                data: {\n                    code: 4301,\n                    message: `The app does not have client messaging enabled.`,\n                },\n            });\n        }\n\n        // Make sure the event name length is not too big.\n        if (event.length > ws.app.maxEventNameLength) {\n            let broadcastMessage = {\n                event: 'pusher:error',\n                channel,\n                data: {\n                    code: 4301,\n                    message: `Event name is too long. Maximum allowed size is ${ws.app.maxEventNameLength}.`,\n                },\n            };\n\n            ws.sendJson(broadcastMessage);\n\n            return;\n        }\n\n        let payloadSizeInKb = Utils.dataToKilobytes(message.data);\n\n        // Make sure the total payload of the message body is not too big.\n        if (payloadSizeInKb > parseFloat(ws.app.maxEventPayloadInKb as string)) {\n            let broadcastMessage = {\n                event: 'pusher:error',\n                channel,\n                data: {\n                    code: 4301,\n                    message: `The event data should be less than ${ws.app.maxEventPayloadInKb} KB.`,\n                },\n            };\n\n            ws.sendJson(broadcastMessage);\n\n            return;\n        }\n\n        this.server.adapter.isInChannel(ws.app.id, channel, ws.id).then(canBroadcast => {\n            if (!canBroadcast) {\n                return;\n            }\n\n            this.server.rateLimiter.consumeFrontendEventPoints(1, ws.app, ws).then(response => {\n                if (response.canContinue) {\n                    let userId = ws.presence.has(channel) ? ws.presence.get(channel).user_id : null;\n\n                    let message = JSON.stringify({\n                        event,\n                        channel,\n                        data,\n                        ...userId ? { user_id: userId } : {},\n                    });\n\n                    this.server.adapter.send(ws.app.id, channel, message, ws.id);\n\n                    this.server.webhookSender.sendClientEvent(\n                        ws.app, channel, event, data, ws.id, userId,\n                    );\n\n                    return;\n                }\n\n                ws.sendJson({\n                    event: 'pusher:error',\n                    channel,\n                    data: {\n                        code: 4301,\n                        message: 'The rate limit for sending client events exceeded the quota.',\n                    },\n                });\n            });\n        });\n    }\n\n    /**\n     * Handle the signin coming from the frontend.\n     */\n    handleSignin(ws: WebSocket, message: PusherMessage): void {\n        if (!ws.userAuthenticationTimeout) {\n            return;\n        }\n\n        this.signinTokenIsValid(ws, message.data.user_data, message.data.auth).then(isValid => {\n            if (!isValid) {\n                ws.sendJson({\n                    event: 'pusher:error',\n                    data: {\n                        code: 4009,\n                        message: 'Connection not authorized.',\n                    },\n                });\n\n                try {\n                    ws.end(4009);\n                } catch (e) {\n                    //\n                }\n\n                return;\n            }\n\n            let decodedUser = JSON.parse(message.data.user_data);\n\n            if (!decodedUser.id) {\n                ws.sendJson({\n                    event: 'pusher:error',\n                    data: {\n                        code: 4009,\n                        message: 'The returned user data must contain the \"id\" field.',\n                    },\n                });\n\n                try {\n                    ws.end(4009);\n                } catch (e) {\n                    //\n                }\n\n                return;\n            }\n\n            ws.user = {\n                ...decodedUser,\n                ...{\n                    id: decodedUser.id.toString(),\n                },\n            };\n\n            if (ws.userAuthenticationTimeout) {\n                clearTimeout(ws.userAuthenticationTimeout);\n            }\n\n            this.server.adapter.addSocket(ws.app.id, ws);\n\n            this.server.adapter.addUser(ws).then(() => {\n                ws.sendJson({\n                    event: 'pusher:signin_success',\n                    data: message.data,\n                });\n            });\n        });\n    }\n\n    /**\n     * Send the first event as cache_missed, if it exists, to catch up.\n     */\n    sendMissedCacheIfExists(ws: WebSocket, channel: string) {\n        this.server.cacheManager.get(`app:${ws.app.id}:channel:${channel}:cache_miss`).then(cachedEvent => {\n            if (cachedEvent) {\n                let { event, data } = JSON.parse(cachedEvent);\n                ws.sendJson({ event: event, channel, data: data });\n            } else {\n                ws.sendJson({ event: 'pusher:cache_miss', channel });\n                this.server.webhookSender.sendCacheMissed(ws.app, channel);\n            }\n        });\n    }\n\n    /**\n     * Get the channel manager for the given channel name,\n     * respecting the Pusher protocol.\n     */\n    getChannelManagerFor(channel: string): PublicChannelManager|PrivateChannelManager|EncryptedPrivateChannelManager|PresenceChannelManager {\n        if (Utils.isPresenceChannel(channel)) {\n            return this.presenceChannelManager;\n        } else if (Utils.isEncryptedPrivateChannel(channel)) {\n            return this.encryptedPrivateChannelManager;\n        } else if (Utils.isPrivateChannel(channel)) {\n            return this.privateChannelManager;\n        } else {\n            return this.publicChannelManager;\n        }\n    }\n\n    /**\n     * Use the app manager to retrieve a valid app.\n     */\n    protected checkForValidApp(ws: WebSocket): Promise<App|null> {\n        return this.server.appManager.findByKey(ws.appKey);\n    }\n\n    /**\n     * Make sure that the app is enabled.\n     */\n    protected checkIfAppIsEnabled(ws: WebSocket): Promise<boolean> {\n        return Promise.resolve(ws.app.enabled);\n    }\n\n    /**\n     * Make sure the connection limit is not reached with this connection.\n     * Return a boolean wether the user can connect or not.\n     */\n    protected checkAppConnectionLimit(ws: WebSocket): Promise<boolean> {\n        return this.server.adapter.getSocketsCount(ws.app.id).then(wsCount => {\n            let maxConnections = parseInt(ws.app.maxConnections as string) || -1;\n\n            if (maxConnections < 0) {\n                return true;\n            }\n\n            return wsCount + 1 <= maxConnections;\n        }).catch(err => {\n            Log.error(err);\n            return false;\n        });\n    }\n\n    /**\n     * Check is an incoming connection can subscribe.\n     */\n    signinTokenIsValid(ws: WebSocket, userData: string, signatureToCheck: string): Promise<boolean> {\n        return this.signinTokenForUserData(ws, userData).then(expectedSignature => {\n            return signatureToCheck === expectedSignature;\n        });\n    }\n\n    /**\n     * Get the signin token from the given message, by the Socket.\n     */\n    protected signinTokenForUserData(ws: WebSocket, userData: string): Promise<string> {\n        return new Promise(resolve => {\n            let decodedString = `${ws.id}::user::${userData}`;\n            let token = new Pusher.Token(ws.app.key, ws.app.secret);\n\n            resolve(\n                ws.app.key + ':' + token.sign(decodedString)\n            );\n        });\n    }\n\n    /**\n     * Generate a Pusher-like Socket ID.\n     */\n    protected generateSocketId(): string {\n        let min = 0;\n        let max = 10000000000;\n\n        let randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);\n\n        return randomNumber(min, max) + '.' + randomNumber(min, max);\n    }\n\n    /**\n     * Clear WebSocket timeout.\n     */\n    protected clearTimeout(ws: WebSocket): void {\n        if (ws.timeout) {\n            clearTimeout(ws.timeout);\n        }\n    }\n\n    /**\n     * Update WebSocket timeout.\n     */\n    protected updateTimeout(ws: WebSocket): void {\n        this.clearTimeout(ws);\n\n        ws.timeout = setTimeout(() => {\n            try {\n                ws.end(4201);\n            } catch (e) {\n                //\n            }\n        }, 120_000);\n    }\n\n    /**\n     * Set the authentication timeout for the socket.\n     */\n    protected setUserAuthenticationTimeout(ws: WebSocket): void {\n        ws.userAuthenticationTimeout = setTimeout(() => {\n            ws.sendJson({\n                event: 'pusher:error',\n                data: {\n                    code: 4009,\n                    message: 'Connection not authorized within timeout.',\n                },\n            });\n\n            try {\n                ws.end(4009);\n            } catch (e) {\n                //\n            }\n        }, this.server.options.userAuthenticationTimeout);\n    }\n}\n"
  },
  {
    "path": "tests/encrypted-private.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('private-encrypted channel test', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    test('connects to private-encrypted channel', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClientForEncryptedPrivateChannel();\n            let backend = Utils.newBackend();\n            let channelName = `private-encrypted-${Utils.randomChannelName()}`;\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', e => {\n                    expect(e.message).toBe('hello');\n                    client.disconnect();\n                    done();\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.trigger(channelName, 'greeting', { message: 'hello' })\n                        .catch(error => {\n                            throw new Error(error);\n                        });\n                });\n            });\n        });\n    });\n\n    test('cannot connect to private-encrypted channel with wrong authentication', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClientForEncryptedPrivateChannel({\n                authorizer: (channel, options) => ({\n                    authorize: (socketId, callback) => {\n                        callback(false, {\n                            auth: 'incorrect_token',\n                            channel_data: null,\n                            shared_secret: Utils.newBackend().channelSharedSecret(channel.name).toString('base64'),\n                        });\n                    },\n                }),\n            });\n\n            let channelName = `private-encrypted-${Utils.randomChannelName()}`;\n\n            client.connection.bind('message', ({ event, channel, data }) => {\n                if (event === 'pusher:subscription_error' && channel === channelName) {\n                    expect(data.type).toBe('AuthError');\n                    expect(data.status).toBe(401);\n                    client.disconnect();\n                    done();\n                }\n            });\n\n            client.connection.bind('connected', () => {\n                client.subscribe(channelName);\n            });\n        });\n    });\n\n    test('connects and disconnects to private-encrypted channel and does not leak memory', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClientForEncryptedPrivateChannel();\n            let backend = Utils.newBackend();\n            let channelName = `private-encrypted-${Utils.randomChannelName()}`;\n\n            client.connection.bind('disconnected', () => {\n                Utils.wait(3000).then(() => {\n                    let namespace = server.adapter.getNamespace('app-id');\n\n                    expect(namespace.sockets.size).toBe(0);\n                    expect(namespace.channels.size).toBe(0);\n                    done();\n                });\n            });\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', e => {\n                    expect(e.message).toBe('hello');\n\n                    client.unsubscribe(channelName);\n\n                    Utils.wait(3000).then(() => {\n                        let namespace = server.adapter.getNamespace('app-id');\n                        let socket = namespace.sockets.get(namespace.sockets.keys().next().value);\n\n                        expect(namespace.channels.size).toBe(0);\n                        expect(namespace.sockets.size).toBe(1);\n                        expect(socket.subscribedChannels.size).toBe(0);\n                        expect(socket.presence.size).toBe(0);\n\n                        client.disconnect();\n                    });\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.trigger(channelName, 'greeting', { message: 'hello' });\n                });\n            });\n        });\n    });\n\n    test('sudden close connection in private-encrypted channel and does not leak memory', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClientForEncryptedPrivateChannel();\n            let backend = Utils.newBackend();\n            let channelName = `private-encrypted-${Utils.randomChannelName()}`;\n\n            client.connection.bind('disconnected', () => {\n                Utils.wait(3000).then(() => {\n                    let namespace = server.adapter.getNamespace('app-id');\n\n                    expect(namespace.sockets.size).toBe(0);\n                    expect(namespace.channels.size).toBe(0);\n                    done();\n                });\n            });\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', e => {\n                    expect(e.message).toBe('hello');\n                    client.disconnect();\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.trigger(channelName, 'greeting', { message: 'hello' });\n                });\n            });\n        });\n    });\n\n    test('cached private-encrypted channels work', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client1 = Utils.newClientForEncryptedPrivateChannel();\n            let backend = Utils.newBackend();\n            let channelName = `private-encrypted-cache-${Utils.randomChannelName()}`;\n\n            client1.connection.bind('connected', () => {\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    channel.bind('pusher:cache_miss', (data) => {\n                        expect(data).toBe(undefined);\n\n                        channel.bind('greeting', e => {\n                            expect(e.message).toBe('hello');\n    \n                            let client2 = Utils.newClientForEncryptedPrivateChannel();\n    \n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:cache_miss', () => {\n                                    throw new Error('Did not expect cache_miss to be invoked.');\n                                });\n\n                                channel.bind('greeting', e => {\n                                    expect(e.message).toBe('hello');\n                                    done()\n                                })\n                            });\n                        });\n                    });\n\n                    backend.trigger(channelName, 'greeting', { message: 'hello' }).catch(error => {\n                        throw new Error(error);\n                    });\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/fixtures/dynamodb_schema.js",
    "content": "const AWS = require('aws-sdk');\n\nlet ddb = new AWS.DynamoDB({\n    apiVersion: '2012-08-10',\n    region: 'us-east-1',\n    endpoint: `http://${process.env.DYNAMODB_URL || '127.0.0.1:8000'}`,\n});\n\nlet createRecord = () => {\n    const params = {\n        TableName: 'apps',\n        Item: {\n            AppId: { S: 'app-id' },\n            AppKey: { S: 'app-key' },\n            AppSecret: { S: 'app-secret' },\n            MaxConnections: { N: '-1' },\n            EnableClientMessages: { B: 'false' },\n            Enabled: { B: 'true' },\n            MaxBackendEventsPerSecond: { N: '-1' },\n            MaxClientEventsPerSecond: { N: '-1' },\n            MaxReadRequestsPerSecond: { N: '-1' },\n            Webhooks: { S: '[]', },\n\n            /**\n             * The following fields are optional. It's not a problem, because DynamoDB is NoSQL.\n             * If one of the following fields doesn't exist,\n             * the default ones defined at the server-level will take priority.\n             */\n            // MaxPresenceMembersPerChannel: { N: '-1' },\n            // MaxPresenceMemberSizeInKb: { N: '-1' },\n            // MaxChannelNameLength: { N: '-1' },\n            // MaxEventChannelsAtOnce: { N: '-1' },\n            // MaxEventNameLength: { N: '-1' },\n            // MaxEventPayloadInKb: { N: '-1' },\n            // MaxEventBatchSize: { N: '-1' },\n            // EnableUserAuthentication: { B: 'false' }\n        },\n    };\n\n    return ddb.putItem(params).promise().then(() => {\n        console.log('Record created.');\n    }).catch(err => {\n        console.error(err);\n        console.log('Record already existent.');\n    });\n};\n\nddb.describeTable({ TableName: 'apps' }).promise().then((result) => {\n    createRecord();\n}).catch(err => {\n    console.error(err);\n\n    ddb.createTable({\n        TableName: 'apps',\n        AttributeDefinitions: [\n            {\n                AttributeName: 'AppId',\n                AttributeType: 'S',\n            },\n            {\n                AttributeName: 'AppKey',\n                AttributeType: 'S',\n            },\n        ],\n        KeySchema: [{\n            AttributeName: 'AppId',\n            KeyType: 'HASH',\n        }],\n        GlobalSecondaryIndexes: [{\n            IndexName: 'AppKeyIndex',\n            KeySchema: [{\n                AttributeName: 'AppKey',\n                KeyType: 'HASH',\n            }],\n            Projection: {\n                ProjectionType: 'ALL',\n            },\n            ProvisionedThroughput: {\n                ReadCapacityUnits: 100,\n                WriteCapacityUnits: 100,\n            },\n        }],\n        StreamSpecification: {\n            StreamEnabled: false,\n        },\n        ProvisionedThroughput: {\n            ReadCapacityUnits: 100,\n            WriteCapacityUnits: 100,\n        },\n    }).promise().then(() => {\n        console.log('Table created.');\n    }).then(createRecord).catch((err) => {\n        console.error(err);\n        console.log('Table already existent.');\n    });\n});\n"
  },
  {
    "path": "tests/fixtures/mysql_schema.sql",
    "content": "CREATE TABLE IF NOT EXISTS `apps` (\n    `id` varchar(255) NOT NULL,\n    `key` varchar(255) NOT NULL,\n    `secret` varchar(255) NOT NULL,\n    `max_connections` integer(10) NOT NULL,\n    `enabled` tinyint(1) NOT NULL,\n    `enable_client_messages` tinyint(1) NOT NULL,\n    `max_backend_events_per_sec` integer(10) NOT NULL,\n    `max_client_events_per_sec` integer(10) NOT NULL,\n    `max_read_req_per_sec` integer(10) NOT NULL,\n    `webhooks` json,\n    `max_presence_members_per_channel` tinyint(1) NULL,\n    `max_presence_member_size_in_kb` tinyint(1) NULL,\n    `max_channel_name_length` tinyint(1) NULL,\n    `max_event_channels_at_once` tinyint(1) NULL,\n    `max_event_name_length` tinyint(1) NULL,\n    `max_event_payload_in_kb` tinyint(1) NULL,\n    `max_event_batch_size` tinyint(1) NULL,\n    `enable_user_authentication` tinyint(1) NOT NULL,\n    PRIMARY KEY (`id`)\n);\n\nINSERT INTO apps (\n    id,\n    `key`,\n    secret,\n    max_connections,\n    `enabled`,\n    enable_client_messages,\n    max_backend_events_per_sec,\n    max_client_events_per_sec,\n    max_read_req_per_sec,\n    webhooks,\n    max_presence_members_per_channel,\n    max_presence_member_size_in_kb,\n    max_channel_name_length,\n    max_event_channels_at_once,\n    max_event_name_length,\n    max_event_payload_in_kb,\n    max_event_batch_size,\n    enable_user_authentication\n) VALUES (\n    'app-id',\n    'app-key',\n    'app-secret',\n    200,\n    1,\n    1,\n    -1,\n    -1,\n    -1,\n    '[]',\n    null,\n    null,\n    null,\n    null,\n    null,\n    null,\n    null,\n    0\n);\n"
  },
  {
    "path": "tests/fixtures/postgres_schema.sql",
    "content": "CREATE TABLE IF NOT EXISTS apps (\n    id varchar(255) PRIMARY KEY,\n    \"key\" varchar(255) NOT NULL,\n    secret varchar(255) NOT NULL,\n    max_connections integer NOT NULL,\n    enable_client_messages smallint NOT NULL,\n    \"enabled\" smallint NOT NULL,\n    max_backend_events_per_sec integer NOT NULL,\n    max_client_events_per_sec integer NOT NULL,\n    max_read_req_per_sec integer NOT NULL,\n    webhooks json,\n    max_presence_members_per_channel integer DEFAULT NULL,\n    max_presence_member_size_in_kb integer DEFAULT NULL,\n    max_channel_name_length integer DEFAULT NULL,\n    max_event_channels_at_once integer DEFAULT NULL,\n    max_event_name_length integer DEFAULT NULL,\n    max_event_payload_in_kb integer DEFAULT NULL,\n    max_event_batch_size integer DEFAULT NULL,\n    enable_user_authentication smallint NOT NULL\n);\n\nINSERT INTO apps (\n    id,\n    \"key\",\n    secret,\n    max_connections,\n    \"enabled\",\n    enable_client_messages,\n    max_backend_events_per_sec,\n    max_client_events_per_sec,\n    max_read_req_per_sec,\n    webhooks,\n    max_presence_members_per_channel,\n    max_presence_member_size_in_kb,\n    max_channel_name_length,\n    max_event_channels_at_once,\n    max_event_name_length,\n    max_event_payload_in_kb,\n    max_event_batch_size,\n    enable_user_authentication\n) VALUES (\n    'app-id',\n    'app-key',\n    'app-secret',\n    200,\n    1,\n    1,\n    -1,\n    -1,\n    -1,\n    '[]',\n    null,\n    null,\n    null,\n    null,\n    null,\n    null,\n    null,\n    0\n);\n"
  },
  {
    "path": "tests/fixtures/sqs.json",
    "content": "{\n  \"FifoQueue\": \"true\",\n  \"ContentBasedDeduplication\": \"true\",\n  \"DeduplicationScope\": \"messageGroup\",\n  \"FifoThroughputLimit\": \"perMessageGroupId\",\n  \"MessageRetentionPeriod\": \"3600\",\n  \"ReceiveMessageWaitTimeSeconds\": \"1\",\n  \"VisibilityTimeout\": \"5\"\n}\n"
  },
  {
    "path": "tests/http-api.cluster-adapter.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('http api test for cluster adapter', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster'))('get api channels with cluster adapter', done => {\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient();\n                let backend = Utils.newBackend();\n                let channelName = Utils.randomChannelName();\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                            expect(body.channels[channelName]).toBeDefined();\n                            expect(body.channels[channelName].subscription_count).toBe(1);\n                            expect(body.channels[channelName].occupied).toBe(true);\n\n                            let client2 = Utils.newClient({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                                        expect(body.channels[channelName]).toBeDefined();\n                                        expect(body.channels[channelName].subscription_count).toBe(2);\n                                        expect(body.channels[channelName].occupied).toBe(true);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                                                // TODO: Expect\n                                                // expect(body.channels[channelName]).toBeUndefined();\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster'))('get api channel with cluster adapter', done => {\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient();\n                let backend = Utils.newBackend();\n                let channelName = Utils.randomChannelName();\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                            expect(body.subscription_count).toBe(1);\n                            expect(body.occupied).toBe(true);\n\n                            let client2 = Utils.newClient();\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                        expect(body.subscription_count).toBe(2);\n                                        expect(body.occupied).toBe(true);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                                expect(body.subscription_count).toBe(0);\n                                                expect(body.occupied).toBe(false);\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster'))('get api presence channel with cluster adapter', done => {\n        let user1 = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        let user2 = {\n            user_id: 2,\n            user_info: {\n                id: 2,\n                name: 'Alice',\n            },\n        };\n\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPresenceUser(user1);\n                let backend = Utils.newBackend();\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                            expect(body.subscription_count).toBe(1);\n                            expect(body.occupied).toBe(true);\n\n                            let client2 = Utils.newClientForPresenceUser(user2, {}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                        expect(body.subscription_count).toBe(2);\n                                        expect(body.user_count).toBe(2);\n                                        expect(body.occupied).toBe(true);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                                expect(body.subscription_count).toBe(0);\n                                                expect(body.user_count).toBe(0);\n                                                expect(body.occupied).toBe(false);\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster'))('get api presence users with cluster adapter', done => {\n        let user1 = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        let user2 = {\n            user_id: 2,\n            user_info: {\n                id: 2,\n                name: 'Alice',\n            },\n        };\n\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPresenceUser(user1);\n                let backend = Utils.newBackend();\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                            expect(body.users.length).toBe(1);\n\n                            let client2 = Utils.newClientForPresenceUser(user2, {}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                        expect(body.users.length).toBe(2);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                                expect(body.users.length).toBe(0);\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster'))('presence channel users should count only once for same-user multiple connections with cluster adapter', done => {\n        let user = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPresenceUser(user);\n                let backend = Utils.newBackend();\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                            expect(body.users.length).toBe(1);\n\n                            let client2 = Utils.newClientForPresenceUser(user, {}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                        expect(body.users.length).toBe(1);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                                expect(body.users.length).toBe(0);\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('signin after connection with termination call for cluster', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002, 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 });\n                let client2;\n                let backend = Utils.newBackend();\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', (payload) => {\n                        if (payload.event === 'pusher:error' && payload.data.code === 4009) {\n                            client1.disconnect();\n                            client2.disconnect();\n                            done();\n                        }\n\n                        if (payload.event === 'pusher:signin_success') {\n                            client2 = Utils.newClientForPrivateChannel({}, 6002, 'app-key', { id: 2 });\n\n                            client2.connection.bind('connected', () => {\n                                client2.connection.bind('message', (payload) => {\n                                    if (payload.event === 'pusher:signin_success') {\n                                        backend.terminateUserConnections('1');\n                                    }\n                                });\n\n                                client2.signin();\n                            });\n                        }\n                    });\n\n                    client1.signin();\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('broadcast to user for cluster', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'port': 6002, 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 });\n                let client2;\n                let backend = Utils.newBackend();\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', (message) => {\n                        if (message.event === 'pusher:signin_success') {\n                            client2 = Utils.newClientForPrivateChannel({}, 6002, 'app-key', { id: 2 });\n\n                            client2.connection.bind('connected', () => {\n                                client2.connection.bind('message', (payload) => {\n                                    if (payload.event === 'pusher:signin_success') {\n                                        backend.sendToUser('1', 'my-event', { works: true });\n                                    }\n                                });\n\n                                client2.signin();\n                            });\n                        }\n\n                        if (message.event === 'my-event') {\n                            client1.disconnect();\n                            client2.disconnect();\n                            done();\n                        }\n                    });\n\n                    client1.signin();\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/http-api.nats-adapter.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('http api test for nats adapter', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats'))('get api channels with nats adapter', done => {\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient();\n                let backend = Utils.newBackend();\n                let channelName = Utils.randomChannelName();\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                            expect(body.channels[channelName]).toBeDefined();\n                            expect(body.channels[channelName].subscription_count).toBe(1);\n                            expect(body.channels[channelName].occupied).toBe(true);\n\n                            let client2 = Utils.newClient({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                                        expect(body.channels[channelName]).toBeDefined();\n                                        expect(body.channels[channelName].subscription_count).toBe(2);\n                                        expect(body.channels[channelName].occupied).toBe(true);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                                                // TODO: Expect\n                                                // expect(body.channels[channelName]).toBeUndefined();\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats'))('get api channel with nats adapter', done => {\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient();\n                let backend = Utils.newBackend();\n                let channelName = Utils.randomChannelName();\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                            expect(body.subscription_count).toBe(1);\n                            expect(body.occupied).toBe(true);\n\n                            let client2 = Utils.newClient();\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                        expect(body.subscription_count).toBe(2);\n                                        expect(body.occupied).toBe(true);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                                expect(body.subscription_count).toBe(0);\n                                                expect(body.occupied).toBe(false);\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats'))('get api presence channel with nats adapter', done => {\n        let user1 = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        let user2 = {\n            user_id: 2,\n            user_info: {\n                id: 2,\n                name: 'Alice',\n            },\n        };\n\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPresenceUser(user1);\n                let backend = Utils.newBackend();\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                            expect(body.subscription_count).toBe(1);\n                            expect(body.occupied).toBe(true);\n\n                            let client2 = Utils.newClientForPresenceUser(user2, {}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                        expect(body.subscription_count).toBe(2);\n                                        expect(body.user_count).toBe(2);\n                                        expect(body.occupied).toBe(true);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                                expect(body.subscription_count).toBe(0);\n                                                expect(body.user_count).toBe(0);\n                                                expect(body.occupied).toBe(false);\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats'))('get api presence users with nats adapter', done => {\n        let user1 = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        let user2 = {\n            user_id: 2,\n            user_info: {\n                id: 2,\n                name: 'Alice',\n            },\n        };\n\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPresenceUser(user1);\n                let backend = Utils.newBackend();\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                            expect(body.users.length).toBe(1);\n\n                            let client2 = Utils.newClientForPresenceUser(user2, {}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                        expect(body.users.length).toBe(2);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                                expect(body.users.length).toBe(0);\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats'))('presence channel users should count only once for same-user multiple connections with nats adapter', done => {\n        let user = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPresenceUser(user);\n                let backend = Utils.newBackend();\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                            expect(body.users.length).toBe(1);\n\n                            let client2 = Utils.newClientForPresenceUser(user, {}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                        expect(body.users.length).toBe(1);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                                expect(body.users.length).toBe(0);\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('signin after connection with termination call for nats', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002, 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 });\n                let client2;\n                let backend = Utils.newBackend();\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', (payload) => {\n                        if (payload.event === 'pusher:error' && payload.data.code === 4009) {\n                            client1.disconnect();\n                            client2.disconnect();\n                            done();\n                        }\n\n                        if (payload.event === 'pusher:signin_success') {\n                            client2 = Utils.newClientForPrivateChannel({}, 6002, 'app-key', { id: 2 });\n\n                            client2.connection.bind('connected', () => {\n                                client2.connection.bind('message', (payload) => {\n                                    if (payload.event === 'pusher:signin_success') {\n                                        backend.terminateUserConnections('1');\n                                    }\n                                });\n\n                                client2.signin();\n                            });\n                        }\n                    });\n\n                    client1.signin();\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('broadcast to user for nats', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'port': 6002, 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 });\n                let client2;\n                let backend = Utils.newBackend();\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', (message) => {\n                        if (message.event === 'pusher:signin_success') {\n                            client2 = Utils.newClientForPrivateChannel({}, 6002, 'app-key', { id: 2 });\n\n                            client2.connection.bind('connected', () => {\n                                client2.connection.bind('message', (payload) => {\n                                    if (payload.event === 'pusher:signin_success') {\n                                        backend.sendToUser('1', 'my-event', { works: true });\n                                    }\n                                });\n\n                                client2.signin();\n                            });\n                        }\n\n                        if (message.event === 'my-event') {\n                            client1.disconnect();\n                            client2.disconnect();\n                            done();\n                        }\n                    });\n\n                    client1.signin();\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/http-api.redis-adapter.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('http api test for redis adapter', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis'))('get api channels with redis adapter', done => {\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient();\n                let backend = Utils.newBackend();\n                let channelName = Utils.randomChannelName();\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                            expect(body.channels[channelName]).toBeDefined();\n                            expect(body.channels[channelName].subscription_count).toBe(1);\n                            expect(body.channels[channelName].occupied).toBe(true);\n\n                            let client2 = Utils.newClient({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                                        expect(body.channels[channelName]).toBeDefined();\n                                        expect(body.channels[channelName].subscription_count).toBe(2);\n                                        expect(body.channels[channelName].occupied).toBe(true);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                                                // TODO: Expect\n                                                // expect(body.channels[channelName]).toBeUndefined();\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis'))('get api channel with redis adapter', done => {\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient();\n                let backend = Utils.newBackend();\n                let channelName = Utils.randomChannelName();\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                            expect(body.subscription_count).toBe(1);\n                            expect(body.occupied).toBe(true);\n\n                            let client2 = Utils.newClient();\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                        expect(body.subscription_count).toBe(2);\n                                        expect(body.occupied).toBe(true);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                                expect(body.subscription_count).toBe(0);\n                                                expect(body.occupied).toBe(false);\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis'))('get api presence channel with redis adapter', done => {\n        let user1 = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        let user2 = {\n            user_id: 2,\n            user_info: {\n                id: 2,\n                name: 'Alice',\n            },\n        };\n\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPresenceUser(user1);\n                let backend = Utils.newBackend();\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                            expect(body.subscription_count).toBe(1);\n                            expect(body.occupied).toBe(true);\n\n                            let client2 = Utils.newClientForPresenceUser(user2, {}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                        expect(body.subscription_count).toBe(2);\n                                        expect(body.user_count).toBe(2);\n                                        expect(body.occupied).toBe(true);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                                expect(body.subscription_count).toBe(0);\n                                                expect(body.user_count).toBe(0);\n                                                expect(body.occupied).toBe(false);\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis'))('get api presence users with redis adapter', done => {\n        let user1 = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        let user2 = {\n            user_id: 2,\n            user_info: {\n                id: 2,\n                name: 'Alice',\n            },\n        };\n\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPresenceUser(user1);\n                let backend = Utils.newBackend();\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                            expect(body.users.length).toBe(1);\n\n                            let client2 = Utils.newClientForPresenceUser(user2, {}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                        expect(body.users.length).toBe(2);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                                expect(body.users.length).toBe(0);\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis'))('presence channel users should count only once for same-user multiple connections with redis adapter', done => {\n        let user = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPresenceUser(user);\n                let backend = Utils.newBackend();\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                            expect(body.users.length).toBe(1);\n\n                            let client2 = Utils.newClientForPresenceUser(user, {}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                        expect(body.users.length).toBe(1);\n\n                                        client1.connection.bind('disconnected', () => {\n                                            client2.disconnect();\n                                        });\n\n                                        client2.connection.bind('disconnected', () => {\n                                            backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                                expect(body.users.length).toBe(0);\n                                                done();\n                                            });\n                                        });\n\n                                        client1.disconnect();\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('signin after connection with termination call for redis', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002, 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 });\n                let client2;\n                let backend = Utils.newBackend();\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', (payload) => {\n                        if (payload.event === 'pusher:error' && payload.data.code === 4009) {\n                            client1.disconnect();\n                            client2.disconnect();\n                            done();\n                        }\n\n                        if (payload.event === 'pusher:signin_success') {\n                            client2 = Utils.newClientForPrivateChannel({}, 6002, 'app-key', { id: 2 });\n\n                            client2.connection.bind('connected', () => {\n                                client2.connection.bind('message', (payload) => {\n                                    if (payload.event === 'pusher:signin_success') {\n                                        backend.terminateUserConnections('1');\n                                    }\n                                });\n\n                                client2.signin();\n                            });\n                        }\n                    });\n\n                    client1.signin();\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('broadcast to user for redis', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'port': 6002, 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 });\n                let client2;\n                let backend = Utils.newBackend();\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', (message) => {\n                        if (message.event === 'pusher:signin_success') {\n                            client2 = Utils.newClientForPrivateChannel({}, 6002, 'app-key', { id: 2 });\n\n                            client2.connection.bind('connected', () => {\n                                client2.connection.bind('message', (payload) => {\n                                    if (payload.event === 'pusher:signin_success') {\n                                        backend.sendToUser('1', 'my-event', { works: true });\n                                    }\n                                });\n\n                                client2.signin();\n                            });\n                        }\n\n                        if (message.event === 'my-event') {\n                            client1.disconnect();\n                            client2.disconnect();\n                            done();\n                        }\n                    });\n\n                    client1.signin();\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/http-api.test.ts",
    "content": "import axios from 'axios';\nimport { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('http api test', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    test('health checks', done => {\n        Utils.newServer({}, (server: Server) => {\n            axios.get('http://127.0.0.1:6001').then(res => {\n                done();\n            }).catch(() => {\n                throw new Error('Healthchecks failed');\n            });\n        });\n    });\n\n    test('usage endpoint', done => {\n        Utils.newServer({}, (server: Server) => {\n            axios.get('http://127.0.0.1:9601/usage').then(res => {\n                done();\n            }).catch(() => {\n                throw new Error('Usage endpoint failed');\n            });\n        });\n    });\n\n    test('get api channels', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client1 = Utils.newClient();\n            let backend = Utils.newBackend();\n            let channelName = Utils.randomChannelName();\n\n            client1.connection.bind('connected', () => {\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                        expect(body.channels[channelName]).toBeDefined();\n                        expect(body.channels[channelName].subscription_count).toBe(1);\n                        expect(body.channels[channelName].occupied).toBe(true);\n\n                        let client2 = Utils.newClient();\n\n                        client2.connection.bind('connected', () => {\n                            let channel = client2.subscribe(channelName);\n\n                            channel.bind('pusher:subscription_succeeded', () => {\n                                backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                                    expect(body.channels[channelName]).toBeDefined();\n                                    expect(body.channels[channelName].subscription_count).toBe(2);\n                                    expect(body.channels[channelName].occupied).toBe(true);\n\n                                    client1.connection.bind('disconnected', () => {\n                                        client2.disconnect();\n                                    });\n\n                                    client2.connection.bind('disconnected', () => {\n                                        backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                                            expect(body.channels[channelName]).toBeUndefined();\n                                            done();\n                                        });\n                                    });\n\n                                    client1.disconnect();\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    test('get api channel', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client1 = Utils.newClient();\n            let backend = Utils.newBackend();\n            let channelName = Utils.randomChannelName();\n\n            client1.connection.bind('connected', () => {\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                        expect(body.subscription_count).toBe(1);\n                        expect(body.occupied).toBe(true);\n\n                        let client2 = Utils.newClient();\n\n                        client2.connection.bind('connected', () => {\n                            let channel = client2.subscribe(channelName);\n\n                            channel.bind('pusher:subscription_succeeded', () => {\n                                backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                    expect(body.subscription_count).toBe(2);\n                                    expect(body.occupied).toBe(true);\n\n                                    client1.connection.bind('disconnected', () => {\n                                        client2.disconnect();\n                                    });\n\n                                    client2.connection.bind('disconnected', () => {\n                                        backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                            expect(body.subscription_count).toBe(0);\n                                            expect(body.occupied).toBe(false);\n                                            done();\n                                        });\n                                    });\n\n                                    client1.disconnect();\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    test('get api presence channel', done => {\n        let user1 = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        let user2 = {\n            user_id: 2,\n            user_info: {\n                id: 2,\n                name: 'Alice',\n            },\n        };\n\n        Utils.newServer({}, (server: Server) => {\n            let client1 = Utils.newClientForPresenceUser(user1);\n            let backend = Utils.newBackend();\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            client1.connection.bind('connected', () => {\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                        expect(body.subscription_count).toBe(1);\n                        expect(body.occupied).toBe(true);\n\n                        let client2 = Utils.newClientForPresenceUser(user2);\n\n                        client2.connection.bind('connected', () => {\n                            let channel = client2.subscribe(channelName);\n\n                            channel.bind('pusher:subscription_succeeded', () => {\n                                backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                    expect(body.subscription_count).toBe(2);\n                                    expect(body.user_count).toBe(2);\n                                    expect(body.occupied).toBe(true);\n\n                                    client1.connection.bind('disconnected', () => {\n                                        client2.disconnect();\n                                    });\n\n                                    client2.connection.bind('disconnected', () => {\n                                        backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => {\n                                            expect(body.subscription_count).toBe(0);\n                                            expect(body.user_count).toBe(0);\n                                            expect(body.occupied).toBe(false);\n                                            done();\n                                        });\n                                    });\n\n                                    client1.disconnect();\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    test('get api presence users', done => {\n        let user1 = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        let user2 = {\n            user_id: 2,\n            user_info: {\n                id: 2,\n                name: 'Alice',\n            },\n        };\n\n        Utils.newServer({}, (server: Server) => {\n            let client1 = Utils.newClientForPresenceUser(user1);\n            let backend = Utils.newBackend();\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            client1.connection.bind('connected', () => {\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                        expect(body.users.length).toBe(1);\n\n                        let client2 = Utils.newClientForPresenceUser(user2);\n\n                        client2.connection.bind('connected', () => {\n                            let channel = client2.subscribe(channelName);\n\n                            channel.bind('pusher:subscription_succeeded', () => {\n                                backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                    expect(body.users.length).toBe(2);\n\n                                    client1.connection.bind('disconnected', () => {\n                                        client2.disconnect();\n                                    });\n\n                                    client2.connection.bind('disconnected', () => {\n                                        backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                            expect(body.users.length).toBe(0);\n                                            done();\n                                        });\n                                    });\n\n                                    client1.disconnect();\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    test('presence channel users should count only once for same-user multiple connections', done => {\n        let user = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        Utils.newServer({}, (server: Server) => {\n            let client1 = Utils.newClientForPresenceUser(user);\n            let backend = Utils.newBackend();\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            client1.connection.bind('connected', () => {\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                        expect(body.users.length).toBe(1);\n\n                        let client2 = Utils.newClientForPresenceUser(user);\n\n                        client2.connection.bind('connected', () => {\n                            let channel = client2.subscribe(channelName);\n\n                            channel.bind('pusher:subscription_succeeded', () => {\n                                backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                    expect(body.users.length).toBe(1);\n\n                                    client1.connection.bind('disconnected', () => {\n                                        client2.disconnect();\n                                    });\n\n                                    client2.connection.bind('disconnected', () => {\n                                        backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                                            expect(body.users.length).toBe(0);\n                                            done();\n                                        });\n                                    });\n\n                                    client1.disconnect();\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    test('sends batch events', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClient();\n            let backend = Utils.newBackend();\n            let channelName = Utils.randomChannelName();\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n                let receivedMessages = 0;\n\n                channel.bind('greeting', e => {\n                    expect(e.message).toBe('hello');\n                    expect(e.weirdVariable).toBe('abc/d');\n\n                    receivedMessages++;\n\n                    if (receivedMessages === 3) {\n                        client.disconnect();\n                        done();\n                    }\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.triggerBatch([\n                        { name: 'greeting', channel: channelName, data: { message: 'hello', weirdVariable: 'abc/d' } },\n                        { name: 'greeting', channel: channelName, data: { message: 'hello', weirdVariable: 'abc/d' } },\n                        { name: 'greeting', channel: channelName, data: { message: 'hello', weirdVariable: 'abc/d' } },\n                    ]).catch(error => {\n                        throw new Error(error);\n                    });\n                });\n            });\n        });\n    });\n\n    test('passing an inexistent app id will return 404', done => {\n        Utils.newServer({}, (server: Server) => {\n            let backend = Utils.newBackend('inexistent-app-id');\n\n            backend.get({ path: '/channels' }).then(res => res.json()).then(body => {\n                expect(body.error).toBeDefined();\n                expect(body.code).toBe(404);\n                done();\n            });\n        });\n    });\n\n    test('a non-presence channel cannot read users', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClient();\n            let channelName = Utils.randomChannelName();\n            let backend = Utils.newBackend();\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => {\n                        expect(body.error).toBeDefined();\n                        expect(body.code).toBe(400);\n                        client.disconnect();\n                        done();\n                    });\n                });\n            });\n        });\n    });\n\n    test('throw error when credentials dont match', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClient();\n            let channelName = Utils.randomChannelName();\n            let goodBackend = Utils.newBackend();\n            let badBackend = Utils.newBackend('app-id', 'app-key', 'invalidSecret');\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting-from-bad', e => {\n                    // throw the test if the bad backend can emit\n                    // meaning that the security does not work\n                    expect(true).toBeFalsy();\n                    done();\n                });\n\n                channel.bind('greeting-from-good', e => {\n                    client.disconnect();\n                    done();\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    badBackend.trigger(channelName, 'greeting-from-bad', {\n                        message: 'hello',\n                        array: ['we', 'support', 'array'],\n                        objects: { works: true },\n                    }).catch(error => {\n                        throw new Error(error);\n                    });\n\n                    goodBackend.trigger(channelName, 'greeting-from-good', {\n                        message: 'hello',\n                        array: ['we', 'support', 'array'],\n                        objects: { works: true },\n                    }).catch(error => {\n                        throw new Error(error);\n                    });\n                });\n            });\n        });\n    });\n\n    test('should check for eventLimits.maxChannelsAtOnce', done => {\n        Utils.newServer({ 'eventLimits.maxChannelsAtOnce': 1 }, (server: Server) => {\n            let backend = Utils.newBackend();\n\n            backend.trigger(['ch1', 'ch2'], 'greeting', { message: 'hello' })\n                .then(res => res.json())\n                .then(res => {\n                    expect(res.error).toBeDefined();\n                    expect(res.code).toBe(400);\n                    done();\n                })\n                .catch(error => {\n                    throw new Error(error);\n                });\n        });\n    });\n\n    test('should check for eventLimits.maxNameLength', done => {\n        Utils.newServer({ 'eventLimits.maxNameLength': 7 }, (server: Server) => {\n            let backend = Utils.newBackend();\n\n            backend.trigger('ch1', 'greeting', { message: 'hello' })\n                .then(res => res.json())\n                .then(res => {\n                    expect(res.error).toBeDefined();\n                    expect(res.code).toBe(400);\n                    done();\n                })\n                .catch(error => {\n                    throw new Error(error);\n                });\n        });\n    });\n\n    test('should check for eventLimits.maxPayloadInKb', done => {\n        Utils.newServer({ 'eventLimits.maxPayloadInKb': 1/1024 }, (server: Server) => {\n            let backend = Utils.newBackend();\n\n            backend.trigger('ch1', 'greeting', { message: 'hello' })\n                .then(res => res.json())\n                .then(res => {\n                    expect(res.error).toBeDefined();\n                    expect(res.code).toBe(413);\n                    done();\n                })\n                .catch(error => {\n                    throw new Error(error);\n                });\n        });\n    });\n\n    test('should check for httpApi.requestLimitInMb', done => {\n        Utils.newServer({ 'httpApi.requestLimitInMb': 1/1024/1024 }, (server: Server) => {\n            let backend = Utils.newBackend();\n\n            backend.trigger('ch1', 'greeting', { message: 'hello' })\n                .catch(err => {\n                    expect(err.body).toBeDefined();\n                    expect(err.status).toBe(413);\n                    done();\n                })\n                .then(res => {\n                    if (res && res.json()) {\n                        throw new Error('The request limit did not work.');\n                    }\n                });\n        });\n    });\n\n    test('non existent route must return 404', done => {\n        Utils.newServer({}, (server: Server) => {\n            axios.get('http://127.0.0.1:6001/favicon.ico').then(res => {\n                throw new Error('Status must be 404');\n            },(e) => {\n                if (e.response.status !== 404) {\n                    throw new Error('Status must be 404');\n                }\n\n                done();\n            });\n        });\n    });\n\n    test('check server can handle a numeric app id', done => {\n        Utils.newServer({\n            'appManager.array.apps.0.id': 40000\n        }, (server: Server) => {\n            // Don't test database configs, because the APP-ID is hard coded (therefore this will always fail).\n            if (process.env.TEST_APP_MANAGER != 'array') {\n                done();\n            }\n\n            let client = Utils.newClient();\n            let backend = Utils.newBackend(\"40000\");\n            let channelName = Utils.randomChannelName();\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', e => {\n                    expect(e.message).toBe('hello');\n                    expect(e.weirdVariable).toBe('abc/d');\n                    client.disconnect();\n                    done();\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.trigger(channelName, 'greeting', { message: 'hello', weirdVariable: 'abc/d' })\n                        .catch(error => {\n                            throw new Error(error);\n                        });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('signin after connection with termination call', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => {\n            let client = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 });\n            let backend = Utils.newBackend();\n\n            client.connection.bind('connected', () => {\n                client.connection.bind('message', (payload) => {\n                    if (payload.event === 'pusher:error' && payload.data.code === 4009) {\n                        client.disconnect();\n                        done();\n                    }\n\n                    if (payload.event === 'pusher:signin_success') {\n                        backend.terminateUserConnections('1');\n                    }\n                });\n\n                client.signin();\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('broadcast to user', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => {\n            let client = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 });\n            let backend = Utils.newBackend();\n\n            client.connection.bind('connected', () => {\n                client.connection.bind('message', (message) => {\n                    if (message.event === 'my-event') {\n                        client.disconnect();\n                        done();\n                    }\n\n                    if (message.event === 'pusher:signin_success') {\n                        backend.sendToUser('1', 'my-event', { works: true });\n                    }\n                });\n\n                client.signin();\n            });\n        });\n    });\n\n    test('get api presence channel with filter_by_prefix', done => {\n        let user1 = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        Utils.newServer({}, (server: Server) => {\n            let presenceClient = Utils.newClientForPresenceUser(user1);\n            let backend = Utils.newBackend();\n            let presenceChannelName = `presence-${Utils.randomChannelName()}`;\n\n            presenceClient.connection.bind('connected', () => {\n                let presenceChannel = presenceClient.subscribe(presenceChannelName);\n\n                presenceChannel.bind('pusher:subscription_succeeded', () => {\n                    let privateClient = Utils.newClientForPrivateChannel();\n                    let privateChannelName = `private-${Utils.randomChannelName()}`;\n\n                    privateClient.connection.bind('connected', () => {\n                        let privateChannel = privateClient.subscribe(privateChannelName);\n\n                        privateChannel.bind('pusher:subscription_succeeded', () => {\n                            backend.get({ path: '/channels', params: { filter_by_prefix: `presence-` } }).then(res => res.json()).then(body => {\n                                expect(body.channels[presenceChannelName]).toBeDefined();\n                                expect(body.channels[privateChannelName]).toBeUndefined();\n                                expect(body.channels[presenceChannelName].subscription_count).toBe(1);\n\n                                presenceClient.disconnect();\n                                privateClient.disconnect();\n                                done();\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/presence.cluster-adapter.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('presence channel test for cluster adapter', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster'))('handles joins and leaves for cluster adapter', done => {\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let john = {\n                    user_id: 1,\n                    user_info: {\n                        id: 1,\n                        name: 'John',\n                    },\n                };\n\n                let alice = {\n                    user_id: 2,\n                    user_info: {\n                        id: 2,\n                        name: 'Alice',\n                    },\n                };\n\n                let johnClient = Utils.newClientForPresenceUser(john);\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                johnClient.connection.bind('connected', () => {\n                    let johnChannel = johnClient.subscribe(channelName);\n\n                    johnChannel.bind('pusher:subscription_succeeded', (data) => {\n                        expect(data.count).toBe(1);\n                        expect(data.me.id).toBe(1);\n                        expect(data.members['1'].id).toBe(1);\n                        expect(data.me.info.name).toBe('John');\n\n                        let aliceClient = Utils.newClientForPresenceUser(alice, {}, 6002);\n\n                        aliceClient.connection.bind('connected', () => {\n                            Utils.wait(3000).then(() => {\n                                let aliceChannel = aliceClient.subscribe(channelName);\n\n                                aliceChannel.bind('pusher:subscription_succeeded', (data) => {\n                                    expect(data.count).toBe(2);\n                                    expect(data.me.id).toBe(2);\n                                    expect(data.members['1'].id).toBe(1);\n                                    expect(data.members['2'].id).toBe(2);\n                                    expect(data.me.info.name).toBe('Alice');\n                                    aliceClient.disconnect();\n                                });\n                            });\n                        });\n                    });\n\n                    johnChannel.bind('pusher:member_added', data => {\n                        expect(data.id).toBe(2);\n                        expect(data.info.name).toBe('Alice');\n                    });\n\n                    johnChannel.bind('pusher:member_removed', data => {\n                        expect(data.id).toBe(2);\n                        expect(data.info.name).toBe('Alice');\n                        johnClient.disconnect();\n                        done();\n                    });\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/presence.nats-adapter.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('presence channel test for nats adapter', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats'))('handles joins and leaves for nats adapter', done => {\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let john = {\n                    user_id: 1,\n                    user_info: {\n                        id: 1,\n                        name: 'John',\n                    },\n                };\n\n                let alice = {\n                    user_id: 2,\n                    user_info: {\n                        id: 2,\n                        name: 'Alice',\n                    },\n                };\n\n                let johnClient = Utils.newClientForPresenceUser(john);\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                johnClient.connection.bind('connected', () => {\n                    let johnChannel = johnClient.subscribe(channelName);\n\n                    johnChannel.bind('pusher:subscription_succeeded', (data) => {\n                        expect(data.count).toBe(1);\n                        expect(data.me.id).toBe(1);\n                        expect(data.members['1'].id).toBe(1);\n                        expect(data.me.info.name).toBe('John');\n\n                        let aliceClient = Utils.newClientForPresenceUser(alice, {}, 6002);\n\n                        aliceClient.connection.bind('connected', () => {\n                            Utils.wait(3000).then(() => {\n                                let aliceChannel = aliceClient.subscribe(channelName);\n\n                                aliceChannel.bind('pusher:subscription_succeeded', (data) => {\n                                    expect(data.count).toBe(2);\n                                    expect(data.me.id).toBe(2);\n                                    expect(data.members['1'].id).toBe(1);\n                                    expect(data.members['2'].id).toBe(2);\n                                    expect(data.me.info.name).toBe('Alice');\n                                    aliceClient.disconnect();\n                                });\n                            });\n                        });\n                    });\n\n                    johnChannel.bind('pusher:member_added', data => {\n                        expect(data.id).toBe(2);\n                        expect(data.info.name).toBe('Alice');\n                    });\n\n                    johnChannel.bind('pusher:member_removed', data => {\n                        expect(data.id).toBe(2);\n                        expect(data.info.name).toBe('Alice');\n                        johnClient.disconnect();\n                        done();\n                    });\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/presence.redis-adapter.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('presence channel test for redis adapter', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis'))('handles joins and leaves for redis adapter', done => {\n        Utils.newServer({ port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let john = {\n                    user_id: 1,\n                    user_info: {\n                        id: 1,\n                        name: 'John',\n                    },\n                };\n\n                let alice = {\n                    user_id: 2,\n                    user_info: {\n                        id: 2,\n                        name: 'Alice',\n                    },\n                };\n\n                let johnClient = Utils.newClientForPresenceUser(john);\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                johnClient.connection.bind('connected', () => {\n                    let johnChannel = johnClient.subscribe(channelName);\n\n                    johnChannel.bind('pusher:subscription_succeeded', (data) => {\n                        expect(data.count).toBe(1);\n                        expect(data.me.id).toBe(1);\n                        expect(data.members['1'].id).toBe(1);\n                        expect(data.me.info.name).toBe('John');\n\n                        let aliceClient = Utils.newClientForPresenceUser(alice, {}, 6002);\n\n                        aliceClient.connection.bind('connected', () => {\n                            let aliceChannel = aliceClient.subscribe(channelName);\n\n                            aliceChannel.bind('pusher:subscription_succeeded', (data) => {\n                                expect(data.count).toBe(2);\n                                expect(data.me.id).toBe(2);\n                                expect(data.members['1'].id).toBe(1);\n                                expect(data.members['2'].id).toBe(2);\n                                expect(data.me.info.name).toBe('Alice');\n                                aliceClient.disconnect();\n                            });\n                        });\n                    });\n\n                    johnChannel.bind('pusher:member_added', data => {\n                        expect(data.id).toBe(2);\n                        expect(data.info.name).toBe('Alice');\n                    });\n\n                    johnChannel.bind('pusher:member_removed', data => {\n                        expect(data.id).toBe(2);\n                        expect(data.info.name).toBe('Alice');\n                        johnClient.disconnect();\n                        done();\n                    });\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/presence.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('presence channel test', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    test('connects to presence channel', done => {\n        Utils.newServer({}, (server: Server) => {\n            let user = {\n                user_id: 1,\n                user_info: {\n                    id: 1,\n                    name: 'John',\n                },\n            };\n\n            let client = Utils.newClientForPresenceUser(user);\n            let backend = Utils.newBackend();\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', (e) => {\n                    expect(e.message).toBe('hello');\n                    client.disconnect();\n                    done();\n                });\n\n                channel.bind('pusher:subscription_succeeded', (data) => {\n                    expect(data.count).toBe(1);\n                    expect(data.me.id).toBe(1);\n                    expect(data.members['1'].id).toBe(1);\n                    expect(data.me.info.name).toBe('John');\n\n                    backend.trigger(channelName, 'greeting', { message: 'hello' })\n                        .catch(error => {\n                            throw new Error(error);\n                        });\n                });\n            });\n        });\n    });\n\n    test('handles joins and leaves', done => {\n        Utils.newServer({}, (server: Server) => {\n            let john = {\n                user_id: 1,\n                user_info: {\n                    id: 1,\n                    name: 'John',\n                },\n            };\n\n            let alice = {\n                user_id: 2,\n                user_info: {\n                    id: 2,\n                    name: 'Alice',\n                },\n            };\n\n            let johnClient = Utils.newClientForPresenceUser(john);\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            johnClient.connection.bind('connected', () => {\n                let johnChannel = johnClient.subscribe(channelName);\n\n                johnChannel.bind('pusher:subscription_succeeded', (data) => {\n                    expect(data.count).toBe(1);\n                    expect(data.me.id).toBe(1);\n                    expect(data.members['1'].id).toBe(1);\n                    expect(data.me.info.name).toBe('John');\n\n                    let aliceClient = Utils.newClientForPresenceUser(alice);\n\n                    aliceClient.connection.bind('connected', () => {\n                        let aliceChannel = aliceClient.subscribe(channelName);\n\n                        aliceChannel.bind('pusher:subscription_succeeded', (data) => {\n                            expect(data.count).toBe(2);\n                            expect(data.me.id).toBe(2);\n                            expect(data.members['1'].id).toBe(1);\n                            expect(data.members['2'].id).toBe(2);\n                            expect(data.me.info.name).toBe('Alice');\n                            aliceClient.disconnect();\n                        });\n                    });\n                });\n\n                johnChannel.bind('pusher:member_added', data => {\n                    expect(data.id).toBe(2);\n                    expect(data.info.name).toBe('Alice');\n                });\n\n                johnChannel.bind('pusher:member_removed', data => {\n                    expect(data.id).toBe(2);\n                    expect(data.info.name).toBe('Alice');\n                    johnClient.disconnect();\n                    done();\n                });\n            });\n        });\n    });\n\n    test('cannot connect to presence channel with wrong authentication', done => {\n        Utils.newServer({}, (server: Server) => {\n            let user = {\n                user_id: 1,\n                user_info: {\n                    id: 1,\n                    name: 'John',\n                },\n            };\n\n            let client = Utils.newClientForPresenceUser(user, {\n                authorizer: (channel, options) => ({\n                    authorize: (socketId, callback) => {\n                        callback(false, {\n                            auth: 'incorrect_token',\n                            channel_data: JSON.stringify(user),\n                        });\n                    },\n                }),\n            });\n\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            client.connection.bind('message', ({ event, channel, data }) => {\n                if (event === 'pusher:subscription_error' && channel === channelName) {\n                    expect(data.type).toBe('AuthError');\n                    expect(data.status).toBe(401);\n                    client.disconnect();\n                    done();\n                }\n            });\n\n            client.connection.bind('connected', () => {\n                client.subscribe(channelName);\n            });\n        });\n    });\n\n    test('connects and disconnects to presence channel and does not leak memory', done => {\n        Utils.newServer({}, (server: Server) => {\n            let user = {\n                user_id: 1,\n                user_info: {\n                    id: 1,\n                    name: 'John',\n                },\n            };\n\n            let client = Utils.newClientForPresenceUser(user);\n            let backend = Utils.newBackend();\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            client.connection.bind('disconnected', () => {\n                Utils.wait(3000).then(() => {\n                    let namespace = server.adapter.getNamespace('app-id');\n\n                    expect(namespace.sockets.size).toBe(0);\n                    expect(namespace.channels.size).toBe(0);\n                    done();\n                });\n            });\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', (e) => {\n                    expect(e.message).toBe('hello');\n\n                    client.unsubscribe(channelName);\n\n                    Utils.wait(3000).then(() => {\n                        let namespace = server.adapter.getNamespace('app-id');\n                        let socket = namespace.sockets.get(namespace.sockets.keys().next().value);\n\n                        expect(namespace.channels.size).toBe(0);\n                        expect(namespace.sockets.size).toBe(1);\n                        expect(socket.subscribedChannels.size).toBe(0);\n                        expect(socket.presence.size).toBe(0);\n                        client.disconnect();\n                    });\n                });\n\n                channel.bind('pusher:subscription_succeeded', (data) => {\n                    backend.trigger(channelName, 'greeting', { message: 'hello' });\n                });\n            });\n        });\n    });\n\n    test('sudden close connection in presence channel and does not leak memory', done => {\n        Utils.newServer({}, (server: Server) => {\n            let user = {\n                user_id: 1,\n                user_info: {\n                    id: 1,\n                    name: 'John',\n                },\n            };\n\n            let client = Utils.newClientForPresenceUser(user);\n            let backend = Utils.newBackend();\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            client.connection.bind('disconnected', () => {\n                Utils.wait(3000).then(() => {\n                    let namespace = server.adapter.getNamespace('app-id');\n\n                    expect(namespace.sockets.size).toBe(0);\n                    expect(namespace.channels.size).toBe(0);\n                    done();\n                });\n            });\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', (e) => {\n                    expect(e.message).toBe('hello');\n                    client.disconnect();\n                });\n\n                channel.bind('pusher:subscription_succeeded', (data) => {\n                    backend.trigger(channelName, 'greeting', { message: 'hello' });\n                });\n            });\n        });\n    });\n\n    test('connecting to the channel twice with same user does not trigger member_added twice', done => {\n        Utils.newServer({}, (server: Server) => {\n            let john = {\n                user_id: 1,\n                user_info: {\n                    id: 1,\n                    name: 'John',\n                },\n            };\n\n            let alice = {\n                user_id: 2,\n                user_info: {\n                    id: 2,\n                    name: 'Alice',\n                },\n            };\n\n            let johnClient = Utils.newClientForPresenceUser(john);\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            johnClient.connection.bind('connected', () => {\n                let johnChannel = johnClient.subscribe(channelName);\n\n                johnChannel.bind('pusher:subscription_succeeded', (data) => {\n                    let aliceClient = Utils.newClientForPresenceUser(alice);\n\n                    aliceClient.connection.bind('connected', () => {\n                        let aliceChannel = aliceClient.subscribe(channelName);\n\n                        aliceChannel.bind('pusher:member_added', data => {\n                            throw new Error('Did not expect John to be added again.');\n                        });\n\n                        aliceChannel.bind('pusher:member_removed', data => {\n                            server.adapter.getChannelMembers('app-id', channelName).then(members => {\n                                if (members.size === 1) {\n                                    done();\n                                    aliceClient.disconnect();\n                                } else {\n                                    throw new Error('The member_removed got triggered but John did not left.');\n                                }\n                            });\n                        });\n\n                        aliceChannel.bind('pusher:subscription_succeeded', (data) => {\n                            expect(data.count).toBe(2);\n\n                            let anotherJohnClient = Utils.newClientForPresenceUser(john);\n\n                            anotherJohnClient.connection.bind('connected', () => {\n                                let anotherJohnChannel = anotherJohnClient.subscribe(channelName);\n\n                                anotherJohnChannel.bind('pusher:subscription_succeeded', (data) => {\n                                    expect(data.count).toBe(2);\n\n                                    anotherJohnClient.disconnect();\n                                    johnClient.disconnect();\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    test('cached presence channels work', done => {\n        Utils.newServer({}, (server: Server) => {\n            let john = {\n                user_id: 1,\n                user_info: {\n                    id: 1,\n                    name: 'John',\n                },\n            };\n\n            let alice = {\n                user_id: 2,\n                user_info: {\n                    id: 2,\n                    name: 'Alice',\n                },\n            };\n\n            let client1 = Utils.newClientForPresenceUser(john);\n            let backend = Utils.newBackend();\n            let channelName = `presence-cache-${Utils.randomChannelName()}`;\n\n            client1.connection.bind('connected', () => {\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    channel.bind('pusher:cache_miss', (data) => {\n                        expect(data).toBe(undefined);\n\n                        channel.bind('greeting', e => {\n                            expect(e.message).toBe('hello');\n    \n                            let client2 = Utils.newClientForPresenceUser(alice);\n    \n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n    \n                                channel.bind('greeting', e => {\n                                    expect(e.message).toBe('hello');\n                                    done()\n                                })\n                                channel.bind('pusher:cache_miss', () => {\n                                    throw new Error('Did not expect cache_miss to be invoked.');\n                                });\n                            });\n                        });\n                    });\n\n                    backend.trigger(channelName, 'greeting', { message: 'hello' }).catch(error => {\n                        throw new Error(error);\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('user authentication works if conn immediately joins a presence channel', (done) => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => {\n            let user = {\n                user_id: 1,\n                user_info: {\n                    id: 1,\n                    name: 'John',\n                },\n            };\n\n            let client = Utils.newClientForPresenceUser(user);\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    // After subscription, wait 10 seconds to make sure it isn't disconnected\n                    setTimeout(() => {\n                        client.disconnect();\n                        done();\n                    }, 10_000);\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/private.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('private channel test', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    test('connects to private channel', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClientForPrivateChannel();\n            let backend = Utils.newBackend();\n            let channelName = `private-${Utils.randomChannelName()}`;\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', e => {\n                    expect(e.message).toBe('hello');\n                    client.disconnect();\n                    done();\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.trigger(channelName, 'greeting', { message: 'hello' })\n                        .catch(error => {\n                            throw new Error(error);\n                        });\n                });\n            });\n        });\n    });\n\n    test('cannot connect to private channel with wrong authentication', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClientForPrivateChannel({\n                authorizer: (channel, options) => ({\n                    authorize: (socketId, callback) => {\n                        callback(false, {\n                            auth: 'incorrect_token',\n                            channel_data: null,\n                        });\n                    },\n                }),\n            });\n\n            let channelName = `private-${Utils.randomChannelName()}`;\n\n            client.connection.bind('message', ({ event, channel, data }) => {\n                if (event === 'pusher:subscription_error' && channel === channelName) {\n                    expect(data.type).toBe('AuthError');\n                    expect(data.status).toBe(401);\n                    client.disconnect();\n                    done();\n                }\n            });\n\n            client.connection.bind('connected', () => {\n                client.subscribe(channelName);\n            });\n        });\n    });\n\n    test('connects and disconnects to private channel and does not leak memory', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClientForPrivateChannel();\n            let backend = Utils.newBackend();\n            let channelName = `private-${Utils.randomChannelName()}`;\n\n            client.connection.bind('disconnected', () => {\n                Utils.wait(3000).then(() => {\n                    let namespace = server.adapter.getNamespace('app-id');\n\n                    expect(namespace.sockets.size).toBe(0);\n                    expect(namespace.channels.size).toBe(0);\n                    done();\n                });\n            });\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', e => {\n                    expect(e.message).toBe('hello');\n\n                    client.unsubscribe(channelName);\n\n                    Utils.wait(3000).then(() => {\n                        let namespace = server.adapter.getNamespace('app-id');\n                        let socket = namespace.sockets.get(namespace.sockets.keys().next().value);\n\n                        expect(namespace.channels.size).toBe(0);\n                        expect(namespace.sockets.size).toBe(1);\n                        expect(socket.subscribedChannels.size).toBe(0);\n                        expect(socket.presence.size).toBe(0);\n\n                        client.disconnect();\n                    });\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.trigger(channelName, 'greeting', { message: 'hello' });\n                });\n            });\n        });\n    });\n\n    test('sudden close connection in private channel and does not leak memory', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClientForPrivateChannel();\n            let backend = Utils.newBackend();\n            let channelName = `private-${Utils.randomChannelName()}`;\n\n            client.connection.bind('disconnected', () => {\n                Utils.wait(3000).then(() => {\n                    let namespace = server.adapter.getNamespace('app-id');\n\n                    expect(namespace.sockets.size).toBe(0);\n                    expect(namespace.channels.size).toBe(0);\n                    done();\n                });\n            });\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', e => {\n                    expect(e.message).toBe('hello');\n                    client.disconnect();\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.trigger(channelName, 'greeting', { message: 'hello' });\n                });\n            });\n        });\n    });\n\n    test('cached private channels work', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client1 = Utils.newClientForPrivateChannel();\n            let backend = Utils.newBackend();\n            let channelName = `private-cache-${Utils.randomChannelName()}`;\n\n            client1.connection.bind('connected', () => {\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    channel.bind('pusher:cache_miss', (data) => {\n                        expect(data).toBe(undefined);\n\n                        channel.bind('greeting', e => {\n                            expect(e.message).toBe('hello');\n    \n                            let client2 = Utils.newClientForPrivateChannel();\n    \n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:cache_miss', () => {\n                                    throw new Error('Did not expect cache_miss to be invoked.');\n                                });\n\n                                channel.bind('greeting', e => {\n                                    expect(e.message).toBe('hello');\n                                    done()\n                                })\n                            });\n                        });\n                    });\n\n                    backend.trigger(channelName, 'greeting', { message: 'hello' }).catch(error => {\n                        throw new Error(error);\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('user authentication works if conn immediately joins a private channel', (done) => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => {\n            let client = Utils.newClientForPrivateChannel();\n            let channelName = `private-${Utils.randomChannelName()}`;\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    // After subscription, wait 10 seconds to make sure it isn't disconnected\n                    setTimeout(() => {\n                        client.disconnect();\n                        done();\n                    }, 10_000);\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/public.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\ndescribe('public channel test', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    test('connects to public channel', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClient();\n            let backend = Utils.newBackend();\n            let channelName = Utils.randomChannelName();\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', e => {\n                    expect(e.message).toBe('hello');\n                    expect(e.weirdVariable).toBe('abc/d');\n                    client.disconnect();\n                    done();\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.trigger(channelName, 'greeting', { message: 'hello', weirdVariable: 'abc/d' })\n                        .catch(error => {\n                            throw new Error(error);\n                        });\n                });\n            });\n        });\n    });\n\n    test('connects and disconnected to public channel does not leak memory', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClient();\n            let backend = Utils.newBackend();\n            let channelName = Utils.randomChannelName();\n\n            client.connection.bind('disconnected', () => {\n                Utils.wait(3000).then(() => {\n                    let namespace = server.adapter.getNamespace('app-id');\n\n                    expect(namespace.sockets.size).toBe(0);\n                    expect(namespace.channels.size).toBe(0);\n                    done();\n                });\n            });\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', e => {\n                    expect(e.message).toBe('hello');\n\n                    client.unsubscribe(channelName);\n\n                    Utils.wait(3000).then(() => {\n                        let namespace = server.adapter.getNamespace('app-id');\n                        let socket = namespace.sockets.get(namespace.sockets.keys().next().value);\n\n                        expect(namespace.channels.size).toBe(0);\n                        expect(namespace.sockets.size).toBe(1);\n                        expect(socket.subscribedChannels.size).toBe(0);\n                        expect(socket.presence.size).toBe(0);\n\n                        client.disconnect();\n                    });\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.trigger(channelName, 'greeting', { message: 'hello' });\n                });\n            });\n        });\n    });\n\n    test('sudden close connection in public channel does not leak memory', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClient();\n            let backend = Utils.newBackend();\n            let channelName = Utils.randomChannelName();\n\n            client.connection.bind('disconnected', () => {\n                Utils.wait(3000).then(() => {\n                    let namespace = server.adapter.getNamespace('app-id');\n\n                    expect(namespace.sockets.size).toBe(0);\n                    expect(namespace.channels.size).toBe(0);\n                    done();\n                });\n            });\n\n            client.connection.bind('connected', () => {\n                let channel = client.subscribe(channelName);\n\n                channel.bind('greeting', e => {\n                    expect(e.message).toBe('hello');\n                    client.disconnect();\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    backend.trigger(channelName, 'greeting', { message: 'hello' });\n                });\n            });\n        });\n    });\n\n    test('cached public channels work', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client1 = Utils.newClient();\n            let backend = Utils.newBackend();\n            let channelName = `cache-${Utils.randomChannelName()}`;\n\n            client1.connection.bind('connected', () => {\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    channel.bind('pusher:cache_miss', (data) => {\n                        expect(data).toBe(undefined);\n\n                        channel.bind('greeting', e => {\n                            expect(e.message).toBe('hello');\n    \n                            let client2 = Utils.newClient();\n    \n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:cache_miss', () => {\n                                    throw new Error('Did not expect cache_miss to be invoked.');\n                                });\n\n                                channel.bind('greeting', e => {\n                                    expect(e.message).toBe('hello');\n                                    done()\n                                })\n                            });\n                        });\n                    });\n\n                    backend.trigger(channelName, 'greeting', { message: 'hello' }).catch(error => {\n                        throw new Error(error);\n                    });\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/utils.ts",
    "content": "import async from 'async';\nimport { Log } from '../src/log';\nimport { PusherApiMessage } from '../src/message';\nimport { Server } from './../src/server';\nimport { v4 as uuidv4 } from 'uuid';\n\nconst bodyParser = require('body-parser');\nconst express = require('express');\nconst Pusher = require('pusher');\nconst PusherJS = require('pusher-js');\nconst tcpPortUsed = require('tcp-port-used');\n\nexport class Utils {\n    public static wsServers: Server[] = [];\n    public static httpServers: any[] = [];\n\n    static appManagerIs(manager: string): boolean {\n        return (process.env.TEST_APP_MANAGER || 'array') === manager;\n    }\n\n    static adapterIs(adapter: string) {\n        return (process.env.TEST_ADAPTER || 'local') === adapter;\n    }\n\n    static queueDriverIs(queueDriver: string) {\n        return (process.env.TEST_QUEUE_DRIVER || 'sync') === queueDriver;\n    }\n\n    static waitForPortsToFreeUp(): Promise<any> {\n        return Promise.all([\n            tcpPortUsed.waitUntilFree(6001, 500, 5 * 1000),\n            tcpPortUsed.waitUntilFree(6002, 500, 5 * 1000),\n            tcpPortUsed.waitUntilFree(3001, 500, 5 * 1000),\n            tcpPortUsed.waitUntilFree(9601, 500, 5 * 1000),\n            tcpPortUsed.waitUntilFree(11002, 500, 5 * 1000),\n        ]);\n    }\n\n    static newServer(options = {}, callback): any {\n        options = {\n            'cluster.prefix': uuidv4(),\n            'adapter.redis.prefix': uuidv4(),\n            'adapter.nats.prefix': uuidv4(),\n            'appManager.array.apps.0.maxBackendEventsPerSecond': 200,\n            'appManager.array.apps.0.maxClientEventsPerSecond': 200,\n            'appManager.array.apps.0.maxReadRequestsPerSecond': 200,\n            'metrics.enabled': true,\n            'appManager.mysql.useMysql2': true,\n            'cluster.port': parseInt((Math.random() * (20000 - 10000) + 10000).toString()), // random: 10000-20000\n            'appManager.dynamodb.endpoint': 'http://127.0.0.1:8000',\n            'cluster.ignoreProcess': false,\n            'webhooks.batching.enabled': false, // TODO: Find out why batching works but fails tests\n            'webhooks.batching.duration': 1,\n            'appManager.cache.enabled': true,\n            'appManager.cache.ttl': -1,\n            ...options,\n            'adapter.driver': process.env.TEST_ADAPTER || 'local',\n            'cache.driver': process.env.TEST_CACHE_DRIVER || 'memory',\n            'appManager.driver': process.env.TEST_APP_MANAGER || 'array',\n            'queue.driver': process.env.TEST_QUEUE_DRIVER || 'sync',\n            'rateLimiter.driver': process.env.TEST_RATE_LIMITER || 'local',\n            'database.mysql.user': process.env.TEST_MYSQL_USER || 'testing',\n            'database.mysql.password': process.env.TEST_MYSQL_PASSWORD || 'testing',\n            'database.mysql.database': process.env.TEST_MYSQL_DATABASE || 'testing',\n            'database.postgres.user': process.env.TEST_POSTGRES_USER || 'testing',\n            'database.postgres.password': process.env.TEST_POSTGRES_PASSWORD || 'testing',\n            'database.postgres.database': process.env.TEST_POSTGRES_DATABASE || 'testing',\n            'queue.sqs.queueUrl': process.env.TEST_SQS_URL || 'http://localhost:4566/000000000000/test.fifo',\n            'debug': process.env.TEST_DEBUG || false,\n            'shutdownGracePeriod': 1_000,\n        };\n\n        return (new Server(options)).start((server: Server) => {\n            this.wsServers.push(server);\n\n            if (server.options.cache.driver === 'redis') {\n                server.cacheManager.driver.redisConnection.flushdb().then(() => {\n                    callback(server);\n                });\n            } else {\n                callback(server);\n            }\n        });\n    }\n\n    static newClonedServer(server: Server, options = {}, callback): any {\n        return this.newServer({\n            // Make sure the same prefixes exists so that they can communicate\n            'adapter.redis.prefix': server.options.adapter.redis.prefix,\n            'adapter.nats.prefix': server.options.adapter.nats.prefix,\n            'cluster.prefix': server.options.cluster.prefix,\n            'cluster.port': server.options.cluster.port,\n            ...options,\n        }, callback);\n    }\n\n    static newWebhookServer(requestHandler: CallableFunction, onReadyCallback: CallableFunction): any {\n        let webhooksApp = express();\n\n        webhooksApp.use(bodyParser.json());\n\n        webhooksApp.use((req, res, next) => {\n            res.header('Access-Control-Allow-Origin', '*');\n            res.header('Access-Control-Allow-Methods', '*');\n            res.header('Access-Control-Allow-Headers', '*');\n            next();\n        });\n\n        webhooksApp.post('*', requestHandler);\n\n        let server = webhooksApp.listen(3001, () => {\n            Log.successTitle('🎉 Webhook Server is up and running!');\n\n            server.on('error', err => {\n                console.log('Websocket server error', err);\n            });\n\n            this.httpServers.push(server);\n\n            onReadyCallback(server);\n        });\n    }\n\n    static flushWsServers(): Promise<void> {\n        if (this.wsServers.length === 0) {\n            return Promise.resolve();\n        }\n\n        return async.each(this.wsServers, (server: Server, serverCallback) => {\n            server.stop().then(() => {\n                serverCallback();\n            });\n        }).then(() => {\n            this.wsServers = [];\n        });\n    }\n\n    static flushHttpServers(): Promise<void> {\n        if (this.httpServers.length === 0) {\n            return Promise.resolve();\n        }\n\n        return async.each(this.httpServers, (server: any, serverCallback) => {\n            server.close(() => {\n                serverCallback();\n            });\n        }).then(() => {\n            this.httpServers = [];\n        });\n    }\n\n    static flushServers(): Promise<any> {\n        return Promise.all([\n            this.flushWsServers(),\n            this.flushHttpServers(),\n        ]);\n    }\n\n    static newClient(options = {}, port = 6001, key = 'app-key', withStateChange = true): any {\n        let client = new PusherJS(key, {\n            wsHost: '127.0.0.1',\n            httpHost: '127.0.0.1',\n            wsPort: port,\n            wssPort: port,\n            httpPort: port,\n            httpsPort: port,\n            forceTLS: false,\n            encrypted: true,\n            disableStats: true,\n            enabledTransports: ['ws'],\n            ignoreNullOrigin: true,\n            encryptionMasterKeyBase64: 'nxzvbGF+f8FGhk/jOaZvgMle1tqxzF/VfUZLBLhhaH0=',\n            ...options,\n        });\n\n        if (withStateChange) {\n            client.connection.bind('state_change', ({ current }) => {\n                if (current === 'unavailable') {\n                    console.log('The connection could not be made. Status: ' + current);\n                }\n            });\n        }\n\n        return client;\n    }\n\n    static newBackend(appId = 'app-id', key = 'app-key', secret = 'app-secret', port = 6001): any {\n        return new Pusher({\n            appId,\n            key,\n            secret,\n            host: '127.0.0.1',\n            port,\n            encryptionMasterKeyBase64: 'nxzvbGF+f8FGhk/jOaZvgMle1tqxzF/VfUZLBLhhaH0=',\n        });\n    }\n\n    static newClientForPrivateChannel(clientOptions = {}, port = 6001, key = 'app-key', userData = {}): any {\n        return this.newClient({\n            authorizer: (channel, options) => ({\n                authorize: (socketId, callback) => {\n                    callback(false, {\n                        auth: this.signTokenForPrivateChannel(socketId, channel),\n                        channel_data: null,\n                    });\n                },\n            }),\n            userAuthentication: {\n                customHandler: ({ socketId }, callback) => {\n                    callback(false, {\n                        auth: this.signTokenForUserAuthentication(socketId, JSON.stringify(userData), key),\n                        user_data: JSON.stringify(userData),\n                    });\n                },\n            },\n            ...clientOptions,\n        }, port, key);\n    }\n\n    static newClientForEncryptedPrivateChannel(clientOptions = {}, port = 6001, key = 'app-key', userData = {}): any {\n        return this.newClient({\n            authorizer: (channel, options) => ({\n                authorize: (socketId, callback) => {\n                    callback(false, {\n                        auth: this.signTokenForPrivateChannel(socketId, channel, key),\n                        channel_data: null,\n                        shared_secret: this.newBackend().channelSharedSecret(channel.name).toString('base64'),\n                    });\n                },\n            }),\n            userAuthentication: {\n                customHandler: ({ socketId }, callback) => {\n                    callback(false, {\n                        auth: this.signTokenForUserAuthentication(socketId, JSON.stringify(userData), key),\n                        user_data: JSON.stringify(userData),\n                    });\n                },\n            },\n            ...clientOptions,\n        }, port, key);\n    }\n\n    static newClientForPresenceUser(user: any, clientOptions = {}, port = 6001, key = 'app-key', userData = {}): any {\n        return this.newClient({\n            authorizer: (channel, options) => ({\n                authorize: (socketId, callback) => {\n                    callback(false, {\n                        auth: this.signTokenForPresenceChannel(socketId, channel, user, key),\n                        channel_data: JSON.stringify(user),\n                    });\n                },\n            }),\n            userAuthentication: {\n                customHandler: ({ socketId }, callback) => {\n                    callback(false, {\n                        auth: this.signTokenForUserAuthentication(socketId, JSON.stringify(userData), key),\n                        user_data: JSON.stringify(userData),\n                    });\n                },\n            },\n            ...clientOptions,\n        }, port, key);\n    }\n\n    static signTokenForPrivateChannel(\n        socketId: string,\n        channel: any,\n        key = 'app-key',\n        secret = 'app-secret'\n    ): string {\n        let token = new Pusher.Token(key, secret);\n\n        return key + ':' + token.sign(`${socketId}:${channel.name}`);\n    }\n\n    static signTokenForPresenceChannel(\n        socketId: string,\n        channel: any,\n        channelData: any,\n        key = 'app-key',\n        secret = 'app-secret'\n    ): string {\n        let token = new Pusher.Token(key, secret);\n\n        return key + ':' + token.sign(`${socketId}:${channel.name}:${JSON.stringify(channelData)}`);\n    }\n\n    static signTokenForUserAuthentication(\n        socketId: string,\n        userData: string,\n        key = 'app-key',\n        secret = 'app-secret'\n    ): string {\n        let token = new Pusher.Token(key, secret);\n\n        return key + ':' + token.sign(`${socketId}::user::${userData}`);\n    }\n\n    static wait(ms): Promise<void> {\n        return new Promise(resolve => setTimeout(resolve, ms));\n    }\n\n    static randomChannelName(): string {\n        return `channel-${Math.floor(Math.random() * 10000000)}`;\n    }\n\n    static shouldRun(condition): jest.It {\n        return condition ? it : it.skip;\n    }\n}\n"
  },
  {
    "path": "tests/webhooks.test.ts",
    "content": "import { App } from '../src/app';\nimport { Server } from '../src/server';\nimport { Utils } from './utils';\nimport { createWebhookHmac } from \"../src/webhook-sender\";\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('webhooks test', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('webhooks from client events', done => {\n        let webhooks = [{\n            event_types: ['client_event'],\n            url: 'http://127.0.0.1:3001/webhook',\n        }];\n\n        let channelName = `private-${Utils.randomChannelName()}`;\n        let client1;\n        let client2;\n\n        Utils.newServer({\n            'appManager.array.apps.0.enableClientMessages': true,\n            'appManager.array.apps.0.webhooks': webhooks,\n            'database.redis.keyPrefix': 'client-event-webhook',\n        }, (server: Server) => {\n            Utils.newWebhookServer((req, res) => {\n                let app = new App(server.options.appManager.array.apps[0], server);\n                let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret);\n\n                expect(req.headers['x-pusher-key']).toBe('app-key');\n                expect(req.headers['x-pusher-signature']).toBe(rightSignature);\n                expect(req.body.time_ms).toBeDefined();\n                expect(req.body.events).toBeDefined();\n                expect(req.body.events.length).toBe(1);\n\n                const webhookEvent = req.body.events[0];\n\n                expect(webhookEvent.name).toBe('client_event');\n                expect(webhookEvent.channel).toBe(channelName);\n                expect(webhookEvent.event).toBe('client-greeting');\n                expect(webhookEvent.data.message).toBe('hello');\n                expect(webhookEvent.socket_id).toBeDefined();\n\n                res.json({ ok: true });\n                client1.disconnect();\n                client2.disconnect();\n                done();\n            }, (activeHttpServer) => {\n                client1 = Utils.newClientForPrivateChannel();\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        client2 = Utils.newClientForPrivateChannel();\n\n                        client2.connection.bind('connected', () => {\n                            let channel = client2.subscribe(channelName);\n\n                            channel.bind('pusher:subscription_succeeded', () => {\n                                channel.trigger('client-greeting', {\n                                    message: 'hello',\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    }, 60 * 1000);\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('webhooks from channel_occupied and channel_vacated', done => {\n        let webhooks = [{\n            event_types: ['channel_occupied', 'channel_vacated'],\n            url: 'http://127.0.0.1:3001/webhook',\n        }];\n\n        let channelName = `private-${Utils.randomChannelName()}`;\n        let client = Utils.newClientForPrivateChannel();\n\n        Utils.newServer({\n            'appManager.array.apps.0.webhooks': webhooks,\n            'database.redis.keyPrefix': 'channel-webhooks',\n        }, (server: Server) => {\n            Utils.newWebhookServer((req, res) => {\n                let app = new App(server.options.appManager.array.apps[0], server);\n                let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret);\n\n                expect(req.headers['x-pusher-key']).toBe('app-key');\n                expect(req.headers['x-pusher-signature']).toBe(rightSignature);\n                expect(req.body.time_ms).toBeDefined();\n                expect(req.body.events).toBeDefined();\n                expect(req.body.events.length).toBe(1);\n\n                const webhookEvent = req.body.events[0];\n\n                if (webhookEvent.name === 'channel_occupied') {\n                    expect(webhookEvent.channel).toBe(channelName);\n                }\n\n                res.json({ ok: true });\n\n                if (webhookEvent.name === 'channel_vacated') {\n                    expect(webhookEvent.channel).toBe(channelName);\n                    client.disconnect();\n                    done();\n                }\n            }, (activeHttpServer) => {\n                client.connection.bind('connected', () => {\n                    let channel = client.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        client.unsubscribe(channelName);\n                    });\n                });\n            });\n        });\n    }, 60 * 1000);\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('webhooks from member_added and member_removed', done => {\n        let webhooks = [{\n            event_types: ['member_added', 'member_removed'],\n            url: 'http://127.0.0.1:3001/webhook',\n        }];\n\n        let john = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        let alice = {\n            user_id: 2,\n            user_info: {\n                id: 2,\n                name: 'Alice',\n            },\n        };\n\n        let channelName = `presence-${Utils.randomChannelName()}`;\n        let johnClient;\n        let aliceClient;\n\n        Utils.newServer({\n            'appManager.array.apps.0.webhooks': webhooks,\n            'database.redis.keyPrefix': 'presence-webhooks',\n        }, (server: Server) => {\n            Utils.newWebhookServer((req, res) => {\n                let app = new App(server.options.appManager.array.apps[0], server);\n                let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret);\n\n                expect(req.headers['x-pusher-key']).toBe('app-key');\n                expect(req.headers['x-pusher-signature']).toBe(rightSignature);\n                expect(req.body.time_ms).toBeDefined();\n                expect(req.body.events).toBeDefined();\n                expect(req.body.events.length).toBe(1);\n\n                const webhookEvent = req.body.events[0];\n\n                if (req.body.name === 'member_added') {\n                    expect(webhookEvent.channel).toBe(channelName);\n                    expect(webhookEvent.user_id).toBe(2);\n                    expect([1, 2].includes(webhookEvent.user_id)).toBe(true);\n                }\n\n                res.json({ ok: true });\n\n                if (webhookEvent.name === 'member_removed') {\n                    expect(webhookEvent.channel).toBe(channelName);\n                    expect(webhookEvent.user_id).toBe(2);\n                    johnClient.disconnect();\n                    done();\n                }\n            }, (activeHttpServer) => {\n                johnClient = Utils.newClientForPresenceUser(john);\n\n                johnClient.connection.bind('connected', () => {\n                    let johnChannel = johnClient.subscribe(channelName);\n\n                    johnChannel.bind('pusher:subscription_succeeded', (data) => {\n                        expect(data.count).toBe(1);\n                        expect(data.me.id).toBe(1);\n                        expect(data.members['1'].id).toBe(1);\n                        expect(data.me.info.name).toBe('John');\n\n                        aliceClient = Utils.newClientForPresenceUser(alice);\n\n                        aliceClient.connection.bind('connected', () => {\n                            let aliceChannel = aliceClient.subscribe(channelName);\n\n                            aliceChannel.bind('pusher:subscription_succeeded', (data) => {\n                                expect(data.count).toBe(2);\n                                expect(data.me.id).toBe(2);\n                                expect(data.members['1'].id).toBe(1);\n                                expect(data.members['2'].id).toBe(2);\n                                expect(data.me.info.name).toBe('Alice');\n                                aliceClient.disconnect();\n                            });\n                        });\n                    });\n\n                    johnChannel.bind('pusher:member_added', data => {\n                        expect(data.id).toBe(2);\n                        expect(data.info.name).toBe('Alice');\n                    });\n\n                    johnChannel.bind('pusher:member_removed', data => {\n                        expect(data.id).toBe(2);\n                        expect(data.info.name).toBe('Alice');\n                    });\n                });\n            });\n        });\n    }, 60 * 1000);\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('webhooks from member_added and member_removed alongside filtering', done => {\n        let channelName = `presence-${Utils.randomChannelName()}`;\n\n        let webhooks = [\n            {\n                event_types: ['member_added'],\n                url: 'http://127.0.0.1:3001/webhook',\n                filter: {\n                    channel_name_starts_with: channelName,\n                },\n            },\n            {\n                event_types: ['member_removed'],\n                url: 'http://127.0.0.1:3001/webhook',\n                filter: {\n                    channel_name_starts_with: channelName,\n                },\n            },\n        ];\n\n        let john = {\n            user_id: 1,\n            user_info: {\n                id: 1,\n                name: 'John',\n            },\n        };\n\n        let alice = {\n            user_id: 2,\n            user_info: {\n                id: 2,\n                name: 'Alice',\n            },\n        };\n\n        let johnClient;\n        let aliceClient;\n\n        Utils.newServer({\n            'appManager.array.apps.0.webhooks': webhooks,\n            'database.redis.keyPrefix': 'presence-webhooks',\n        }, (server: Server) => {\n            Utils.newWebhookServer((req, res) => {\n                let app = new App(server.options.appManager.array.apps[0], server);\n                let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret);\n\n                expect(req.headers['x-pusher-key']).toBe('app-key');\n                expect(req.headers['x-pusher-signature']).toBe(rightSignature);\n                expect(req.body.time_ms).toBeDefined();\n                expect(req.body.events).toBeDefined();\n                expect(req.body.events.length).toBe(1);\n\n                const webhookEvent = req.body.events[0];\n\n                if (req.body.name === 'member_added') {\n                    expect(webhookEvent.channel).toBe(channelName);\n                    expect(webhookEvent.user_id).toBe(2);\n                    expect([1, 2].includes(webhookEvent.user_id)).toBe(true);\n                }\n\n                res.json({ ok: true });\n\n                if (webhookEvent.name === 'member_removed') {\n                    expect(webhookEvent.channel).toBe(channelName);\n                    expect(webhookEvent.user_id).toBe(2);\n                    johnClient.disconnect();\n                    done();\n                }\n            }, (activeHttpServer) => {\n                johnClient = Utils.newClientForPresenceUser(john);\n\n                johnClient.connection.bind('connected', () => {\n                    let johnChannel = johnClient.subscribe(channelName);\n\n                    johnChannel.bind('pusher:subscription_succeeded', (data) => {\n                        expect(data.count).toBe(1);\n                        expect(data.me.id).toBe(1);\n                        expect(data.members['1'].id).toBe(1);\n                        expect(data.me.info.name).toBe('John');\n\n                        aliceClient = Utils.newClientForPresenceUser(alice);\n\n                        aliceClient.connection.bind('connected', () => {\n                            let aliceChannel = aliceClient.subscribe(channelName);\n\n                            aliceChannel.bind('pusher:subscription_succeeded', (data) => {\n                                expect(data.count).toBe(2);\n                                expect(data.me.id).toBe(2);\n                                expect(data.members['1'].id).toBe(1);\n                                expect(data.members['2'].id).toBe(2);\n                                expect(data.me.info.name).toBe('Alice');\n                                aliceClient.disconnect();\n                            });\n                        });\n                    });\n\n                    johnChannel.bind('pusher:member_added', data => {\n                        expect(data.id).toBe(2);\n                        expect(data.info.name).toBe('Alice');\n                    });\n\n                    johnChannel.bind('pusher:member_removed', data => {\n                        expect(data.id).toBe(2);\n                        expect(data.info.name).toBe('Alice');\n                    });\n                });\n            });\n        });\n    }, 60 * 1000);\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('lambda webhooks', done => {\n        let webhooks = [{\n            event_types: ['client_event'],\n            lambda_function: 'some-lambda-function',\n            lambda: {\n                client_options: {\n                    endpoint: 'http://127.0.0.1:3001',\n                },\n            },\n        }];\n\n        let channelName = `private-${Utils.randomChannelName()}`;\n        let client1;\n        let client2;\n\n        Utils.newServer({\n            'appManager.array.apps.0.enableClientMessages': true,\n            'appManager.array.apps.0.webhooks': webhooks,\n            'database.redis.keyPrefix': 'client-event-webhook',\n        }, (server: Server) => {\n            Utils.newWebhookServer((req, res) => {\n                // Mocking the AWS endpoint as our webhook so that we can test\n                // the fact that the AWS client sends the webhook through Lambda.\n                expect(req.originalUrl).toBe('/2015-03-31/functions/some-lambda-function/invocations');\n\n                res.json({ ok: true });\n                client1.disconnect();\n                client2.disconnect();\n                done();\n            }, (activeHttpServer) => {\n                client1 = Utils.newClientForPrivateChannel();\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        client2 = Utils.newClientForPrivateChannel();\n\n                        client2.connection.bind('connected', () => {\n                            let channel = client2.subscribe(channelName);\n\n                            channel.bind('pusher:subscription_succeeded', () => {\n                                channel.trigger('client-greeting', {\n                                    message: 'hello',\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    }, 60 * 1000);\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('webhooks filtered by channel name', done => {\n        const sharedWebhookConfig = {\n            event_types: ['channel_occupied'],\n            url: 'http://127.0.0.1:3001/webhook',\n        };\n\n        const webhooks = [\n            {\n                ...sharedWebhookConfig,\n                filter: {\n                    channel_name_starts_with: 'private-',\n                },\n            },\n            {\n                ...sharedWebhookConfig,\n                filter: {\n                    channel_name_starts_with: 'private-',\n                    channel_name_ends_with: '-foo',\n                },\n            },\n            {\n                ...sharedWebhookConfig,\n                filter: {\n                    channel_name_ends_with: '-bar',\n                },\n            },\n        ];\n\n        // We expect the webhook to be called 1 time for these channels\n        const matchedChannels = [\n            `private-${Utils.randomChannelName()}`,\n            `private-${Utils.randomChannelName()}-foo`,\n            `${Utils.randomChannelName()}-bar`,\n        ];\n\n        // We don't expect any webhooks to be called for these channels\n        const unmatchedChannels = [\n            `public-${Utils.randomChannelName()}`,\n            `public-${Utils.randomChannelName()}-foo`,\n            `${Utils.randomChannelName()}-foo`,\n        ];\n\n        let client = Utils.newClientForPrivateChannel();\n\n        Utils.newServer({\n            'appManager.array.apps.0.webhooks': webhooks,\n            'database.redis.keyPrefix': 'channel-webhooks',\n        }, (server: Server) => {\n            let receivedWebhookRequests = 0;\n\n            Utils.newWebhookServer((req, res) => {\n                let app = new App(server.options.appManager.array.apps[0], server);\n                let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret);\n\n                expect(req.headers['x-pusher-key']).toBe('app-key');\n                expect(req.headers['x-pusher-signature']).toBe(rightSignature);\n                expect(req.body.time_ms).toBeDefined();\n                expect(req.body.events).toBeDefined();\n                expect(req.body.events.length).toBe(1);\n\n                req.body.events.forEach(webhookEvent => {\n                    if (matchedChannels.includes(webhookEvent.channel)) {\n                        receivedWebhookRequests += 1;\n                    }\n\n                    if (receivedWebhookRequests >= matchedChannels.length) {\n                        done();\n                        client.disconnect();\n                    }\n                });\n\n                res.json({ ok: true });\n            }, (activeHttpServer) => {\n                client.connection.bind('connected', () => {\n                    [...unmatchedChannels, ...matchedChannels].forEach(channelName => client.subscribe(channelName));\n                });\n            });\n        });\n    }, 60 * 1000);\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('webhooks can have custom headers', done => {\n        const webhooks = [{\n            event_types: ['channel_occupied'],\n            url: 'http://127.0.0.1:3001/webhook',\n            headers: {\n                'X-Custom-Header': 'custom-value',\n                // These headers below should not be sent with `custom-value`\n                'X-Pusher-Key': 'custom-value',\n                'X-Pusher-Signature': 'custom-value',\n            },\n        }];\n\n        const channelName = `private-${Utils.randomChannelName()}`;\n        let client = Utils.newClientForPrivateChannel();\n\n        Utils.newServer({\n            'appManager.array.apps.0.webhooks': webhooks,\n            'database.redis.keyPrefix': 'channel-webhooks',\n        }, (server: Server) => {\n            Utils.newWebhookServer((req, res) => {\n                let app = new App(server.options.appManager.array.apps[0], server);\n                let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret);\n\n                expect(req.headers['x-pusher-key']).toBe('app-key');\n                expect(req.headers['x-pusher-signature']).toBe(rightSignature);\n                expect(req.headers['x-custom-header']).toBe('custom-value');\n                expect(req.body.time_ms).toBeDefined();\n                expect(req.body.events).toBeDefined();\n                expect(req.body.events.length).toBe(1);\n\n                res.json({ ok: true });\n                client.disconnect();\n                done();\n            }, (activeHttpServer) => {\n                client.connection.bind('connected', () => {\n                    client.subscribe(channelName);\n                });\n            });\n        });\n    }, 60 * 1000);\n\n    Utils.shouldRun(Utils.appManagerIs('array') && Utils.queueDriverIs('sqs'))('sqs batching', done => {\n        let webhooks = [{\n            event_types: ['client_event'],\n            url: 'http://127.0.0.1:3001/webhook',\n        }];\n\n        let channelName = `private-${Utils.randomChannelName()}`;\n        let client1;\n        let client2;\n\n        Utils.newServer({\n            'appManager.array.apps.0.enableClientMessages': true,\n            'appManager.array.apps.0.webhooks': webhooks,\n            'database.redis.keyPrefix': 'client-event-webhook',\n            'queue.sqs.processBatch': true,\n            'queue.sqs.batchSize': 2,\n            'queue.sqs.pollingWaitTimeMs': 1000,\n        }, (server: Server) => {\n            Utils.newWebhookServer((req, res) => {\n                let app = new App(server.options.appManager.array.apps[0], server);\n                let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret);\n\n                expect(req.headers['x-pusher-key']).toBe('app-key');\n                expect(req.headers['x-pusher-signature']).toBe(rightSignature);\n                expect(req.body.time_ms).toBeDefined();\n                expect(req.body.events).toBeDefined();\n                expect(req.body.events.length).toBe(1);\n\n                const webhookEvent = req.body.events[0];\n\n                expect(webhookEvent.name).toBe('client_event');\n                expect(webhookEvent.channel).toBe(channelName);\n                expect(webhookEvent.event).toBe('client-greeting');\n                expect(webhookEvent.data.message).toBe('hello');\n                expect(webhookEvent.socket_id).toBeDefined();\n\n                res.json({ ok: true });\n                client1.disconnect();\n                client2.disconnect();\n                done();\n            }, (activeHttpServer) => {\n                client1 = Utils.newClientForPrivateChannel();\n\n                client1.connection.bind('connected', () => {\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        client2 = Utils.newClientForPrivateChannel();\n\n                        client2.connection.bind('connected', () => {\n                            let channel = client2.subscribe(channelName);\n\n                            channel.bind('pusher:subscription_succeeded', () => {\n                                channel.trigger('client-greeting', {\n                                    message: 'hello',\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    }, 60 * 1000);\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('webhooks from cache_miss', done => {\n        let webhooks = [{\n            event_types: ['cache_miss'],\n            url: 'http://127.0.0.1:3001/webhook',\n        }];\n\n        let channelName = `private-cache-${Utils.randomChannelName()}`;\n        let client = Utils.newClientForPrivateChannel();\n\n        Utils.newServer({\n            'appManager.array.apps.0.webhooks': webhooks,\n            'database.redis.keyPrefix': 'client-event-cache-miss',\n        }, (server: Server) => {\n            Utils.newWebhookServer((req, res) => {\n                let app = new App(server.options.appManager.array.apps[0], server);\n                let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret);\n\n                expect(req.headers['x-pusher-key']).toBe('app-key');\n                expect(req.headers['x-pusher-signature']).toBe(rightSignature);\n                expect(req.body.time_ms).toBeDefined();\n                expect(req.body.events).toBeDefined();\n                expect(req.body.events.length).toBe(1);\n\n                const webhookEvent = req.body.events[0];\n\n                if (webhookEvent.name === 'cache_miss') {\n                    expect(webhookEvent.channel).toBe(channelName);\n                    client.disconnect();\n                    done();\n                }\n\n                res.json({ ok: true });\n            }, (activeHttpServer) => {\n                client.connection.bind('connected', () => {\n                    client.subscribe(channelName);\n                });\n            });\n        });\n    }, 20_000);\n});\n"
  },
  {
    "path": "tests/ws.cluster-adapter.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('ws test for cluster adapter', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('client events with cluster adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel();\n                let client2;\n                let channelName = `private-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === 'client-greeting' && channel === channelName) {\n                            expect(data.message).toBe('hello');\n                            client1.disconnect();\n                            client2.disconnect();\n                            done();\n                        }\n                    });\n\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        Utils.wait(3000).then(() => {\n                            client2 = Utils.newClientForPrivateChannel({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    channel.trigger('client-greeting', {\n                                        message: 'hello',\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('client events dont get emitted when client messaging is disabled with cluster adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': false }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': false, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel();\n                let channelName = `private-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === 'client-greeting' && channel === channelName) {\n                            throw new Error('The message was actually sent.');\n                        }\n                    });\n\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        Utils.wait(3000).then(() => {\n                            let client2 = Utils.newClientForPrivateChannel({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    channel.bind('pusher:error', (error) => {\n                                        expect(error.code).toBe(4301);\n                                        client1.disconnect();\n                                        client2.disconnect();\n                                        done();\n                                    });\n\n                                    channel.trigger('client-greeting', {\n                                        message: 'hello',\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('client events dont get emitted when event name is big with cluster adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel();\n                let channelName = `private-${Utils.randomChannelName()}`;\n                let eventName = 'client-a8hsuNFXUhfStiWE02R'; // 26 characters\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === eventName && channel === channelName) {\n                            throw new Error('The message was actually sent.');\n                        }\n                    });\n\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        Utils.wait(3000).then(() => {\n                            let client2 = Utils.newClientForPrivateChannel({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    channel.bind('pusher:error', (error) => {\n                                        expect(error.code).toBe(4301);\n                                        client1.disconnect();\n                                        client2.disconnect();\n                                        done();\n                                    });\n\n                                    channel.trigger(eventName, {\n                                        message: 'hello',\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('client events dont get emitted when event payload is big with cluster adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel();\n                let channelName = `private-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === 'client-greeting' && channel === channelName) {\n                            throw new Error('The message was actually sent.');\n                        }\n                    });\n\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        Utils.wait(3000).then(() => {\n                            let client2 = Utils.newClientForPrivateChannel({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    channel.bind('pusher:error', (error) => {\n                                        expect(error.code).toBe(4301);\n                                        client1.disconnect();\n                                        client2.disconnect();\n                                        done();\n                                    });\n\n                                    channel.trigger('client-greeting', {\n                                        message: 'hello',\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('throw over quota error if reached connection limit for cluster adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.maxConnections': 1, port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.maxConnections': 1, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient({}, 6001, 'app-key', false);\n\n                client1.connection.bind('connected', () => {\n                    Utils.wait(3000).then(() => {\n                        let client2 = Utils.newClient({}, 6002, 'app-key', false);\n\n                        client2.connection.bind('state_change', ({ current }) => {\n                            if (current === 'failed') {\n                                client1.disconnect();\n                                done();\n                            } else {\n                                throw new Error(`${current} is not an expected state.`);\n                            }\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster'))('should check for presence.maxMembersPerChannel for cluster adapter', done => {\n        Utils.newServer({ 'presence.maxMembersPerChannel': 1, port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'presence.maxMembersPerChannel': 1, port: 6002 }, (server2: Server) => {\n                let user1 = {\n                    user_id: 1,\n                    user_info: {\n                        id: 1,\n                        name: 'John',\n                    },\n                };\n\n                let user2 = {\n                    user_id: 2,\n                    user_info: {\n                        id: 2,\n                        name: 'Alice',\n                    },\n                };\n\n                let client1 = Utils.newClientForPresenceUser(user1);\n                let client2 = Utils.newClientForPresenceUser(user2, {}, 6002);\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    let channel1 = client1.subscribe(channelName);\n\n                    channel1.bind('pusher:subscription_succeeded', () => {\n                        Utils.wait(3000).then(() => {\n                            client2.connection.bind('message', ({ event, channel, data }) => {\n                                if (event === 'pusher:subscription_error' && channel === channelName) {\n                                    expect(data.type).toBe('LimitReached');\n                                    expect(data.status).toBe(4100);\n                                    expect(data.error).toBeDefined();\n                                    client1.disconnect();\n                                    client2.disconnect();\n                                    done();\n                                }\n                            });\n\n                            client2.subscribe(channelName);\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster'))('adapter getSockets works with cluster adapter', done => {\n        Utils.newServer({}, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient();\n\n                client1.connection.bind('connected', () => {\n                    Utils.wait(3000).then(() => {\n                        server1.adapter.getSockets('app-id').then(sockets => {\n                            expect(sockets.size).toBe(1);\n\n                            let client2 = Utils.newClient({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                server1.adapter.getSockets('app-id').then(sockets => {\n                                    expect(sockets.size).toBe(2);\n                                    client1.disconnect();\n                                    client2.disconnect();\n                                    done();\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('cluster'))('adapter getChannelSockets works with cluster adapter', done => {\n        Utils.newServer({}, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient();\n                let channelName = Utils.randomChannelName();\n\n                client1.connection.bind('connected', () => {\n                    server1.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                        expect(sockets.size).toBe(0);\n\n                        let channel1 = client1.subscribe(channelName);\n\n                        channel1.bind('pusher:subscription_succeeded', () => {\n                            Utils.wait(3000).then(() => {\n                                server1.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                                    expect(sockets.size).toBe(1);\n\n                                    let client2 = Utils.newClient({}, 6002);\n\n                                    client2.connection.bind('connected', () => {\n                                        let channel2 = client2.subscribe(channelName);\n\n                                        channel2.bind('pusher:subscription_succeeded', () => {\n                                            Utils.wait(3000).then(() => {\n                                                server1.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                                                    expect(sockets.size).toBe(2);\n\n                                                    client2.unsubscribe(channelName);\n\n                                                    Utils.wait(3000).then(() => {\n                                                        server1.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                                                            expect(sockets.size).toBe(1);\n                                                            client1.disconnect();\n                                                            client2.disconnect();\n                                                            done();\n                                                        });\n                                                    });\n                                                });\n                                            });\n                                        });\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/ws.nats-adapter.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('ws test for nats adapter', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('client events with nats adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel();\n                let client2;\n                let channelName = `private-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === 'client-greeting' && channel === channelName) {\n                            expect(data.message).toBe('hello');\n                            client1.disconnect();\n                            client2.disconnect();\n                            done();\n                        }\n                    });\n\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        Utils.wait(3000).then(() => {\n                            client2 = Utils.newClientForPrivateChannel({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    channel.trigger('client-greeting', {\n                                        message: 'hello',\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('client events dont get emitted when client messaging is disabled with nats adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': false }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': false, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel();\n                let channelName = `private-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === 'client-greeting' && channel === channelName) {\n                            throw new Error('The message was actually sent.');\n                        }\n                    });\n\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        Utils.wait(3000).then(() => {\n                            let client2 = Utils.newClientForPrivateChannel({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    channel.bind('pusher:error', (error) => {\n                                        expect(error.code).toBe(4301);\n                                        client1.disconnect();\n                                        client2.disconnect();\n                                        done();\n                                    });\n\n                                    channel.trigger('client-greeting', {\n                                        message: 'hello',\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('client events dont get emitted when event name is big with nats adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel();\n                let channelName = `private-${Utils.randomChannelName()}`;\n                let eventName = 'client-a8hsuNFXUhfStiWE02R'; // 26 characters\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === eventName && channel === channelName) {\n                            throw new Error('The message was actually sent.');\n                        }\n                    });\n\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        Utils.wait(3000).then(() => {\n                            let client2 = Utils.newClientForPrivateChannel({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    channel.bind('pusher:error', (error) => {\n                                        expect(error.code).toBe(4301);\n                                        client1.disconnect();\n                                        client2.disconnect();\n                                        done();\n                                    });\n\n                                    channel.trigger(eventName, {\n                                        message: 'hello',\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('client events dont get emitted when event payload is big with nats adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel();\n                let channelName = `private-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === 'client-greeting' && channel === channelName) {\n                            throw new Error('The message was actually sent.');\n                        }\n                    });\n\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        Utils.wait(3000).then(() => {\n                            let client2 = Utils.newClientForPrivateChannel({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                let channel = client2.subscribe(channelName);\n\n                                channel.bind('pusher:subscription_succeeded', () => {\n                                    channel.bind('pusher:error', (error) => {\n                                        expect(error.code).toBe(4301);\n                                        client1.disconnect();\n                                        client2.disconnect();\n                                        done();\n                                    });\n\n                                    channel.trigger('client-greeting', {\n                                        message: 'hello',\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('throw over quota error if reached connection limit for nats adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.maxConnections': 1, port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.maxConnections': 1, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient({}, 6001, 'app-key', false);\n\n                client1.connection.bind('connected', () => {\n                    Utils.wait(3000).then(() => {\n                        let client2 = Utils.newClient({}, 6002, 'app-key', false);\n\n                        client2.connection.bind('state_change', ({ current }) => {\n                            if (current === 'failed') {\n                                client1.disconnect();\n                                done();\n                            } else {\n                                throw new Error(`${current} is not an expected state.`);\n                            }\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats'))('should check for presence.maxMembersPerChannel for nats adapter', done => {\n        Utils.newServer({ 'presence.maxMembersPerChannel': 1, port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'presence.maxMembersPerChannel': 1, port: 6002 }, (server2: Server) => {\n                let user1 = {\n                    user_id: 1,\n                    user_info: {\n                        id: 1,\n                        name: 'John',\n                    },\n                };\n\n                let user2 = {\n                    user_id: 2,\n                    user_info: {\n                        id: 2,\n                        name: 'Alice',\n                    },\n                };\n\n                let client1 = Utils.newClientForPresenceUser(user1);\n                let client2 = Utils.newClientForPresenceUser(user2, {}, 6002);\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    let channel1 = client1.subscribe(channelName);\n\n                    channel1.bind('pusher:subscription_succeeded', () => {\n                        Utils.wait(3000).then(() => {\n                            client2.connection.bind('message', ({ event, channel, data }) => {\n                                if (event === 'pusher:subscription_error' && channel === channelName) {\n                                    expect(data.type).toBe('LimitReached');\n                                    expect(data.status).toBe(4100);\n                                    expect(data.error).toBeDefined();\n                                    client1.disconnect();\n                                    client2.disconnect();\n                                    done();\n                                }\n                            });\n\n                            client2.subscribe(channelName);\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats'))('adapter getSockets works with nats adapter', done => {\n        Utils.newServer({}, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient();\n\n                client1.connection.bind('connected', () => {\n                    Utils.wait(3000).then(() => {\n                        server1.adapter.getSockets('app-id').then(sockets => {\n                            expect(sockets.size).toBe(1);\n\n                            let client2 = Utils.newClient({}, 6002);\n\n                            client2.connection.bind('connected', () => {\n                                server1.adapter.getSockets('app-id').then(sockets => {\n                                    expect(sockets.size).toBe(2);\n                                    client1.disconnect();\n                                    client2.disconnect();\n                                    done();\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('nats'))('adapter getChannelSockets works with nats adapter', done => {\n        Utils.newServer({}, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient();\n                let channelName = Utils.randomChannelName();\n\n                client1.connection.bind('connected', () => {\n                    server1.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                        expect(sockets.size).toBe(0);\n\n                        let channel1 = client1.subscribe(channelName);\n\n                        channel1.bind('pusher:subscription_succeeded', () => {\n                            Utils.wait(3000).then(() => {\n                                server1.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                                    expect(sockets.size).toBe(1);\n\n                                    let client2 = Utils.newClient({}, 6002);\n\n                                    client2.connection.bind('connected', () => {\n                                        let channel2 = client2.subscribe(channelName);\n\n                                        channel2.bind('pusher:subscription_succeeded', () => {\n                                            Utils.wait(3000).then(() => {\n                                                server1.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                                                    expect(sockets.size).toBe(2);\n\n                                                    client2.unsubscribe(channelName);\n\n                                                    Utils.wait(3000).then(() => {\n                                                        server1.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                                                            expect(sockets.size).toBe(1);\n                                                            client1.disconnect();\n                                                            client2.disconnect();\n                                                            done();\n                                                        });\n                                                    });\n                                                });\n                                            });\n                                        });\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/ws.redis-adapter.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('ws test for redis adapter', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('client events with redis adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel();\n                let client2;\n                let channelName = `private-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === 'client-greeting' && channel === channelName) {\n                            expect(data.message).toBe('hello');\n                            client1.disconnect();\n                            client2.disconnect();\n                            done();\n                        }\n                    });\n\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        client2 = Utils.newClientForPrivateChannel({}, 6002);\n\n                        client2.connection.bind('connected', () => {\n                            let channel = client2.subscribe(channelName);\n\n                            channel.bind('pusher:subscription_succeeded', () => {\n                                channel.trigger('client-greeting', {\n                                    message: 'hello',\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('client events dont get emitted when client messaging is disabled with redis adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': false }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': false, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel();\n                let channelName = `private-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === 'client-greeting' && channel === channelName) {\n                            throw new Error('The message was actually sent.');\n                        }\n                    });\n\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        let client2 = Utils.newClientForPrivateChannel({}, 6002);\n\n                        client2.connection.bind('connected', () => {\n                            let channel = client2.subscribe(channelName);\n\n                            channel.bind('pusher:subscription_succeeded', () => {\n                                channel.bind('pusher:error', (error) => {\n                                    expect(error.code).toBe(4301);\n                                    client1.disconnect();\n                                    client2.disconnect();\n                                    done();\n                                });\n\n                                channel.trigger('client-greeting', {\n                                    message: 'hello',\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('client events dont get emitted when event name is big with redis adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel();\n                let channelName = `private-${Utils.randomChannelName()}`;\n                let eventName = 'client-a8hsuNFXUhfStiWE02R'; // 26 characters\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === eventName && channel === channelName) {\n                            throw new Error('The message was actually sent.');\n                        }\n                    });\n\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        let client2 = Utils.newClientForPrivateChannel({}, 6002);\n\n                        client2.connection.bind('connected', () => {\n                            let channel = client2.subscribe(channelName);\n\n                            channel.bind('pusher:subscription_succeeded', () => {\n                                channel.bind('pusher:error', (error) => {\n                                    expect(error.code).toBe(4301);\n                                    client1.disconnect();\n                                    client2.disconnect();\n                                    done();\n                                });\n\n                                channel.trigger(eventName, {\n                                    message: 'hello',\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('client events dont get emitted when event payload is big with redis adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClientForPrivateChannel();\n                let channelName = `private-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    client1.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === 'client-greeting' && channel === channelName) {\n                            throw new Error('The message was actually sent.');\n                        }\n                    });\n\n                    let channel = client1.subscribe(channelName);\n\n                    channel.bind('pusher:subscription_succeeded', () => {\n                        let client2 = Utils.newClientForPrivateChannel({}, 6002);\n\n                        client2.connection.bind('connected', () => {\n                            let channel = client2.subscribe(channelName);\n\n                            channel.bind('pusher:subscription_succeeded', () => {\n                                channel.bind('pusher:error', (error) => {\n                                    expect(error.code).toBe(4301);\n                                    client1.disconnect();\n                                    client2.disconnect();\n                                    done();\n                                });\n\n                                channel.trigger('client-greeting', {\n                                    message: 'hello',\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('throw over quota error if reached connection limit for redis adapter', done => {\n        Utils.newServer({ 'appManager.array.apps.0.maxConnections': 1, port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'appManager.array.apps.0.maxConnections': 1, port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient({}, 6001, 'app-key', false);\n\n                client1.connection.bind('connected', () => {\n                    let client2 = Utils.newClient({}, 6002, 'app-key', false);\n\n                    client2.connection.bind('state_change', ({ current }) => {\n                        if (current === 'failed') {\n                            client1.disconnect();\n                            done();\n                        } else {\n                            throw new Error(`${current} is not an expected state.`);\n                        }\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis'))('should check for presence.maxMembersPerChannel for redis adapter', done => {\n        Utils.newServer({ 'presence.maxMembersPerChannel': 1, port: 6001 }, (server1: Server) => {\n            Utils.newClonedServer(server1, { 'presence.maxMembersPerChannel': 1, port: 6002 }, (server2: Server) => {\n                let user1 = {\n                    user_id: 1,\n                    user_info: {\n                        id: 1,\n                        name: 'John',\n                    },\n                };\n\n                let user2 = {\n                    user_id: 2,\n                    user_info: {\n                        id: 2,\n                        name: 'Alice',\n                    },\n                };\n\n                let client1 = Utils.newClientForPresenceUser(user1);\n                let client2 = Utils.newClientForPresenceUser(user2, {}, 6002);\n                let channelName = `presence-${Utils.randomChannelName()}`;\n\n                client1.connection.bind('connected', () => {\n                    let channel1 = client1.subscribe(channelName);\n\n                    channel1.bind('pusher:subscription_succeeded', () => {\n                        client2.connection.bind('message', ({ event, channel, data }) => {\n                            if (event === 'pusher:subscription_error' && channel === channelName) {\n                                expect(data.type).toBe('LimitReached');\n                                expect(data.status).toBe(4100);\n                                expect(data.error).toBeDefined();\n                                client1.disconnect();\n                                client2.disconnect();\n                                done();\n                            }\n                        });\n\n                        client2.subscribe(channelName);\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis'))('adapter getSockets works with redis adapter', done => {\n        Utils.newServer({}, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient();\n\n                client1.connection.bind('connected', () => {\n                    server1.adapter.getSockets('app-id').then(sockets => {\n                        expect(sockets.size).toBe(1);\n\n                        let client2 = Utils.newClient({}, 6002);\n\n                        client2.connection.bind('connected', () => {\n                            server1.adapter.getSockets('app-id').then(sockets => {\n                                expect(sockets.size).toBe(2);\n                                client1.disconnect();\n                                client2.disconnect();\n                                done();\n                            });\n                        });\n                    })\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.adapterIs('redis'))('adapter getChannelSockets works with redis adapter', done => {\n        Utils.newServer({}, (server1: Server) => {\n            Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => {\n                let client1 = Utils.newClient();\n                let channelName = Utils.randomChannelName();\n\n                client1.connection.bind('connected', () => {\n                    server1.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                        expect(sockets.size).toBe(0);\n\n                        let channel1 = client1.subscribe(channelName);\n\n                        channel1.bind('pusher:subscription_succeeded', () => {\n                            server1.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                                expect(sockets.size).toBe(1);\n\n                                let client2 = Utils.newClient({}, 6002);\n\n                                client2.connection.bind('connected', () => {\n                                    let channel2 = client2.subscribe(channelName);\n\n                                    channel2.bind('pusher:subscription_succeeded', () => {\n                                        server1.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                                            expect(sockets.size).toBe(2);\n\n                                            client2.unsubscribe(channelName);\n\n                                            Utils.wait(3000).then(() => {\n                                                server1.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                                                    expect(sockets.size).toBe(1);\n                                                    client1.disconnect();\n                                                    client2.disconnect();\n                                                    done();\n                                                });\n                                            });\n                                        });\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/ws.test.ts",
    "content": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_TIMES || '1'));\n\ndescribe('ws test', () => {\n    beforeEach(() => {\n        jest.resetModules();\n\n        return Utils.waitForPortsToFreeUp();\n    });\n\n    afterEach(() => {\n        return Utils.flushServers();\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('client events', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true }, (server: Server) => {\n            let client1 = Utils.newClientForPrivateChannel();\n            let client2;\n            let channelName = `private-${Utils.randomChannelName()}`;\n\n            client1.connection.bind('connected', () => {\n                client1.connection.bind('message', ({ event, channel, data }) => {\n                    if (event === 'client-greeting' && channel === channelName) {\n                        expect(data.message).toBe('hello');\n                        client1.disconnect();\n                        client2.disconnect();\n                        done();\n                    }\n                });\n\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    client2 = Utils.newClientForPrivateChannel();\n\n                    client2.connection.bind('connected', () => {\n                        let channel = client2.subscribe(channelName);\n\n                        channel.bind('pusher:subscription_succeeded', () => {\n                            channel.trigger('client-greeting', {\n                                message: 'hello',\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array') && !Utils.adapterIs('nats'))('client events for presence channels', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true }, (server: Server) => {\n            let user1 = {\n                user_id: 1,\n                user_info: {\n                    id: 1,\n                    name: 'John',\n                },\n            };\n\n            let user2 = {\n                user_id: 2,\n                user_info: {\n                    id: 2,\n                    name: 'Alice',\n                },\n            };\n\n            let client1 = Utils.newClientForPresenceUser(user1);\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            client1.connection.bind('connected', () => {\n                let client2 = Utils.newClientForPresenceUser(user2);\n\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('client-greeting', (data, metadata) => {\n                    expect(data.message).toBe('hello');\n                    expect(metadata.user_id).toBe(2);\n                    client1.disconnect();\n                    client2.disconnect();\n                    done();\n                });\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    client2.connection.bind('connected', () => {\n                        let channel = client2.subscribe(channelName);\n\n                        channel.bind('pusher:subscription_succeeded', () => {\n                            channel.trigger('client-greeting', { message: 'hello' });\n                        });\n                    });\n                });\n            });\n        });\n    }, 60_000);\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('client events dont get emitted when client messaging is disabled', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': false }, (server: Server) => {\n            let client1 = Utils.newClientForPrivateChannel();\n            let channelName = `private-${Utils.randomChannelName()}`;\n\n            client1.connection.bind('connected', () => {\n                client1.connection.bind('message', ({ event, channel, data }) => {\n                    if (event === 'client-greeting' && channel === channelName) {\n                        throw new Error('The message was actually sent.');\n                    }\n                });\n\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    let client2 = Utils.newClientForPrivateChannel();\n\n                    client2.connection.bind('connected', () => {\n                        let channel = client2.subscribe(channelName);\n\n                        channel.bind('pusher:subscription_succeeded', () => {\n                            channel.bind('pusher:error', (error) => {\n                                expect(error.code).toBe(4301);\n                                client1.disconnect();\n                                client2.disconnect();\n                                done();\n                            });\n\n                            channel.trigger('client-greeting', {\n                                message: 'hello',\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('client events dont get emitted when event name is big', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25 }, (server: Server) => {\n            let client1 = Utils.newClientForPrivateChannel();\n            let channelName = `private-${Utils.randomChannelName()}`;\n            let eventName = 'client-a8hsuNFXUhfStiWE02R'; // 26 characters\n\n            client1.connection.bind('connected', () => {\n                client1.connection.bind('message', ({ event, channel, data }) => {\n                    if (event === eventName && channel === channelName) {\n                        throw new Error('The message was actually sent.');\n                    }\n                });\n\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    let client2 = Utils.newClientForPrivateChannel();\n\n                    client2.connection.bind('connected', () => {\n                        let channel = client2.subscribe(channelName);\n\n                        channel.bind('pusher:subscription_succeeded', () => {\n                            channel.bind('pusher:error', (error) => {\n                                expect(error.code).toBe(4301);\n                                client1.disconnect();\n                                client2.disconnect();\n                                done();\n                            });\n\n                            channel.trigger(eventName, {\n                                message: 'hello',\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('client events dont get emitted when event payload is big', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024 }, (server: Server) => {\n            let client1 = Utils.newClientForPrivateChannel();\n            let channelName = `private-${Utils.randomChannelName()}`;\n\n            client1.connection.bind('connected', () => {\n                client1.connection.bind('message', ({ event, channel, data }) => {\n                    if (event === 'client-greeting' && channel === channelName) {\n                        throw new Error('The message was actually sent.');\n                    }\n                });\n\n                let channel = client1.subscribe(channelName);\n\n                channel.bind('pusher:subscription_succeeded', () => {\n                    let client2 = Utils.newClientForPrivateChannel({});\n\n                    client2.connection.bind('connected', () => {\n                        let channel = client2.subscribe(channelName);\n\n                        channel.bind('pusher:subscription_succeeded', () => {\n                            channel.bind('pusher:error', (error) => {\n                                expect(error.code).toBe(4301);\n                                client1.disconnect();\n                                client2.disconnect();\n                                done();\n                            });\n\n                            channel.trigger('client-greeting', {\n                                message: 'hello',\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    test('cannot connect using invalid app key', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client = Utils.newClient({}, 6001, 'invalid-key', false);\n\n            client.connection.bind('state_change', ({ current }) => {\n                if (['unavailable', 'failed', 'disconnected'].includes(current)) {\n                    done();\n                } else {\n                    throw new Error(`${current} is not an expected state.`);\n                }\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('throw over quota error if reached connection limit', done => {\n        Utils.newServer({ 'appManager.array.apps.0.maxConnections': 1 }, (server: Server) => {\n            let client1 = Utils.newClient({}, 6001, 'app-key', false);\n\n            client1.connection.bind('connected', () => {\n                let client2 = Utils.newClient({}, 6001, 'app-key', false);\n\n                client2.connection.bind('state_change', ({ current }) => {\n                    if (['unavailable', 'failed', 'disconnected'].includes(current)) {\n                        client1.disconnect();\n                        done();\n                    } else {\n                        throw new Error(`${current} is not an expected state.`);\n                    }\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('throw invalid app error if app is deactivated', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enabled': false }, (server: Server) => {\n            let client = Utils.newClient();\n\n            client.connection.bind('state_change', ({ current }) => {\n                if (['unavailable', 'failed', 'disconnected'].includes(current)) {\n                    done();\n                } else {\n                    throw new Error(`${current} is not an expected state.`);\n                }\n            });\n        });\n    });\n\n    test('should check for channelLimits.maxNameLength', done => {\n        Utils.newServer({ 'channelLimits.maxNameLength': 25 }, (server: Server) => {\n            let client = Utils.newClient();\n\n            client.connection.bind('connected', () => {\n                let channelName = 'a8hsuNFXUhfS1zoyvtDtiWE02Ra'; // 26 characters\n\n                client.subscribe(channelName);\n\n                client.connection.bind('message', ({ event, channel, data }) => {\n                    if (event === 'pusher:subscription_error' && channel === channelName) {\n                        expect(data.type).toBe('LimitReached');\n                        expect(data.status).toBe(4009);\n                        expect(data.error).toBeDefined();\n                        client.disconnect();\n                        done();\n                    }\n                });\n            });\n        });\n    });\n\n    test('should check for presence.maxMemberSizeInKb', done => {\n        Utils.newServer({ 'presence.maxMemberSizeInKb': 1/1024/1024 }, (server: Server) => {\n            let user = {\n                user_id: 1,\n                user_info: {\n                    id: 1,\n                    name: 'John',\n                },\n            };\n\n            let client = Utils.newClientForPresenceUser(user);\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            client.connection.bind('connected', () => {\n                client.subscribe(channelName);\n\n                client.connection.bind('message', ({ event, channel, data }) => {\n                    if (event === 'pusher:subscription_error' && channel === channelName) {\n                        expect(data.type).toBe('LimitReached');\n                        expect(data.status).toBe(4301);\n                        expect(data.error).toBeDefined();\n                        client.disconnect();\n                        done();\n                    }\n                });\n            });\n        });\n    });\n\n    test('should check for presence.maxMembersPerChannel', done => {\n        Utils.newServer({ 'presence.maxMembersPerChannel': 1 }, (server: Server) => {\n            let user1 = {\n                user_id: 1,\n                user_info: {\n                    id: 1,\n                    name: 'John',\n                },\n            };\n\n            let user2 = {\n                user_id: 2,\n                user_info: {\n                    id: 2,\n                    name: 'Alice',\n                },\n            };\n\n            let client1 = Utils.newClientForPresenceUser(user1);\n            let client2 = Utils.newClientForPresenceUser(user2);\n            let channelName = `presence-${Utils.randomChannelName()}`;\n\n            client1.connection.bind('connected', () => {\n                let channel1 = client1.subscribe(channelName);\n\n                channel1.bind('pusher:subscription_succeeded', () => {\n                    client2.connection.bind('message', ({ event, channel, data }) => {\n                        if (event === 'pusher:subscription_error' && channel === channelName) {\n                            expect(data.type).toBe('LimitReached');\n                            expect(data.status).toBe(4100);\n                            expect(data.error).toBeDefined();\n                            client1.disconnect();\n                            client2.disconnect();\n                            done();\n                        }\n                    });\n\n                    client2.subscribe(channelName);\n                });\n            });\n        });\n    });\n\n    test('adapter getSockets works', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client1 = Utils.newClient();\n\n            client1.connection.bind('connected', () => {\n                server.adapter.getSockets('app-id').then(sockets => {\n                    expect(sockets.size).toBe(1);\n\n                    let client2 = Utils.newClient();\n\n                    client2.connection.bind('connected', () => {\n                        server.adapter.getSockets('app-id').then(sockets => {\n                            expect(sockets.size).toBe(2);\n                            client1.disconnect();\n                            client2.disconnect();\n                            done();\n                        });\n                    });\n                })\n            });\n        });\n    });\n\n    test('adapter getChannelSockets works', done => {\n        Utils.newServer({}, (server: Server) => {\n            let client1 = Utils.newClient();\n            let channelName = Utils.randomChannelName();\n\n            client1.connection.bind('connected', () => {\n                server.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                    expect(sockets.size).toBe(0);\n\n                    let client1 = Utils.newClient();\n                    let channel1 = client1.subscribe(channelName);\n\n                    channel1.bind('pusher:subscription_succeeded', () => {\n                        server.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                            expect(sockets.size).toBe(1);\n\n                            let client2 = Utils.newClient();\n\n                            client2.connection.bind('connected', () => {\n                                let channel2 = client2.subscribe(channelName);\n\n                                channel2.bind('pusher:subscription_succeeded', () => {\n                                    server.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                                        expect(sockets.size).toBe(2);\n\n                                        client2.unsubscribe(channelName);\n\n                                        Utils.wait(3000).then(() => {\n                                            server.adapter.getChannelSockets('app-id', channelName).then(sockets => {\n                                                expect(sockets.size).toBe(1);\n                                                client1.disconnect();\n                                                client2.disconnect();\n                                                done();\n                                            });\n                                        });\n                                    });\n                                });\n                            });\n                        });\n                    });\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('signin after connection', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => {\n            let client = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 });\n\n            client.connection.bind('connected', () => {\n                client.connection.bind('message', ({ event }) => {\n                    if (event === 'pusher:signin_success') {\n                        // After subscription, wait 10 seconds to make sure it isn't disconnected\n                        setTimeout(() => {\n                            client.disconnect();\n                            done();\n                        }, 10_000);\n                    }\n                });\n\n                client.signin();\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('not calling signin after connection throws right error code', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => {\n            let client = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 });\n\n            client.connection.bind('connected', () => {\n                client.connection.bind('message', (error) => {\n                    if (error.event === 'pusher:error') {\n                        expect(error.data.code).toBe(4009);\n                        client.disconnect();\n                        done();\n                    }\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('not having user id throws an error', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => {\n            let client = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { name: 'John' });\n\n            client.connection.bind('connected', () => {\n                client.connection.bind('message', (error) => {\n                    if (error.event === 'pusher:error') {\n                        expect(error.data.code).toBe(4009);\n                        client.disconnect();\n                        done();\n                    }\n                });\n            });\n        });\n    });\n\n    Utils.shouldRun(Utils.appManagerIs('array'))('sending wrong user data token throws error', done => {\n        Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => {\n            let client = Utils.newClientForPrivateChannel({\n                userAuthentication: {\n                    customHandler: ({ socketId }, callback) => {\n                        callback(false, {\n                            auth: 'fail-on-purpose',\n                            user_data: JSON.stringify({ id: 1 }),\n                        });\n                    },\n                },\n            }, 6001, 'app-key', { id: 1 });\n\n            client.connection.bind('connected', () => {\n                client.connection.bind('message', (error) => {\n                    if (error.event === 'pusher:error') {\n                        expect(error.data.code).toBe(4009);\n                        client.disconnect();\n                        done();\n                    }\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"allowSyntheticDefaultImports\": true,\n    \"module\": \"commonjs\",\n    \"moduleResolution\": \"node\",\n    \"outDir\": \"./dist\",\n    \"sourceMap\": false,\n    \"target\": \"es2019\",\n    \"noImplicitAny\": false,\n    \"preserveConstEnums\": true,\n    \"removeComments\": true,\n    \"typeRoots\": [\n      \"node_modules/@types\"\n    ],\n    \"lib\": [\n      \"es2019\",\n      \"dom\"\n    ],\n    \"types\": [\n      \"jest\",\n      \"node\"\n    ]\n  },\n  \"include\": [\n    \"./typings/**/*.ts\",\n    \"./src/**/*.ts\"\n  ],\n  \"exclude\": [\n    \"node_modules\"\n  ]\n}\n"
  }
]