diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..e05914176 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,29 @@ +*~ +.dockerignore +.hg +Dockerfile + +# Remove the git objects, logs, etc. to make final image smaller. +# Some files still need to be in the .git directory, because Etherpad at +# startup uses them to discover its version number. +.git/branches +.git/COMMIT_EDITMSG +.git/config +.git/description +.git/FETCH_HEAD +.git/hooks +.git/index +.git/info +.git/logs +.git/objects +.git/ORIG_HEAD +.git/packed-refs +.git/refs/remotes/ +.git/rr-cache/ +.gitignore + +settings.json +src/node_modules +admin/node_modules +ui/node_modules +node_modules diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..f521471dc --- /dev/null +++ b/.editorconfig @@ -0,0 +1,17 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +end_of_line = lf +# editorconfig-tools is unable to ignore longs strings or urls +max_line_length = off + +[CHANGELOG.md] +indent_size = 4 + +[*.bat] +end_of_line = crlf diff --git a/.env.default b/.env.default new file mode 100644 index 000000000..e9b560b72 --- /dev/null +++ b/.env.default @@ -0,0 +1,18 @@ +# Please copy and rename this file. +# +# !Attention! +# Always ensure to load the env variables in every terminal session. +# Otherwise the env variables will not be available + +DOCKER_COMPOSE_APP_PORT_PUBLISHED=9001 +DOCKER_COMPOSE_APP_PORT_TARGET=9001 + +# IMPORTANT: When the env var DEFAULT_PAD_TEXT is unset or empty, then the pad is not established (not the landing page). +# The env var DEFAULT_PAD_TEXT seems to be mandatory in the latest version of etherpad. +DOCKER_COMPOSE_APP_DEV_ENV_DEFAULT_PAD_TEXT="Welcome to etherpad" + +DOCKER_COMPOSE_APP_ADMIN_PASSWORD= + +DOCKER_COMPOSE_POSTGRES_DATABASE=db +DOCKER_COMPOSE_POSTGRES_PASSWORD=etherpad-lite-password +DOCKER_COMPOSE_POSTGRES_USER=etherpad-lite-user diff --git a/.env.dev.default b/.env.dev.default new file mode 100644 index 000000000..b78b5599a --- /dev/null +++ b/.env.dev.default @@ -0,0 +1,18 @@ +# Please copy and rename this file. +# +# !Attention! +# Always ensure to load the env variables in every terminal session. +# Otherwise the env variables will not be available + +DOCKER_COMPOSE_APP_DEV_PORT_PUBLISHED=9001 +DOCKER_COMPOSE_APP_DEV_PORT_TARGET=9001 + +# IMPORTANT: When the env var DEFAULT_PAD_TEXT is unset or empty, then the pad is not established (not the landing page). +# The env var DEFAULT_PAD_TEXT seems to be mandatory in the latest version of etherpad. +DOCKER_COMPOSE_APP_DEV_ENV_DEFAULT_PAD_TEXT="Welcome to etherpad" + +DOCKER_COMPOSE_APP_DEV_ADMIN_PASSWORD= + +DOCKER_COMPOSE_POSTGRES_DEV_ENV_POSTGRES_DATABASE=db +DOCKER_COMPOSE_POSTGRES_DEV_ENV_POSTGRES_PASSWORD=etherpad-lite-password +DOCKER_COMPOSE_POSTGRES_DEV_ENV_POSTGRES_USER=etherpad-lite-user \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..6313b56c5 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..8fd968ed2 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +github: ether diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..041f7c1a9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,47 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + + + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Server (please complete the following information):** + - Etherpad version: + - OS: [e.g., Ubuntu 20.04] + - Node.js version (`node --version`): + - npm version (`npm --version`): + - Is the server free of plugins: + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..9f8fe9f89 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,33 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: Feature Request +assignees: '' + +--- + +* * * + +name: Feature request +about: Suggest an idea for this project +title: '' +labels: enhancement +assignees: + +* * * + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when (...) + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. + +**Plugin?** +Might this feature be better suited to being a plugin? Usually features that can be plugins, should be. diff --git a/.github/ISSUE_TEMPLATE/plugin-request-template.md b/.github/ISSUE_TEMPLATE/plugin-request-template.md new file mode 100644 index 000000000..599973981 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/plugin-request-template.md @@ -0,0 +1,30 @@ +--- +name: Plugin request template +about: Suggest a plugin for Etherpad +title: '' +labels: Plugin Request +assignees: JohnMcLear + +--- + +* * * + +name: Plugin request +about: Suggest a plugin for this project +title: '' +labels: plugin request +assignees: + +* * * + +**Is your plugin request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when (...) + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the plugin request here. diff --git a/.github/ISSUE_TEMPLATE/security-issue.md b/.github/ISSUE_TEMPLATE/security-issue.md new file mode 100644 index 000000000..c8b506703 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/security-issue.md @@ -0,0 +1,10 @@ +--- +name: Security issue +about: Notify the Etherpad foundation of a Security issue +title: '' +labels: security +assignees: '' + +--- + +Please email contact@etherpad.org with details of the security issue prior to posting here. diff --git a/.github/ISSUE_TEMPLATE/security.md b/.github/ISSUE_TEMPLATE/security.md new file mode 100644 index 000000000..b2e6824eb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/security.md @@ -0,0 +1,13 @@ +* * * + +name: Security notification +about: Disclose a security issue in Etherpad +title: '' +labels: security +assignees: + +* * * + +**Our Security disclosure process** +1. Please email contact@etherpad.org with detials of the exploit including steps to replicate. +1. Once confirmed we will provide a confirmation, patch and CVE details. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..d9f660907 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,13 @@ + diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..1e7ac79ed --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,20 @@ +version: 2 +updates: + # Maintain dependencies for GitHub Actions + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + - package-ecosystem: "docker" + directory: "/" + schedule: + interval: "daily" + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "daily" + versioning-strategy: "increase" + open-pull-requests-limit: 30 + groups: + dev-dependencies: + dependency-type: "development" \ No newline at end of file diff --git a/.github/workflows/backend-tests.yml b/.github/workflows/backend-tests.yml new file mode 100644 index 000000000..3c6e63bb4 --- /dev/null +++ b/.github/workflows/backend-tests.yml @@ -0,0 +1,290 @@ +name: "Backend tests" + +# any branch is useful for testing before a PR is submitted +on: + push: + paths-ignore: + - "doc/**" + pull_request: + paths-ignore: + - "doc/**" + +permissions: + contents: read + +jobs: + withoutpluginsLinux: + # run on pushes to any branch + # run on PRs from external forks + if: | + (github.event_name != 'pull_request') + || (github.event.pull_request.head.repo.id != github.event.pull_request.base.repo.id) + name: Linux without plugins + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node: [20, 22, 23] + steps: + - + name: Checkout repository + uses: actions/checkout@v4 + - + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - + name: Install libreoffice + uses: awalsh128/cache-apt-pkgs-action@v1.5.0 + with: + packages: libreoffice libreoffice-pdfimport + version: 1.0 + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: bin/installDeps.sh + - name: Install admin ui + working-directory: admin + run: pnpm install + - name: Build admin ui + working-directory: admin + run: pnpm build + - + name: Run the backend tests + run: pnpm test + - name: Run the new vitest tests + working-directory: src + run: pnpm run test:vitest + + withpluginsLinux: + # run on pushes to any branch + # run on PRs from external forks + if: | + (github.event_name != 'pull_request') + || (github.event.pull_request.head.repo.id != github.event.pull_request.base.repo.id) + name: Linux with Plugins + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node: [20, 22, 23] + steps: + - + name: Checkout repository + uses: actions/checkout@v4 + - + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - + name: Install libreoffice + uses: awalsh128/cache-apt-pkgs-action@v1.5.0 + with: + packages: libreoffice libreoffice-pdfimport + version: 1.0 + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: bin/installDeps.sh + - name: Install admin ui + working-directory: admin + run: pnpm install + - name: Build admin ui + working-directory: admin + run: pnpm build + - + name: Install Etherpad plugins + run: > + pnpm install --workspace-root + ep_align + ep_author_hover + ep_cursortrace + ep_font_size + ep_hash_auth + ep_headings2 + ep_markdown + ep_readonly_guest + ep_set_title_on_pad + ep_spellcheck + ep_subscript_and_superscript + ep_table_of_contents + - + name: Run the backend tests + run: pnpm test + - name: Run the new vitest tests + working-directory: src + run: pnpm run test:vitest + + withoutpluginsWindows: + # run on pushes to any branch + # run on PRs from external forks + if: | + (github.event_name != 'pull_request') + || (github.event.pull_request.head.repo.id != github.event.pull_request.base.repo.id) + name: Windows without plugins + runs-on: windows-latest + steps: + - + name: Checkout repository + uses: actions/checkout@v4 + - + uses: actions/setup-node@v4 + with: + node-version: 20 + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: bin/installOnWindows.bat + - name: Install admin ui + working-directory: admin + run: pnpm install + - name: Build admin ui + working-directory: admin + run: pnpm build + - + name: Fix up the settings.json + run: | + powershell -Command "(gc settings.json.template) -replace '\"max\": 10', '\"max\": 10000' | Out-File -encoding ASCII settings.json.holder" + powershell -Command "(gc settings.json.holder) -replace '\"points\": 10', '\"points\": 1000' | Out-File -encoding ASCII settings.json" + - + name: Run the backend tests + working-directory: src + run: pnpm test + - name: Run the new vitest tests + working-directory: src + run: pnpm run test:vitest + + withpluginsWindows: + # run on pushes to any branch + # run on PRs from external forks + if: | + (github.event_name != 'pull_request') + || (github.event.pull_request.head.repo.id != github.event.pull_request.base.repo.id) + name: Windows with Plugins + runs-on: windows-latest + + steps: + - + name: Checkout repository + uses: actions/checkout@v4 + - + uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - name: Install admin ui + working-directory: admin + run: pnpm install + - name: Build admin ui + working-directory: admin + run: pnpm build + - + name: Install Etherpad plugins + # The --legacy-peer-deps flag is required to work around a bug in npm + # v7: https://github.com/npm/cli/issues/2199 + run: > + pnpm install --workspace-root + ep_align + ep_author_hover + ep_cursortrace + ep_font_size + ep_hash_auth + ep_headings2 + ep_markdown + ep_readonly_guest + ep_set_title_on_pad + ep_spellcheck + ep_subscript_and_superscript + ep_table_of_contents + # Etherpad core dependencies must be installed after installing the + # plugin's dependencies, otherwise npm will try to hoist common + # dependencies by removing them from src/node_modules and installing them + # in the top-level node_modules. As of v6.14.10, npm's hoist logic appears + # to be buggy, because it sometimes removes dependencies from + # src/node_modules but fails to add them to the top-level node_modules. + # Even if npm correctly hoists the dependencies, the hoisting seems to + # confuse tools such as `npm outdated`, `npm update`, and some ESLint + # rules. + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: bin/installOnWindows.bat + - + name: Fix up the settings.json + run: | + powershell -Command "(gc settings.json.template) -replace '\"max\": 10', '\"max\": 10000' | Out-File -encoding ASCII settings.json.holder" + powershell -Command "(gc settings.json.holder) -replace '\"points\": 10', '\"points\": 1000' | Out-File -encoding ASCII settings.json" + - + name: Run the backend tests + working-directory: src + run: pnpm test + - name: Run the new vitest tests + working-directory: src + run: pnpm run test:vitest diff --git a/.github/workflows/build-and-deploy-docs.yml b/.github/workflows/build-and-deploy-docs.yml new file mode 100644 index 000000000..3134de22a --- /dev/null +++ b/.github/workflows/build-and-deploy-docs.yml @@ -0,0 +1,70 @@ +# Workflow for deploying static content to GitHub Pages +name: Deploy Docs to GitHub Pages + +on: + # Runs on pushes targeting the default branch + push: + branches: ["develop"] + paths: + - doc/** # Only run workflow when changes are made to the doc directory + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages +permissions: + contents: read + pages: write + id-token: write + packages: read + +# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. +# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. +concurrency: + group: "pages" + cancel-in-progress: false + +jobs: + # Single deploy job since we're just deploying + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup Pages + uses: actions/configure-pages@v5 + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - name: Install dependencies + run: pnpm install + - name: Build app + working-directory: doc + run: pnpm run docs:build + env: + COMMIT_REF: ${{ github.sha }} + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + # Upload entire repository + path: './doc/.vitepress/dist' + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 000000000..94dd1ac75 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,46 @@ +name: "CodeQL" + +on: + push: + branches: [develop, master] + pull_request: + # The branches below must be a subset of the branches above + branches: [develop] + paths-ignore: + - 'doc/**' + schedule: + - cron: '0 13 * * 1' + +permissions: + contents: read + +jobs: + analyze: + permissions: + actions: read # for github/codeql-action/init to get workflow details + contents: read # for actions/checkout to fetch code + security-events: write # for github/codeql-action/autobuild to send a status report + name: Analyze + runs-on: ubuntu-latest + steps: + - + name: Checkout repository + uses: actions/checkout@v4 + with: + # We must fetch at least the immediate parents so that if this is + # a pull request then we can checkout the head. + fetch-depth: 2 + # If this run was triggered by a pull request event, then checkout + # the head of the pull request instead of the merge commit. + - + run: git checkout HEAD^2 + if: ${{ github.event_name == 'pull_request' }} + - + name: Initialize CodeQL + uses: github/codeql-action/init@v3 + - + name: Autobuild + uses: github/codeql-action/autobuild@v3 + - + name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml new file mode 100644 index 000000000..9a9dcfebb --- /dev/null +++ b/.github/workflows/dependency-review.yml @@ -0,0 +1,20 @@ +# Dependency Review Action +# +# This Action will scan dependency manifest files that change as part of a Pull Reqest, surfacing known-vulnerable versions of the packages declared or updated in the PR. Once installed, if the workflow run is marked as required, PRs introducing known-vulnerable packages will be blocked from merging. +# +# Source repository: https://github.com/actions/dependency-review-action +# Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement +name: 'Dependency Review' +on: [pull_request] + +permissions: + contents: read + +jobs: + dependency-review: + runs-on: ubuntu-latest + steps: + - name: 'Checkout Repository' + uses: actions/checkout@v4 + - name: 'Dependency Review' + uses: actions/dependency-review-action@v4 diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 000000000..313d48fc6 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,144 @@ +name: Docker +on: + pull_request: + paths-ignore: + - 'doc/**' + push: + branches: + - 'develop' + paths-ignore: + - 'doc/**' + tags: + - 'v?[0-9]+.[0-9]+.[0-9]+' +env: + TEST_TAG: etherpad/etherpad:test +permissions: + contents: read + +jobs: + docker: + runs-on: ubuntu-latest + steps: + - + name: Check out + uses: actions/checkout@v4 + with: + path: etherpad + + - + name: Set up QEMU + if: github.event_name == 'push' + uses: docker/setup-qemu-action@v3 + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Build and export to Docker + uses: docker/build-push-action@v6 + with: + context: ./etherpad + target: production + load: true + tags: ${{ env.TEST_TAG }} + cache-from: type=gha + cache-to: type=gha,mode=max + - + name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 'lts/*' + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - + name: Test + working-directory: etherpad + run: | + docker run --rm -d -p 9001:9001 --name test ${{ env.TEST_TAG }} + ./bin/installDeps.sh + docker logs -f test & + while true; do + echo "Waiting for Docker container to start..." + status=$(docker container inspect -f '{{.State.Health.Status}}' test) || exit 1 + case ${status} in + healthy) break;; + starting) sleep 2;; + *) printf %s\\n "unexpected status: ${status}" >&2; exit 1;; + esac + done + (cd src && pnpm run test-container) + git clean -dxf . + - + name: Docker meta + if: github.event_name == 'push' + id: meta + uses: docker/metadata-action@v5 + with: + images: etherpad/etherpad + tags: | + type=ref,event=branch + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=semver,pattern={{major}} + - + name: Log in to Docker Hub + if: github.event_name == 'push' + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - + name: Build and push + id: build-docker + if: github.event_name == 'push' + uses: docker/build-push-action@v6 + with: + context: ./etherpad + target: production + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + - name: Update repo description + uses: peter-evans/dockerhub-description@v4 + if: github.ref == 'refs/heads/master' + with: + readme-filepath: ./etherpad/README.md + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + repository: etherpad/etherpad + enable-url-completion: true + - name: Check out + if: github.event_name == 'push' && github.ref == 'refs/heads/develop' + uses: actions/checkout@v4 + with: + path: ether-charts + repository: ether/ether-charts + token: ${{ secrets.ETHER_CHART_TOKEN }} + - name: Update tag in values-dev.yaml + if: success() && github.ref == 'refs/heads/develop' + working-directory: ether-charts + run: | + sed -i 's/tag: ".*"/tag: "${{ steps.build-docker.outputs.digest }}"/' values-dev.yaml + - name: Commit and push changes + working-directory: ether-charts + if: success() && github.ref == 'refs/heads/develop' + run: | + git config --global user.name 'github-actions[bot]' + git config --global user.email 'github-actions[bot]@users.noreply.github.com' + git add values-dev.yaml + git commit -m 'Update develop image tag' + git push diff --git a/.github/workflows/frontend-admin-tests.yml b/.github/workflows/frontend-admin-tests.yml new file mode 100644 index 000000000..4963fac24 --- /dev/null +++ b/.github/workflows/frontend-admin-tests.yml @@ -0,0 +1,153 @@ +# Leave the powered by Sauce Labs bit in as this means we get additional concurrency +name: "Frontend admin tests powered by Sauce Labs" + +on: + push: + paths-ignore: + - 'doc/**' + +permissions: + contents: read # to fetch code (actions/checkout) + +jobs: + withplugins: + name: with plugins + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + node: [20, 22, 23] + + steps: + - + name: Generate Sauce Labs strings + id: sauce_strings + run: | + printf %s\\n '::set-output name=name::${{ github.workflow }} - ${{ github.job }} - Node ${{ matrix.node }}' + printf %s\\n '::set-output name=tunnel_id::${{ github.run_id }}-${{ github.run_number }}-${{ github.job }}-node${{ matrix.node }}' + - + name: Checkout repository + uses: actions/checkout@v4 + - + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Cache playwright binaries + uses: actions/cache@v4 + id: playwright-cache + with: + path: | + ~/.cache/ms-playwright + key: ${{ runner.os }}-playwright-${{ env.PLAYWRIGHT_VERSION }} + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + #- + # name: Install etherpad plugins + # # We intentionally install an old ep_align version to test upgrades to + # # the minor version number. The --legacy-peer-deps flag is required to + # # work around a bug in npm v7: https://github.com/npm/cli/issues/2199 + # run: pnpm install --workspace-root ep_align@0.2.27 + # Etherpad core dependencies must be installed after installing the + # plugin's dependencies, otherwise npm will try to hoist common + # dependencies by removing them from src/node_modules and installing them + # in the top-level node_modules. As of v6.14.10, npm's hoist logic appears + # to be buggy, because it sometimes removes dependencies from + # src/node_modules but fails to add them to the top-level node_modules. + # Even if npm correctly hoists the dependencies, the hoisting seems to + # confuse tools such as `npm outdated`, `npm update`, and some ESLint + # rules. + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: pnpm i + #- + # name: Install etherpad plugins + # run: rm -Rf node_modules/ep_align/static/tests/* + - + name: export GIT_HASH to env + id: environment + run: echo "::set-output name=sha_short::$(git rev-parse --short ${{ github.sha }})" + - + name: Create settings.json + run: cp settings.json.template settings.json + - + name: Write custom settings.json that enables the Admin UI tests + run: "sed -i 's/\"enableAdminUITests\": false/\"enableAdminUITests\": true,\\n\"users\":{\"admin\":{\"password\":\"changeme1\",\"is_admin\":true}}/' settings.json" + - + name: increase maxHttpBufferSize + run: "sed -i 's/\"maxHttpBufferSize\": 50000/\"maxHttpBufferSize\": 10000000/' settings.json" + - + name: Disable import/export rate limiting + run: | + sed -e '/^ *"importExportRateLimiting":/,/^ *\}/ s/"max":.*/"max": 100000000/' -i settings.json + - name: Build admin frontend + working-directory: admin + run: | + pnpm run build + # name: Run the frontend admin tests + # shell: bash + # env: + # SAUCE_USERNAME: ${{ secrets.SAUCE_USERNAME }} + # SAUCE_ACCESS_KEY: ${{ secrets.SAUCE_ACCESS_KEY }} + # SAUCE_NAME: ${{ steps.sauce_strings.outputs.name }} + # TRAVIS_JOB_NUMBER: ${{ steps.sauce_strings.outputs.tunnel_id }} + # GIT_HASH: ${{ steps.environment.outputs.sha_short }} + # run: | + # src/tests/frontend/travis/adminrunner.sh + #- + # uses: saucelabs/sauce-connect-action@v2.3.6 + # with: + # username: ${{ secrets.SAUCE_USERNAME }} + # accessKey: ${{ secrets.SAUCE_ACCESS_KEY }} + # tunnelIdentifier: ${{ steps.sauce_strings.outputs.tunnel_id }} + #- + # name: Run the frontend admin tests + # shell: bash + # env: + # SAUCE_USERNAME: ${{ secrets.SAUCE_USERNAME }} + # SAUCE_ACCESS_KEY: ${{ secrets.SAUCE_ACCESS_KEY }} + # SAUCE_NAME: ${{ steps.sauce_strings.outputs.name }} + # TRAVIS_JOB_NUMBER: ${{ steps.sauce_strings.outputs.tunnel_id }} + # GIT_HASH: ${{ steps.environment.outputs.sha_short }} + # run: | + # src/tests/frontend/travis/adminrunner.sh + - name: Run the frontend admin tests + shell: bash + run: | + pnpm run prod & + connected=false + can_connect() { + curl -sSfo /dev/null http://localhost:9001/ || return 1 + connected=true + } + now() { date +%s; } + start=$(now) + while [ $(($(now) - $start)) -le 15 ] && ! can_connect; do + sleep 1 + done + cd src + pnpm exec playwright install + pnpm exec playwright install-deps + pnpm run test-admin + - uses: actions/upload-artifact@v4 + if: always() + with: + name: playwright-report-${{ matrix.node }} + path: src/playwright-report/ + retention-days: 30 diff --git a/.github/workflows/frontend-tests.yml b/.github/workflows/frontend-tests.yml new file mode 100644 index 000000000..c11058b24 --- /dev/null +++ b/.github/workflows/frontend-tests.yml @@ -0,0 +1,238 @@ +# Leave the powered by Sauce Labs bit in as this means we get additional concurrency +name: "Frontend tests powered by Sauce Labs" + +on: + push: + paths-ignore: + - 'doc/**' + +permissions: + contents: read # to fetch code (actions/checkout) + +jobs: + playwright-chrome: + name: Playwright Chrome + runs-on: ubuntu-latest + steps: + - + name: Generate Sauce Labs strings + id: sauce_strings + run: | + printf %s\\n '::set-output name=name::${{ github.workflow }} - ${{ github.job }}' + printf %s\\n '::set-output name=tunnel_id::${{ github.run_id }}-${{ github.run_number }}-${{ github.job }}' + - + name: Checkout repository + uses: actions/checkout@v4 + - + uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + if: always() + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: bin/installDeps.sh + - + name: export GIT_HASH to env + id: environment + run: echo "::set-output name=sha_short::$(git rev-parse --short ${{ github.sha }})" + - + name: Create settings.json + run: cp ./src/tests/settings.json settings.json + - name: Cache playwright binaries + uses: actions/cache@v4 + id: playwright-cache + with: + path: | + ~/.cache/ms-playwright + key: ${{ runner.os }}-playwright-${{ env.PLAYWRIGHT_VERSION }} + - name: Run the frontend tests + shell: bash + run: | + pnpm run prod & + connected=false + can_connect() { + curl -sSfo /dev/null http://localhost:9001/ || return 1 + connected=true + } + now() { date +%s; } + start=$(now) + while [ $(($(now) - $start)) -le 15 ] && ! can_connect; do + sleep 1 + done + cd src + pnpm exec playwright install chromium --with-deps + pnpm run test-ui --project=chromium + - uses: actions/upload-artifact@v4 + if: always() + with: + name: playwright-report-${{ matrix.node }}-chrome + path: src/playwright-report/ + retention-days: 30 + playwright-firefox: + name: Playwright Firefox + runs-on: ubuntu-latest + steps: + - name: Generate Sauce Labs strings + id: sauce_strings + run: | + printf %s\\n '::set-output name=name::${{ github.workflow }} - ${{ github.job }}' + printf %s\\n '::set-output name=tunnel_id::${{ github.run_id }}-${{ github.run_number }}-${{ github.job }}' + - name: Checkout repository + uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + if: always() + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - name: Install all dependencies and symlink for ep_etherpad-lite + run: bin/installDeps.sh + - name: export GIT_HASH to env + id: environment + run: echo "::set-output name=sha_short::$(git rev-parse --short ${{ github.sha }})" + - name: Create settings.json + run: cp ./src/tests/settings.json settings.json + - name: Cache playwright binaries + uses: actions/cache@v4 + id: playwright-cache + with: + path: | + ~/.cache/ms-playwright + key: ${{ runner.os }}-playwright-${{ env.PLAYWRIGHT_VERSION }} + - name: Run the frontend tests + shell: bash + run: | + pnpm run prod & + connected=false + can_connect() { + curl -sSfo /dev/null http://localhost:9001/ || return 1 + connected=true + } + now() { date +%s; } + start=$(now) + while [ $(($(now) - $start)) -le 15 ] && ! can_connect; do + sleep 1 + done + cd src + pnpm exec playwright install firefox --with-deps + pnpm run test-ui --project=firefox + - uses: actions/upload-artifact@v4 + if: always() + with: + name: playwright-report-${{ matrix.node }}-firefox + path: src/playwright-report/ + retention-days: 30 + playwright-webkit: + name: Playwright Webkit + runs-on: ubuntu-latest + + steps: + - + name: Generate Sauce Labs strings + id: sauce_strings + run: | + printf %s\\n '::set-output name=name::${{ github.workflow }} - ${{ github.job }}' + printf %s\\n '::set-output name=tunnel_id::${{ github.run_id }}-${{ github.run_number }}-${{ github.job }}' + - + name: Checkout repository + uses: actions/checkout@v4 + - + uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Cache playwright binaries + uses: actions/cache@v4 + id: playwright-cache + with: + path: | + ~/.cache/ms-playwright + key: ${{ runner.os }}-playwright-${{ env.PLAYWRIGHT_VERSION }} + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + if: always() + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: bin/installDeps.sh + - + name: export GIT_HASH to env + id: environment + run: echo "::set-output name=sha_short::$(git rev-parse --short ${{ github.sha }})" + - + name: Create settings.json + run: cp ./src/tests/settings.json settings.json + - name: Run the frontend tests + shell: bash + run: | + pnpm run prod & + connected=false + can_connect() { + curl -sSfo /dev/null http://localhost:9001/ || return 1 + connected=true + } + now() { date +%s; } + start=$(now) + while [ $(($(now) - $start)) -le 15 ] && ! can_connect; do + sleep 1 + done + cd src + pnpm exec playwright install webkit --with-deps + pnpm run test-ui --project=webkit || true + - uses: actions/upload-artifact@v4 + if: always() + with: + name: playwright-report-${{ matrix.node }}-webkit + path: src/playwright-report/ + retention-days: 30 + + + diff --git a/.github/workflows/load-test.yml b/.github/workflows/load-test.yml new file mode 100644 index 000000000..50847cd9a --- /dev/null +++ b/.github/workflows/load-test.yml @@ -0,0 +1,173 @@ +name: "Loadtest" + +# any branch is useful for testing before a PR is submitted +on: + push: + paths-ignore: + - "doc/**" + pull_request: + paths-ignore: + - "doc/**" + +permissions: + contents: read + +jobs: + withoutplugins: + # run on pushes to any branch + # run on PRs from external forks + if: | + (github.event_name != 'pull_request') + || (github.event.pull_request.head.repo.id != github.event.pull_request.base.repo.id) + name: without plugins + runs-on: ubuntu-latest + steps: + - + name: Checkout repository + uses: actions/checkout@v4 + - + uses: actions/setup-node@v4 + with: + node-version: 20 + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: bin/installDeps.sh + - + name: Install etherpad-load-test + run: sudo npm install -g etherpad-load-test-socket-io + - + name: Run load test + run: src/tests/frontend/travis/runnerLoadTest.sh 25 50 + + withplugins: + # run on pushes to any branch + # run on PRs from external forks + if: | + (github.event_name != 'pull_request') + || (github.event.pull_request.head.repo.id != github.event.pull_request.base.repo.id) + name: with Plugins + runs-on: ubuntu-latest + steps: + - + name: Checkout repository + uses: actions/checkout@v4 + - + uses: actions/setup-node@v4 + with: + node-version: 20 + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - + name: Install etherpad-load-test + run: pnpm install -g etherpad-load-test-socket-io + - + name: Install etherpad plugins + # The --legacy-peer-deps flag is required to work around a bug in npm v7: + # https://github.com/npm/cli/issues/2199 + run: > + pnpm install --workspace-root + ep_align + ep_author_hover + ep_cursortrace + ep_font_size + ep_hash_auth + ep_headings2 + ep_markdown + ep_readonly_guest + ep_set_title_on_pad + ep_spellcheck + ep_subscript_and_superscript + ep_table_of_contents + # Etherpad core dependencies must be installed after installing the + # plugin's dependencies, otherwise npm will try to hoist common + # dependencies by removing them from src/node_modules and installing them + # in the top-level node_modules. As of v6.14.10, npm's hoist logic appears + # to be buggy, because it sometimes removes dependencies from + # src/node_modules but fails to add them to the top-level node_modules. + # Even if npm correctly hoists the dependencies, the hoisting seems to + # confuse tools such as `npm outdated`, `npm update`, and some ESLint + # rules. + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: bin/installDeps.sh + - + name: Run load test + run: src/tests/frontend/travis/runnerLoadTest.sh 25 50 + + long: + # run on pushes to any branch + # run on PRs from external forks + if: | + (github.event_name != 'pull_request') + || (github.event.pull_request.head.repo.id != github.event.pull_request.base.repo.id) + name: long running + runs-on: ubuntu-latest + steps: + - + name: Checkout repository + uses: actions/checkout@v4 + - + uses: actions/setup-node@v4 + with: + node-version: 20 + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: bin/installDeps.sh + - + name: Install etherpad-load-test + run: sudo npm install -g etherpad-load-test-socket-io + - + name: Run load test + run: src/tests/frontend/travis/runnerLoadTest.sh 5000 5 diff --git a/.github/workflows/perform-type-check.yml b/.github/workflows/perform-type-check.yml new file mode 100644 index 000000000..ba35dec32 --- /dev/null +++ b/.github/workflows/perform-type-check.yml @@ -0,0 +1,52 @@ +name: "Perform type checks" + +# any branch is useful for testing before a PR is submitted +on: + push: + paths-ignore: + - "doc/**" + pull_request: + paths-ignore: + - "doc/**" + +permissions: + contents: read + + +jobs: + performTypeCheck: + if: | + (github.event_name != 'pull_request') + || (github.event.pull_request.head.repo.id != github.event.pull_request.base.repo.id) + name: perform type check + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: ./bin/installDeps.sh + - name: Perform type check + working-directory: ./src + run: npm run ts-check diff --git a/.github/workflows/rate-limit.yml b/.github/workflows/rate-limit.yml new file mode 100644 index 000000000..003a10000 --- /dev/null +++ b/.github/workflows/rate-limit.yml @@ -0,0 +1,71 @@ +name: "rate limit" + +# any branch is useful for testing before a PR is submitted +on: + push: + paths-ignore: + - "doc/**" + pull_request: + paths-ignore: + - "doc/**" + +permissions: + contents: read + +jobs: + ratelimit: + # run on pushes to any branch + # run on PRs from external forks + if: | + (github.event_name != 'pull_request') + || (github.event.pull_request.head.repo.id != github.event.pull_request.base.repo.id) + name: test + runs-on: ubuntu-latest + steps: + - + name: Checkout repository + uses: actions/checkout@v4 + - + uses: actions/setup-node@v4 + with: + node-version: 20 + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + + - + name: docker network + run: docker network create --subnet=172.23.0.0/16 ep_net + - + name: build docker image + run: | + docker build -f Dockerfile -t epl-debian-slim --build-arg NODE_ENV=develop . + docker build -f src/tests/ratelimit/Dockerfile.nginx -t nginx-latest . + docker build -f src/tests/ratelimit/Dockerfile.anotherip -t anotherip . + - + name: run docker images + run: | + docker run --name etherpad-docker -p 9000:9001 --rm --network ep_net --ip 172.23.42.2 -e 'TRUST_PROXY=true' epl-debian-slim & + docker run -p 8081:80 --rm --network ep_net --ip 172.23.42.1 -d nginx-latest + docker run --rm --network ep_net --ip 172.23.42.3 --name anotherip -dt anotherip + - + name: install dependencies and create symlink for ep_etherpad-lite + run: bin/installDeps.sh + - + name: run rate limit test + run: | + cd src/tests/ratelimit + ./testlimits.sh diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 000000000..60249bb15 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,18 @@ +name: 'Close stale issues and PRs' +on: + schedule: + - cron: '30 6 * * *' +permissions: + issues: write + pull-requests: write +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v9 + with: + close-issue-label: wontfix + close-pr-label: wontfix + days-before-close: -1 + exempt-issue-labels: 'pinned,security,Bug,Serious Bug,Minor bug,Black hole bug,Special case Bug,Upstream bug,Feature Request' + exempt-pr-labels: 'pinned,security,Bug,Serious Bug,Minor bug,Black hole bug,Special case Bug,Upstream bug,Feature Request' diff --git a/.github/workflows/upgrade-from-latest-release.yml b/.github/workflows/upgrade-from-latest-release.yml new file mode 100644 index 000000000..08421e7ec --- /dev/null +++ b/.github/workflows/upgrade-from-latest-release.yml @@ -0,0 +1,116 @@ +name: "Upgrade from latest release" + +# any branch is useful for testing before a PR is submitted +on: + push: + paths-ignore: + - "doc/**" + pull_request: + paths-ignore: + - "doc/**" + +permissions: + contents: read + +jobs: + withpluginsLinux: + # run on pushes to any branch + # run on PRs from external forks + if: | + (github.event_name != 'pull_request') + || (github.event.pull_request.head.repo.id != github.event.pull_request.base.repo.id) + name: Linux with Plugins + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node: [20, 22, 23] + steps: + - + name: Check out latest release + uses: actions/checkout@v4 + with: + ref: develop #FIXME change to master when doing release + - + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - name: Install libreoffice + uses: awalsh128/cache-apt-pkgs-action@v1.5.0 + with: + packages: libreoffice libreoffice-pdfimport + version: 1.0 + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - + name: Install libreoffice + uses: awalsh128/cache-apt-pkgs-action@v1.5.0 + with: + packages: libreoffice libreoffice-pdfimport + version: 1.0 + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: bin/installDeps.sh + - name: Install admin ui + working-directory: admin + run: pnpm install + - name: Build admin ui + working-directory: admin + run: pnpm build + - + name: Install Etherpad plugins + run: > + pnpm run install-plugins + ep_align + ep_author_hover + ep_cursortrace + ep_font_size + ep_hash_auth + ep_headings2 + ep_markdown + ep_readonly_guest + ep_set_title_on_pad + ep_spellcheck + ep_subscript_and_superscript + ep_table_of_contents + - + name: Run the backend tests + run: pnpm run test + - + name: Install all dependencies and symlink for ep_etherpad-lite + run: ./bin/installDeps.sh + # Because actions/checkout@v4 is called with "ref: master" and without + # "fetch-depth: 0", the local clone does not have the ${GITHUB_SHA} + # commit. Fetch ${GITHUB_REF} to get the ${GITHUB_SHA} commit. Note that a + # plain "git fetch" only fetches "normal" references (refs/heads/* and + # refs/tags/*), and for pull requests none of the normal references + # include ${GITHUB_SHA}, so we have to explicitly tell Git to fetch + # ${GITHUB_REF}. + - + name: Fetch the new Git commits + run: git fetch --depth=1 origin "${GITHUB_REF}" + - + name: Upgrade to the new Git revision + # For pull requests, ${GITHUB_SHA} is the automatically generated merge + # commit that merges the PR's source branch to its destination branch. + run: git checkout "${GITHUB_SHA}" + - name: Run the backend tests + run: pnpm run test diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml new file mode 100644 index 000000000..c0ce8b8bd --- /dev/null +++ b/.github/workflows/windows.yml @@ -0,0 +1,86 @@ +name: "Windows Build" + +# any branch is useful for testing before a PR is submitted +on: + push: + paths-ignore: + - "doc/**" + pull_request: + paths-ignore: + - "doc/**" + +permissions: + contents: read + +jobs: + build-zip: + permissions: write-all + # run on pushes to any branch + # run on PRs from external forks + if: | + (github.event_name != 'pull_request') + || (github.event.pull_request.head.repo.id != github.event.pull_request.base.repo.id) + name: Build .zip + runs-on: windows-latest + steps: + - + uses: msys2/setup-msys2@v2 + with: + path-type: inherit + install: >- + zip + - + name: Checkout repository + uses: actions/checkout@v4 + - + uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: pnpm/action-setup@v4 + name: Install pnpm + with: + version: 9.0.4 + run_install: false + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Only install direct dependencies + run: pnpm config set auto-install-peers false + - + name: Install all dependencies and symlink for ep_etherpad-lite + shell: msys2 {0} + run: bin/installDeps.sh + - + name: Run the backend tests + shell: msys2 {0} + working-directory: src + run: pnpm test + - + name: Run Etherpad + working-directory: src + run: | + pnpm i + pnpm exec playwright install --with-deps + pnpm run prod & + curl --connect-timeout 10 --max-time 20 --retry 5 --retry-delay 10 --retry-max-time 60 --retry-connrefused http://127.0.0.1:9001/p/test + pnpm exec playwright install chromium --with-deps + pnpm run test-ui --project=chromium + # On release, create release + - name: Generate Changelog + if: ${{startsWith(github.ref, 'refs/tags/v') }} + working-directory: bin + run: pnpm run generateChangelog ${{ github.ref }} > ${{ github.workspace }}-CHANGELOG.txt + - name: Release + uses: softprops/action-gh-release@v2 + if: ${{startsWith(github.ref, 'refs/tags/v') }} + with: + body_path: ${{ github.workspace }}-CHANGELOG.txt + make_latest: true diff --git a/.gitignore b/.gitignore index a3dd9f3b9..71584e76b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,17 +1,30 @@ +/etherpad-win.exe +/etherpad-win.zip node_modules -settings.json +/settings.json !settings.json.template APIKEY.txt -bin/abiword.exe -bin/node.exe -etherpad-lite-win.zip +SESSIONKEY.txt var/dirty.db -bin/convertSettings.json +.env *~ *.patch -src/static/js/jquery.js npm-debug.log *.DS_Store -.ep_initialized *.crt *.key +credentials.json +out/ +.nyc_output +.idea +/package-lock.json +/src/bin/abiword.exe +/src/bin/convertSettings.json +/src/bin/etherpad-1.deb +/src/bin/node.exe +plugin_packages +/src/templates/admin +/src/test-results +playwright-report +state.json +/src/static/oidc diff --git a/.lgtm.yml b/.lgtm.yml new file mode 100644 index 000000000..9dd0f16b6 --- /dev/null +++ b/.lgtm.yml @@ -0,0 +1,9 @@ +extraction: + javascript: + index: + exclude: + - src/static/js/vendors + python: + index: + exclude: + - / diff --git a/.npmrc b/.npmrc new file mode 100644 index 000000000..f301fedf9 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +auto-install-peers=false diff --git a/.travis.yml b/.travis.yml index 77f0c8557..ca8c5380f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,22 +1,145 @@ language: node_js + node_js: - - "0.8" -install: - - "bin/installDeps.sh" - - "export GIT_HASH=$(cat .git/HEAD | head -c 7)" -before_script: - - "tests/frontend/travis/sauce_tunnel.sh" -script: - - "tests/frontend/travis/runner.sh" + - "lts/*" + +services: + - docker + +cache: false + env: global: - - secure: "OxZ2s724S96xu02746LUN+4lBckAe1BOICJjfA4jnFPNpiNU6XoMH52f+LgG\nZzAwu6xMTv+NsaLGp6Avm3cx4GZ+jIiHe4NB9XOgYPa0r0TBIi3ueWYPDyVv\nCniS/4qX68DoFNV4lh7zMBXn0IIPxT4Wppm3desBpjWDP/SdoRs=" - - SAUCE_USER=pita -jdk: - - oraclejdk6 + - secure: "WMGxFkOeTTlhWB+ChMucRtIqVmMbwzYdNHuHQjKCcj8HBEPdZLfCuK/kf4rG\nVLcLQiIsyllqzNhBGVHG1nyqWr0/LTm8JRqSCDDVIhpyzp9KpCJQQJG2Uwjk\n6/HIJJh/wbxsEdLNV2crYU/EiVO3A4Bq0YTHUlbhUqG3mSCr5Ec=" + - secure: "gejXUAHYscbR6Bodw35XexpToqWkv2ifeECsbeEmjaLkYzXmUUNWJGknKSu7\nEUsSfQV8w+hxApr1Z+jNqk9aX3K1I4btL3cwk2trnNI8XRAvu1c1Iv60eerI\nkE82Rsd5lwUaMEh+/HoL8ztFCZamVndoNgX7HWp5J/NRZZMmh4g=" + +_set_loglevel_warn: &set_loglevel_warn | + sed -e 's/"loglevel":[^,]*/"loglevel": "WARN"/' \ + settings.json.template >settings.json.template.new && + mv settings.json.template.new settings.json.template + +_enable_admin_tests: &enable_admin_tests | +sed -e 's/"enableAdminUITests": false/"enableAdminUITests": true,\n"users":{"admin":{"password":"changeme","is_admin":true}}/' \ + settings.json.template >settings.json.template.new && + mv settings.json.template.new settings.json.template + +_install_libreoffice: &install_libreoffice >- + sudo add-apt-repository -y ppa:libreoffice/ppa && + sudo apt-get update && + sudo apt-get -y install libreoffice libreoffice-pdfimport + +# The --legacy-peer-deps flag is required to work around a bug in npm v7: +# https://github.com/npm/cli/issues/2199 +_install_plugins: &install_plugins >- + npm install --no-save --legacy-peer-deps + ep_align + ep_author_hover + ep_cursortrace + ep_font_size + ep_hash_auth + ep_headings2 + ep_markdown + ep_readonly_guest + ep_spellcheck + ep_subscript_and_superscript + ep_table_of_contents + ep_set_title_on_pad + +jobs: + include: + # we can only frontend tests from the ether/ organization and not from forks. + # To request tests to be run ask a maintainer to fork your repo to ether/ + - if: fork = false + name: "Test the Frontend without Plugins" + install: + - *set_loglevel_warn + - *enable_admin_tests + - "src/tests/frontend/travis/sauce_tunnel.sh" + - "bin/installDeps.sh" + - "export GIT_HASH=$(git rev-parse --verify --short HEAD)" + script: + - "./src/tests/frontend/travis/runner.sh" + - name: "Run the Backend tests without Plugins" + install: + - *install_libreoffice + - *set_loglevel_warn + - "bin/installDeps.sh" + - "cd src && pnpm install && cd -" + script: + - "cd src && pnpm test" + - name: "Test the Dockerfile" + install: + - "cd src && pnpm install && cd -" + script: + - "docker build -t etherpad:test ." + - "docker run -d -p 9001:9001 etherpad:test && sleep 3" + - "cd src && pnpm run test-container" + - name: "Load test Etherpad without Plugins" + install: + - *set_loglevel_warn + - "bin/installDeps.sh" + - "cd src && pnpm install && cd -" + - "npm install -g etherpad-load-test" + script: + - "src/tests/frontend/travis/runnerLoadTest.sh" + # we can only frontend tests from the ether/ organization and not from forks. + # To request tests to be run ask a maintainer to fork your repo to ether/ + - if: fork = false + name: "Test the Frontend Plugins only" + install: + - *set_loglevel_warn + - *enable_admin_tests + - "src/tests/frontend/travis/sauce_tunnel.sh" + - "bin/installDeps.sh" + - "rm src/tests/frontend/specs/*" + - *install_plugins + - "export GIT_HASH=$(git rev-parse --verify --short HEAD)" + script: + - "./src/tests/frontend/travis/runner.sh" + - name: "Lint test package-lock.json" + install: + - "npm install lockfile-lint" + script: + - npx lockfile-lint --path src/package-lock.json --validate-https --allowed-hosts npm + - name: "Run the Backend tests with Plugins" + install: + - *install_libreoffice + - *set_loglevel_warn + - "bin/installDeps.sh" + - *install_plugins + - "cd src && pnpm install && cd -" + script: + - "cd src && pnpm test" + - name: "Test the Dockerfile" + install: + - "cd src && pnpm install && cd -" + script: + - "docker build -t etherpad:test ." + - "docker run -d -p 9001:9001 etherpad:test && sleep 3" + - "cd src && pnpm run test-container" + - name: "Load test Etherpad with Plugins" + install: + - *set_loglevel_warn + - "bin/installDeps.sh" + - *install_plugins + - "cd src && npm install && cd -" + - "npm install -g etherpad-load-test" + script: + - "src/tests/frontend/travis/runnerLoadTest.sh" + - name: "Test rate limit" + install: + - "docker network create --subnet=172.23.42.0/16 ep_net" + - "docker build -f Dockerfile -t epl-debian-slim ." + - "docker build -f src/tests/ratelimit/Dockerfile.nginx -t nginx-latest ." + - "docker build -f src/tests/ratelimit/Dockerfile.anotherip -t anotherip ." + - "docker run -p 8081:80 --rm --network ep_net --ip 172.23.42.1 -d nginx-latest" + - "docker run --name etherpad-docker -p 9000:9001 --rm --network ep_net --ip 172.23.42.2 -e 'TRUST_PROXY=true' epl-debian-slim &" + - "docker run --rm --network ep_net --ip 172.23.42.3 --name anotherip -dt anotherip" + - "./bin/installDeps.sh" + script: + - "cd src/tests/ratelimit && bash testlimits.sh" + notifications: - email: - - petermartischka@googlemail.com irc: channels: - - "irc.freenode.org#etherpad-lite-dev" \ No newline at end of file + - "irc.freenode.org#etherpad-lite-dev" diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fac58f2a..e0a70e7dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,1358 @@ +# 2.3.0 + +### Notable enhancements and fixes + +- Added possibility to cluster Etherpads behind reverse proxy. There is now a new reverse proxy designed for Etherpads that handles multiple Etherpads and the created pads in them. It will assign the pad assignement to an Etherpad at random but once the choice was made it will always reverse proxy the same backend. This allows to host multiple concurrent Etherpads and benefit from multi core systems even though one Etherpad is singlethreaded. +- Added reverse proxy configuration for replacing Nginx. In the past there were some issues with nginx and its configuration. This reverse proxy allows you to handle your configuration with ease. + +If you want to find out more about the reverse proxy method check out the repository https://github.com/ether/etherpad-proxy . It also contains a sample docker-compose file with three Etherpads and one etherpad-proxy. Of course you need to adapt the settings.json.template to your liking and map it into the reverse proxy image before you are ready :). + + +- Added client authorization to work with Etherpad. Before it would get blocked because it doesn't have the required claim. As this is now fixed etherpad-proxy can also work with your new OAuth2 configuration and retrieve a token via client credentials flow. + + + + +# 2.2.7 + + +### Notable enhancements and fixes + +- We migrated all important pages to React 19 and React Router v7 + +Besides that only dependency updates. + + + -> Have a merry Christmas and a happy new year. 🎄 🎁 + + +# 2.2.6 + +### Notable enhancements and fixes + +- Added option to delete a pad by the creator. This option can be found in the settings menu. When you click on it you get a confirm dialog and after that you have the chance to completely erase the pad. + + +# 2.2.5 + +### Notable enhancements and fixes + +- Fixed timeslider not scrolling when the revision count is a multiple of 100 +- Added new Restful API for version 2 of Etherpad. It is available at /api-docs + + +# 2.2.4 + +### Notable enhancements and fixes + +- Switched to new SQLite backend +- Fixed rusty-store-kv module not found + + +# 2.2.3 + +### Notable enhancements and fixes + +- Introduced a new in process database `rustydb` that represents a fast key value store written in Rust. +- Readded window._ as a shortcut for getting text +- Added support for migrating any ueberdb database to another. You can now switch as you please. See here: https://docs.etherpad.org/cli.html +- Further Typescript movements +- A lot of security issues fixed and reviewed in this release. Please update. + + +# 2.2.2 + +### Notable enhancements and fixes + +- Removal of Etherpad require kernel: We finally managed to include esbuild to bundle our frontend code together. So no matter how many plugins your server has it is always one JavaScript file. This boosts performance dramatically. +- Added log layoutType: This lets you print the log in either colored or basic (black and white text) +- Introduced esbuild for bundling CSS files +- Cache all files to be bundled in memory for faster load speed + + +# 2.1.1 + + +### Notable enhancements and fixes + +- Fixed failing Docker build when checked out as git submodule. Thanks to @neurolabs +- Fixed: Fallback to websocket and polling when unknown(old) config is present for socket io +- Fixed: Next page disabled if zero page by @samyakj023 +- On CTRL+CLICK bring the window back to focus by Helder Sepulveda + +# 2.1.0 + +### Notable enhancements and fixes + +- Added PWA support. You can now add your Etherpad instance to your home screen on your mobile device or desktop. +- Fixed live plugin manager versions clashing. Thanks to @yacchin1205 +- Fixed a bug in the pad panel where pagination was not working correctly when sorting by pad name + +### Compatibility changes + +- Reintroduced APIKey.txt support. You can now switch between APIKey and OAuth2.0 authentication. This can be toggled with the setting authenticationMethod. The default is OAuth2. If you want to use the APIKey method you can set that to `apikey`. + + +# 2.0.3 + +### Notable enhancements and fixes + +- Added documentation for replacing apikeys with oauth2 +- Bumped live plugin manager to 0.20.0. Thanks to @fgreinacher +- Added better documentation for using docker-compose with Etherpad + + + +# 2.0.2 + +### Notable enhancements and fixes + +- Fixed the locale loading in the admin panel +- Added OAuth2.0 support for the Etherpad API. You can now log in into the Etherpad API with your admin user using OAuth2 + +### Compatibility changes + +- The tests now require generating a token from the OAuth secret. You can find the `generateJWTToken` in the common.ts script for plugin endpoint updates. + + +# 2.0.1 + +### Notable enhancements and fixes + +- Fixed a bug where a plugin depending on a scoped dependency would not install successfully. + + +# 2.0.0 + + +### Compatibility changes + +- Socket io has been updated to 4.7.5. This means that the json.send function won't work anymore and needs to be changed to .emit('message', myObj) +- Deprecating npm version 6 in favor of pnpm: We have made the decision to switch to the well established pnpm (https://pnpm.io/). It works by symlinking dependencies into a global directory allowing you to have a cleaner and more reliable environment. +- Introducing Typescript to the Etherpad core: Etherpad core logic has been rewritten in Typescript allowing for compiler checking of errors. +- Rewritten Admin Panel: The Admin panel has been rewritten in React and now features a more pleasant user experience. It now also features an integrated pad searching with sorting functionality. + +### Notable enhancements and fixes + +* Bugfixes + - Live Plugin Manager: The live plugin manager caused problems when a plugin had depdendencies defined. This issue is now resolved. + +* Enhancements + - pnpm Workspaces: In addition to pnpm we introduced workspaces. A clean way to manage multiple bounded contexts like the admin panel or the bin folder. + - Bin folder: The bin folder has been moved from the src folder to the root folder. This change was necessary as the contained scripts do not represent core functionality of the user. + - Starting Etherpad: Etherpad can now be started with a single command: `pnpm run prod` in the root directory. + - Installing Etherpad: Etherpad no longer symlinks itself in the root directory. This is now also taken care by pnpm, and it just creates a node_modules folder with the src directory`s ep_etherpad-lite folder + - Plugins can now be installed simply via the command: `pnpm run plugins i first-plugin second-plugin` or if you want to install from path you can do: + `pnpm run plugins i --path ../path-to-plugin` + + +# 1.9.7 + +### Notable enhancements and fixes + +* Added Live Plugin Manager: Plugins are now installed into a separate folder on the host system. This folder is called `plugin_packages`. +That way the plugins are separated from the normal etherpad installation. +* Make repairPad.js more verbose +* Fixed favicon not being loaded correctly + +# 1.9.6 + +### Notable enhancements and fixes + +* Prevent etherpad crash when update server is not reachable +* Use npm@6 in Docker build +* Fix setting the log level in settings.json + + +# 1.9.5 + +### Compatibility changes + +* This version deprecates NodeJS16 as it reached its end of life and won't receive any updates. So to get started with Etherpad v1.9.5 you need NodeJS 18 and above. +* The bundled windows NodeJS version has been bumped to the current LTS version 20. + +### Notable enhancements and fixes + +* The support for the tidy program to tidy up HTML files has been removed. This decision was made because it hasn't been updated for years and also caused an incompability when exporting a pad with Abiword. + + +# 1.9.4 + +### Compatibility changes + +* Log4js has been updated to the latest version. As it involved a bump of 6 major version. + A lot has changed since then. Most notably the console appender has been deprecated. You can find out more about it [here](https://github.com/log4js-node/log4js-node) + +### Notable enhancements and fixes + +* Fix for MySQL: The logger calls were incorrectly configured leading to a crash when e.g. somebody uses a different encoding than standard MySQL encoding. + +# 1.9.3 + +### Compability changes + +* express-rate-limit has been bumped to 7.0.0: This involves the breaking change that "max: 0" +in the importExportRateLimiting is set to always trigger. So set it to your desired value. +If you haven't changed that value in the settings.json you are all set. + +### Notable enhancements and fixes + +* Bugfixes + * Fix etherpad crashing with mongodb database + +* Enhancements + * Add surrealdb database support. You can find out more about this database [here](https://surrealdb.com). + * Make sqlite faster: The sqlite library has been switched to better-sqlite3. This should lead to better performance. + +# 1.9.2 + +### Notable enhancements and fixes + +* Security + * Enable session key rotation: This setting can be enabled in the settings.json. It changes the signing key for the cookie authentication in a fixed interval. + +* Bugfixes + * Fix appendRevision when creating a new pad via the API without a text. + + +* Enhancements + * Bump JQuery to version 3.7 + * Update elasticsearch connector to version 8 + +### Compatibility changes + +* No compability changes as JQuery maintains excellent backwards compatibility. + +#### For plugin authors + +* Please update to JQuery 3.7. There is an excellent deprecation guide over [here](https://api.jquery.com/category/deprecated/). Version 3.1 to 3.7 are relevant for the upgrade. + +# 1.9.1 + +### Notable enhancements and fixes + +* Security + * Limit requested revisions in timeslider and export to head revision. (affects v1.9.0) + +* Bugfixes + * revisions in `CHANGESET_REQ` (timeslider) and export (txt, html, custom) + are now checked to be numbers. + * bump sql for audit fix +* Enhancements + * Add keybinding meta-backspace to delete to beginning of line + * Fix automatic Windows build via GitHub Actions + * Enable docs to be build cross platform thanks to asciidoctor + +### Compatibility changes +* tests: drop windows 7 test coverage & use chrome latest for admin tests +* Require Node 16 for Etherpad and target Node 20 for testing + + +# 1.9.0 + +### Notable enhancements and fixes + +* Windows build: + * The bundled `node.exe` was upgraded from v12 to v16. + * The bundled `node.exe` is now a 64-bit executable. If you need the 32-bit + version you must download and install Node.js yourself. +* Improvements to login session management: + * `express_sid` cookies and `sessionstorage:*` database records are no longer + created unless `requireAuthentication` is `true` (or a plugin causes them to + be created). + * Login sessions now have a finite lifetime by default (10 days after + leaving). + * `sessionstorage:*` database records are automatically deleted when the login + session expires (with some exceptions that will be fixed in the future). + * Requests for static content (e.g., `/robots.txt`) and special pages (e.g., + the HTTP API, `/stats`) no longer create login session state. + * The secret used to sign the `express_sid` cookie is now automatically + regenerated every day (called *key rotation*) by default. If key rotation is + enabled, the now-deprecated `SESSIONKEY.txt` file can be safely deleted + after Etherpad starts up (its content is read and saved to the database and + used to validate signatures from old cookies until they expire). +* The following settings from `settings.json` are now applied as expected (they + were unintentionally ignored before): + * `padOptions.lang` + * `padOptions.showChat` + * `padOptions.userColor` + * `padOptions.userName` +* HTTP API: + * Fixed the return value of `getText` when called with a specific revision. + * Fixed a potential attribute pool corruption bug with + `copyPadWithoutHistory`. + * Mappings created by `createGroupIfNotExistsFor` are now removed from the + database when the group is deleted. + * Fixed race conditions in the `setText`, `appendText`, and `restoreRevision` + functions. + * Added an optional `authorId` parameter to `appendText`, + `copyPadWithoutHistory`, `createGroupPad`, `createPad`, `restoreRevision`, + `setHTML`, and `setText`, and bumped the latest API version to 1.3.0. +* Fixed a crash if the database is busy enough to cause a query timeout. +* New `/health` endpoint for getting information about Etherpad's health (see + [draft-inadarei-api-health-check-06](https://www.ietf.org/archive/id/draft-inadarei-api-health-check-06.html)). +* Docker now uses the new `/health` endpoint for health checks, which avoids + issues when authentication is enabled. It also avoids the unnecessary creation + of database records for managing browser sessions. +* When copying a pad, the pad's records are copied in batches to avoid database + timeouts with large pads. +* Exporting a large pad to `.etherpad` format should be faster thanks to bulk + database record fetches. +* When importing an `.etherpad` file, records are now saved to the database in + batches to avoid database timeouts with large pads. + +#### For plugin authors + +* New `expressPreSession` server-side hook. +* Pad server-side hook changes: + * `padCheck`: New hook. + * `padCopy`: New `srcPad` and `dstPad` context properties. + * `padDefaultContent`: New hook. + * `padRemove`: New `pad` context property. +* The `db` property on Pad objects is now public. +* New `getAuthorId` server-side hook. +* New APIs for processing attributes: `ep_etherpad-lite/static/js/attributes` + (low-level API) and `ep_etherpad-lite/static/js/AttributeMap` (high-level + API). +* The `import` server-side hook has a new `ImportError` context property. +* New `exportEtherpad` and `importEtherpad` server-side hooks. +* The `handleMessageSecurity` and `handleMessage` server-side hooks have a new + `sessionInfo` context property that includes the user's author ID, the pad ID, + and whether the user only has read-only access. +* The `handleMessageSecurity` server-side hook can now be used to grant write + access for the current message only. +* The `init_` server-side hooks have a new `logger` context + property that plugins can use to log messages. +* Prevent infinite loop when exiting the server +* Bump dependencies + + +### Compatibility changes + +* Node.js v14.15.0 or later is now required. +* The default login session expiration (applicable if `requireAuthentication` is + `true`) changed from never to 10 days after the user leaves. + +#### For plugin authors + +* The `client` context property for the `handleMessageSecurity` and + `handleMessage` server-side hooks is deprecated; use the `socket` context + property instead. +* Pad server-side hook changes: + * `padCopy`: + * The `originalPad` context property is deprecated; use `srcPad` instead. + * The `destinationID` context property is deprecated; use `dstPad.id` + instead. + * `padCreate`: The `author` context property is deprecated; use the new + `authorId` context property instead. Also, the hook now runs asynchronously. + * `padLoad`: Now runs when a temporary Pad object is created during import. + Also, it now runs asynchronously. + * `padRemove`: The `padID` context property is deprecated; use `pad.id` + instead. + * `padUpdate`: The `author` context property is deprecated; use the new + `authorId` context property instead. Also, the hook now runs asynchronously. +* Returning `true` from a `handleMessageSecurity` hook function is deprecated; + return `'permitOnce'` instead. +* Changes to the `src/static/js/Changeset.js` library: + * The following attribute processing functions are deprecated (use the new + attribute APIs instead): + * `attribsAttributeValue()` + * `eachAttribNumber()` + * `makeAttribsString()` + * `opAttributeValue()` + * `opIterator()`: Deprecated in favor of the new `deserializeOps()` generator + function. + * `appendATextToAssembler()`: Deprecated in favor of the new `opsFromAText()` + generator function. + * `newOp()`: Deprecated in favor of the new `Op` class. +* The `AuthorManager.getAuthor4Token()` function is deprecated; use the new + `AuthorManager.getAuthorId()` function instead. +* The exported database records covered by the `exportEtherpadAdditionalContent` + server-side hook now include keys like `${customPrefix}:${padId}:*`, not just + `${customPrefix}:${padId}`. +* Plugin locales should overwrite core's locales Stale +* Plugin locales overwrite core locales + +# 1.8.18 + +Released: 2022-05-05 + +### Notable enhancements and fixes + + * Upgraded ueberDB to fix a regression with CouchDB. + +# 1.8.17 + +Released: 2022-02-23 + +### Security fixes + +* Fixed a vunlerability in the `CHANGESET_REQ` message handler that allowed a + user with any access to read any pad if the pad ID is known. + +### Notable enhancements and fixes + +* Fixed a bug that caused all pad edit messages received at the server to go + through a single queue. Now there is a separate queue per pad as intended, + which should reduce message processing latency when many pads are active at + the same time. + +# 1.8.16 + +### Security fixes + +If you cannot upgrade to v1.8.16 for some reason, you are encouraged to try +cherry-picking the fixes to the version you are running: + +```shell +git cherry-pick b7065eb9a0ec..77bcb507b30e +``` + +* Maliciously crafted `.etherpad` files can no longer overwrite arbitrary + non-pad database records when imported. +* Imported `.etherpad` files are now subject to numerous consistency checks + before any records are written to the database. This should help avoid + denial-of-service attacks via imports of malformed `.etherpad` files. + +### Notable enhancements and fixes + +* Fixed several `.etherpad` import bugs. +* Improved support for large `.etherpad` imports. + +# 1.8.15 + +### Security fixes + +* Fixed leak of the writable pad ID when exporting from the pad's read-only ID. + This only matters if you treat the writeable pad IDs as secret (e.g., you are + not using [ep_padlist2](https://www.npmjs.com/package/ep_padlist2)) and you + share the pad's read-only ID with untrusted users. Instead of treating + writeable pad IDs as secret, you are encouraged to take advantage of + Etherpad's authentication and authorization mechanisms (e.g., use + [ep_openid_connect](https://www.npmjs.com/package/ep_openid_connect) with + [ep_readonly_guest](https://www.npmjs.com/package/ep_readonly_guest), or write + your own + [authentication](https://etherpad.org/doc/v1.8.14/#index_authenticate) and + [authorization](https://etherpad.org/doc/v1.8.14/#index_authorize) plugins). +* Updated dependencies. + +### Compatibility changes + +* The `logconfig` setting is deprecated. + +#### For plugin authors + +* Etherpad now uses [jsdom](https://github.com/jsdom/jsdom) instead of + [cheerio](https://cheerio.js.org/) for processing HTML imports. There are two + consequences of this change: + * `require('ep_etherpad-lite/node_modules/cheerio')` no longer works. To fix, + your plugin should directly depend on `cheerio` and do `require('cheerio')`. + * The `collectContentImage` hook's `node` context property is now an + [`HTMLImageElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement) + object rather than a Cheerio Node-like object, so the API is slightly + different. See + [citizenos/ep_image_upload#49](https://github.com/citizenos/ep_image_upload/pull/49) + for an example fix. +* The `clientReady` server-side hook is deprecated; use the new `userJoin` hook + instead. +* The `init_` server-side hooks are now run every time Etherpad + starts up, not just the first time after the named plugin is installed. +* The `userLeave` server-side hook's context properties have changed: + * `auth`: Deprecated. + * `author`: Deprecated; use the new `authorId` property instead. + * `readonly`: Deprecated; use the new `readOnly` property instead. + * `rev`: Deprecated. +* Changes to the `src/static/js/Changeset.js` library: + * `opIterator()`: The unused start index parameter has been removed, as has + the unused `lastIndex()` method on the returned object. + * `smartOpAssembler()`: The returned object's `appendOpWithText()` method is + deprecated without a replacement available to plugins (if you need one, let + us know and we can make the private `opsFromText()` function public). + * Several functions that should have never been public are no longer exported: + `applyZip()`, `assert()`, `clearOp()`, `cloneOp()`, `copyOp()`, `error()`, + `followAttributes()`, `opString()`, `stringOp()`, `textLinesMutator()`, + `toBaseTen()`, `toSplices()`. + +### Notable enhancements and fixes + +* Accessibility fix for JAWS screen readers. +* Fixed "clear authorship" error (see issue #5128). +* Etherpad now considers square brackets to be valid URL characters. +* The server no longer crashes if an exception is thrown while processing a + message from a client. +* The `useMonospaceFontGlobal` setting now works (thanks @Lastpixl!). +* Chat improvements: + * The message input field is now a text area, allowing multi-line messages + (use shift-enter to insert a newline). + * Whitespace in chat messages is now preserved. +* Docker improvements: + * New `HEALTHCHECK` instruction (thanks @Gared!). + * New `settings.json` variables: `DB_COLLECTION`, `DB_URL`, + `SOCKETIO_MAX_HTTP_BUFFER_SIZE`, `DUMP_ON_UNCLEAN_EXIT` (thanks + @JustAnotherArchivist!). + * `.ep_initialized` files are no longer created. +* Worked around a [Firefox Content Security Policy + bug](https://bugzilla.mozilla.org/show_bug.cgi?id=1721296) that caused CSP + failures when `'self'` was in the CSP header. See issue #4975 for details. +* UeberDB upgraded from v1.4.10 to v1.4.18. For details, see the [ueberDB + changelog](https://github.com/ether/ueberDB/blob/master/CHANGELOG.md). + Highlights: + * The `postgrespool` driver was renamed to `postgres`, replacing the old + driver of that name. If you used the old `postgres` driver, you may see an + increase in the number of database connections. + * For `postgres`, you can now set the `dbSettings` value in `settings.json` to + a connection string (e.g., `"postgres://user:password@host/dbname"`) instead + of an object. + * For `mongodb`, the `dbName` setting was renamed to `database` (but `dbName` + still works for backwards compatibility) and is now optional (if unset, the + database name in `url` is used). +* `/admin/settings` now honors the `--settings` command-line argument. +* Fixed "Author *X* tried to submit changes as author *Y*" detection. +* Error message display improvements. +* Simplified pad reload after importing an `.etherpad` file. + +#### For plugin authors + +* `clientVars` was added to the context for the `postAceInit` client-side hook. + Plugins should use this instead of the `clientVars` global variable. +* New `userJoin` server-side hook. +* The `userLeave` server-side hook has a new `socket` context property. +* The `helper.aNewPad()` function (accessible to client-side tests) now + accepts hook functions to inject when opening a pad. This can be used to + test any new client-side hooks your plugin provides. +* Chat improvements: + * The `chatNewMessage` client-side hook context has new properties: + * `message`: Provides access to the raw message object so that plugins can + see the original unprocessed message text and any added metadata. + * `rendered`: Allows plugins to completely override how the message is + rendered in the UI. + * New `chatSendMessage` client-side hook that enables plugins to process the + text before sending it to the server or augment the message object with + custom metadata. + * New `chatNewMessage` server-side hook to process new chat messages before + they are saved to the database and relayed to users. +* Readability improvements to browser-side error stack traces. +* Added support for socket.io message acknowledgments. + +# 1.8.14 + +### Security fixes + +* Fixed a persistent XSS vulnerability in the Chat component. In case you can't + update to 1.8.14 directly, we strongly recommend to cherry-pick + a7968115581e20ef47a533e030f59f830486bdfa. Thanks to sonarsource for the + professional disclosure. + +### Compatibility changes + +* Node.js v12.13.0 or later is now required. +* The `favicon` setting is now interpreted as a pathname to a favicon file, not + a URL. Please see the documentation comment in `settings.json.template`. +* The undocumented `faviconPad` and `faviconTimeslider` settings have been + removed. +* MySQL/MariaDB now uses connection pooling, which means you will see up to 10 + connections to the MySQL/MariaDB server (by default) instead of 1. This might + cause Etherpad to crash with a "ER_CON_COUNT_ERROR: Too many connections" + error if your server is configured with a low connection limit. +* Changes to environment variable substitution in `settings.json` (see the + documentation comments in `settings.json.template` for details): + * An environment variable set to the string "null" now becomes `null` instead + of the string "null". Similarly, if the environment variable is unset and + the default value is "null" (e.g., `"${UNSET_VAR:null}"`), the value now + becomes `null` instead of the string "null". It is no longer possible to + produce the string "null" via environment variable substitution. + * An environment variable set to the string "undefined" now causes the setting + to be removed instead of set to the string "undefined". Similarly, if the + environment variable is unset and the default value is "undefined" (e.g., + `"${UNSET_VAR:undefined}"`), the setting is now removed instead of set to + the string "undefined". It is no longer possible to produce the string + "undefined" via environment variable substitution. + * Support for unset variables without a default value is now deprecated. + Please change all instances of `"${FOO}"` in your `settings.json` to + `${FOO:null}` to keep the current behavior. + * The `DB_*` variable substitutions in `settings.json.docker` that previously + defaulted to `null` now default to "undefined". +* Calling `next` without argument when using `Changeset.opIterator` does always + return a new Op. See b9753dcc7156d8471a5aa5b6c9b85af47f630aa8 for details. + +### Notable enhancements and fixes + +* MySQL/MariaDB now uses connection pooling, which should improve stability and + reduce latency. +* Bulk database writes are now retried individually on write failure. +* Minify: Avoid crash due to unhandled Promise rejection if stat fails. +* padIds are now included in /socket.io query string, e.g. + `https://video.etherpad.com/socket.io/?padId=AWESOME&EIO=3&transport=websocket&t=...&sid=...`. + This is useful for directing pads to separate socket.io nodes. +* + + diff --git a/admin/package.json b/admin/package.json new file mode 100644 index 000000000..0c9be67ed --- /dev/null +++ b/admin/package.json @@ -0,0 +1,42 @@ +{ + "name": "admin", + "private": true, + "version": "2.3.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", + "build-copy": "tsc && vite build --outDir ../src/templates/admin --emptyOutDir", + "preview": "vite preview" + }, + "dependencies": { + "@radix-ui/react-switch": "^1.2.2" + }, + "devDependencies": { + "@radix-ui/react-dialog": "^1.1.11", + "@radix-ui/react-toast": "^1.2.11", + "@types/react": "^19.1.2", + "@types/react-dom": "^19.1.3", + "@typescript-eslint/eslint-plugin": "^8.31.1", + "@typescript-eslint/parser": "^8.31.1", + "@vitejs/plugin-react-swc": "^3.9.0", + "eslint": "^9.26.0", + "eslint-plugin-react-hooks": "^5.2.0", + "eslint-plugin-react-refresh": "^0.4.20", + "i18next": "^25.0.2", + "i18next-browser-languagedetector": "^8.1.0", + "lucide-react": "^0.507.0", + "react": "^19.1.0", + "react-dom": "^19.1.0", + "react-hook-form": "^7.56.2", + "react-i18next": "^15.5.1", + "react-router-dom": "^7.5.3", + "socket.io-client": "^4.8.1", + "typescript": "^5.8.2", + "vite": "^6.3.5", + "vite-plugin-static-copy": "^2.3.1", + "vite-plugin-svgr": "^4.3.0", + "zustand": "^5.0.4" + } +} diff --git a/admin/public/Karla-Bold.ttf b/admin/public/Karla-Bold.ttf new file mode 100644 index 000000000..2348e0072 Binary files /dev/null and b/admin/public/Karla-Bold.ttf differ diff --git a/admin/public/Karla-BoldItalic.ttf b/admin/public/Karla-BoldItalic.ttf new file mode 100644 index 000000000..3c0e045ec Binary files /dev/null and b/admin/public/Karla-BoldItalic.ttf differ diff --git a/admin/public/Karla-ExtraBold.ttf b/admin/public/Karla-ExtraBold.ttf new file mode 100644 index 000000000..f18471195 Binary files /dev/null and b/admin/public/Karla-ExtraBold.ttf differ diff --git a/admin/public/Karla-ExtraBoldItalic.ttf b/admin/public/Karla-ExtraBoldItalic.ttf new file mode 100644 index 000000000..3799659c0 Binary files /dev/null and b/admin/public/Karla-ExtraBoldItalic.ttf differ diff --git a/admin/public/Karla-ExtraLight.ttf b/admin/public/Karla-ExtraLight.ttf new file mode 100644 index 000000000..0f8642c02 Binary files /dev/null and b/admin/public/Karla-ExtraLight.ttf differ diff --git a/admin/public/Karla-ExtraLightItalic.ttf b/admin/public/Karla-ExtraLightItalic.ttf new file mode 100644 index 000000000..bb328e175 Binary files /dev/null and b/admin/public/Karla-ExtraLightItalic.ttf differ diff --git a/admin/public/Karla-Italic.ttf b/admin/public/Karla-Italic.ttf new file mode 100644 index 000000000..1853cbe4e Binary files /dev/null and b/admin/public/Karla-Italic.ttf differ diff --git a/admin/public/Karla-Light.ttf b/admin/public/Karla-Light.ttf new file mode 100644 index 000000000..46457ece7 Binary files /dev/null and b/admin/public/Karla-Light.ttf differ diff --git a/admin/public/Karla-LightItalic.ttf b/admin/public/Karla-LightItalic.ttf new file mode 100644 index 000000000..3b0f01ff1 Binary files /dev/null and b/admin/public/Karla-LightItalic.ttf differ diff --git a/admin/public/Karla-Medium.ttf b/admin/public/Karla-Medium.ttf new file mode 100644 index 000000000..9066b49c4 Binary files /dev/null and b/admin/public/Karla-Medium.ttf differ diff --git a/admin/public/Karla-MediumItalic.ttf b/admin/public/Karla-MediumItalic.ttf new file mode 100644 index 000000000..ea9535355 Binary files /dev/null and b/admin/public/Karla-MediumItalic.ttf differ diff --git a/admin/public/Karla-Regular.ttf b/admin/public/Karla-Regular.ttf new file mode 100644 index 000000000..c164d0047 Binary files /dev/null and b/admin/public/Karla-Regular.ttf differ diff --git a/admin/public/Karla-SemiBold.ttf b/admin/public/Karla-SemiBold.ttf new file mode 100644 index 000000000..82e0c5abf Binary files /dev/null and b/admin/public/Karla-SemiBold.ttf differ diff --git a/admin/public/Karla-SemiBoldItalic.ttf b/admin/public/Karla-SemiBoldItalic.ttf new file mode 100644 index 000000000..77c19ef69 Binary files /dev/null and b/admin/public/Karla-SemiBoldItalic.ttf differ diff --git a/admin/public/ep_admin_pads/ar.json b/admin/public/ep_admin_pads/ar.json new file mode 100644 index 000000000..746946edf --- /dev/null +++ b/admin/public/ep_admin_pads/ar.json @@ -0,0 +1,28 @@ +{ + "@metadata": { + "authors": [ + "Meno25", + "محمد أحمد عبد الفتاح" + ] + }, + "ep_adminpads2_action": "فعل", + "ep_adminpads2_autoupdate-label": "التحديث التلقائي على تغييرات الوسادة", + "ep_adminpads2_autoupdate.title": "لتمكين أو تعطيل التحديثات التلقائية للاستعلام الحالي.", + "ep_adminpads2_confirm": "هل تريد حقًا حذف الوسادة {{padID}}؟", + "ep_adminpads2_delete.value": "حذف", + "ep_adminpads2_last-edited": "آخر تعديل", + "ep_adminpads2_loading": "جارٍ التحميل...", + "ep_adminpads2_manage-pads": "إدارة الفوط", + "ep_adminpads2_no-results": "لا توجد نتائج.", + "ep_adminpads2_pad-user-count": "عدد المستخدمين الوسادة", + "ep_adminpads2_padname": "بادنام", + "ep_adminpads2_search-box.placeholder": "مصطلح البحث", + "ep_adminpads2_search-button.value": "بحث", + "ep_adminpads2_search-done": "اكتمل البحث", + "ep_adminpads2_search-error-explanation": "واجه الخادم خطأً أثناء البحث عن منصات:", + "ep_adminpads2_search-error-title": "فشل في الحصول على قائمة الوسادة", + "ep_adminpads2_search-heading": "ابحث عن الفوط", + "ep_adminpads2_title": "إدارة الوسادة", + "ep_adminpads2_unknown-error": "خطأ غير معروف", + "ep_adminpads2_unknown-status": "حالة غير معروفة" +} diff --git a/admin/public/ep_admin_pads/bn.json b/admin/public/ep_admin_pads/bn.json new file mode 100644 index 000000000..0048b52bb --- /dev/null +++ b/admin/public/ep_admin_pads/bn.json @@ -0,0 +1,23 @@ +{ + "@metadata": { + "authors": [ + "আজিজ", + "আফতাবুজ্জামান" + ] + }, + "ep_adminpads2_action": "কার্য", + "ep_adminpads2_delete.value": "মুছে ফেলুন", + "ep_adminpads2_last-edited": "সর্বশেষ সম্পাদিত", + "ep_adminpads2_loading": "লোড হচ্ছে...", + "ep_adminpads2_manage-pads": "প্যাড পরিচালনা করুন", + "ep_adminpads2_no-results": "ফলাফল নেই", + "ep_adminpads2_padname": "প্যাডের নাম", + "ep_adminpads2_search-button.value": "অনুসন্ধান", + "ep_adminpads2_search-done": "অনুসন্ধান সম্পূর্ণ", + "ep_adminpads2_search-error-explanation": "প্যাড অনুসন্ধান করার সময় সার্ভার একটি ত্রুটির সম্মুখীন হয়েছে:", + "ep_adminpads2_search-error-title": "প্যাডের তালিকা পেতে ব্যর্থ", + "ep_adminpads2_search-heading": "প্যাড অনুসন্ধান করুন", + "ep_adminpads2_title": "প্যাড প্রশাসন", + "ep_adminpads2_unknown-error": "অজানা ত্রুটি", + "ep_adminpads2_unknown-status": "অজানা অবস্থা" +} diff --git a/admin/public/ep_admin_pads/ca.json b/admin/public/ep_admin_pads/ca.json new file mode 100644 index 000000000..1d4e34216 --- /dev/null +++ b/admin/public/ep_admin_pads/ca.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Mguix" + ] + }, + "ep_adminpads2_action": "Acció", + "ep_adminpads2_autoupdate-label": "Actualització automàtica en cas de canvis de pad", + "ep_adminpads2_autoupdate.title": "Activa o desactiva les actualitzacions automàtiques per a la consulta actual.", + "ep_adminpads2_confirm": "Esteu segur que voleu suprimir el pad {{padID}}?", + "ep_adminpads2_delete.value": "Esborrar", + "ep_adminpads2_last-edited": "Darrera modificació", + "ep_adminpads2_loading": "S’està carregant…", + "ep_adminpads2_manage-pads": "Gestiona els pads", + "ep_adminpads2_no-results": "No hi ha cap resultat", + "ep_adminpads2_pad-user-count": "Nombre d'usuaris de pads", + "ep_adminpads2_padname": "Nom del pad", + "ep_adminpads2_search-box.placeholder": "Terme de cerca", + "ep_adminpads2_search-button.value": "Cercar", + "ep_adminpads2_search-done": "Cerca completa", + "ep_adminpads2_search-error-explanation": "El servidor ha trobat un error mentre buscava pads:", + "ep_adminpads2_search-error-title": "No s'ha pogut obtenir la llista del pad", + "ep_adminpads2_search-heading": "Cerca pads", + "ep_adminpads2_title": "Administració del pad", + "ep_adminpads2_unknown-error": "Error desconegut", + "ep_adminpads2_unknown-status": "Estat desconegut" +} diff --git a/admin/public/ep_admin_pads/cs.json b/admin/public/ep_admin_pads/cs.json new file mode 100644 index 000000000..19e92894d --- /dev/null +++ b/admin/public/ep_admin_pads/cs.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Spotter" + ] + }, + "ep_adminpads2_action": "Akce", + "ep_adminpads2_autoupdate-label": "Automatická aktualizace změn Padu", + "ep_adminpads2_autoupdate.title": "Povolí nebo zakáže automatické aktualizace pro aktuální dotaz.", + "ep_adminpads2_confirm": "Opravdu chcete odstranit pad {{padID}}?", + "ep_adminpads2_delete.value": "Smazat", + "ep_adminpads2_last-edited": "Naposledy upraveno", + "ep_adminpads2_loading": "Načítání…", + "ep_adminpads2_manage-pads": "Spravovat pady", + "ep_adminpads2_no-results": "Žádné výsledky", + "ep_adminpads2_pad-user-count": "Počet uživatelů padu", + "ep_adminpads2_padname": "Název padu", + "ep_adminpads2_search-box.placeholder": "Hledaný výraz", + "ep_adminpads2_search-button.value": "Hledat", + "ep_adminpads2_search-done": "Hledání dokončeno", + "ep_adminpads2_search-error-explanation": "Při hledání padů došlo k chybě serveru:", + "ep_adminpads2_search-error-title": "Seznam padů se nepodařilo získat", + "ep_adminpads2_search-heading": "Hledat pady", + "ep_adminpads2_title": "Správa Padu", + "ep_adminpads2_unknown-error": "Neznámá chyba", + "ep_adminpads2_unknown-status": "Neznámý stav" +} diff --git a/admin/public/ep_admin_pads/cy.json b/admin/public/ep_admin_pads/cy.json new file mode 100644 index 000000000..02546da90 --- /dev/null +++ b/admin/public/ep_admin_pads/cy.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Robin Owain" + ] + }, + "ep_adminpads2_action": "Gweithred", + "ep_adminpads2_autoupdate-label": "Diweddaru newidiadau pad yn otomatig", + "ep_adminpads2_autoupdate.title": "Galluogi neu analluogi diweddaru'r ymholiad cyfredol.", + "ep_adminpads2_confirm": "Siwr eich bod am ddileu'r pad {{padID}}?", + "ep_adminpads2_delete.value": "Dileu", + "ep_adminpads2_last-edited": "Golygwyd ddiwethaf", + "ep_adminpads2_loading": "Wrthi'n llwytho...", + "ep_adminpads2_manage-pads": "Rheoli'r padiau", + "ep_adminpads2_no-results": "Dim canlyniad", + "ep_adminpads2_pad-user-count": "Cyfri defnyddiwr pad", + "ep_adminpads2_padname": "Enwpad", + "ep_adminpads2_search-box.placeholder": "Term chwilio", + "ep_adminpads2_search-button.value": "Chwilio", + "ep_adminpads2_search-done": "Wedi gorffen", + "ep_adminpads2_search-error-explanation": "Nam ar y gweinydd wrth chwilio'r padiau:", + "ep_adminpads2_search-error-title": "Methwyd a chael y rhestr pad", + "ep_adminpads2_search-heading": "Chwilio am badiau", + "ep_adminpads2_title": "Gweinyddiaeth y pad", + "ep_adminpads2_unknown-error": "Nam o ryw fath", + "ep_adminpads2_unknown-status": "Statws anhysbys" +} diff --git a/admin/public/ep_admin_pads/da.json b/admin/public/ep_admin_pads/da.json new file mode 100644 index 000000000..a5303b9cb --- /dev/null +++ b/admin/public/ep_admin_pads/da.json @@ -0,0 +1,14 @@ +{ + "@metadata": { + "authors": [ + "Saederup92" + ] + }, + "ep_adminpads2_action": "Handling", + "ep_adminpads2_delete.value": "Slet", + "ep_adminpads2_last-edited": "Sidst redigeret", + "ep_adminpads2_loading": "Indlæser...", + "ep_adminpads2_no-results": "Ingen resultater", + "ep_adminpads2_unknown-error": "Ukendt fejl", + "ep_adminpads2_unknown-status": "Ukendt status" +} diff --git a/admin/public/ep_admin_pads/de.json b/admin/public/ep_admin_pads/de.json new file mode 100644 index 000000000..67dd73ddf --- /dev/null +++ b/admin/public/ep_admin_pads/de.json @@ -0,0 +1,33 @@ +{ + "@metadata": { + "authors": [ + "Brettchenweber", + "Justman10000", + "Lorisobi", + "SamTV", + "Umlaut", + "Zunkelty" + ] + }, + "ep_adminpads2_action": "Aktion", + "ep_adminpads2_autoupdate-label": "Automatisch bei Pad-Änderungen updaten", + "ep_adminpads2_autoupdate.title": "Aktiviert oder deaktiviert automatische Aktualisierungen für die aktuelle Abfrage.", + "ep_adminpads2_confirm": "Willst du das Pad {{padID}} wirklich löschen?", + "ep_adminpads2_delete.value": "Löschen", + "ep_adminpads2_cleanup": "Historie aufräumen", + "ep_adminpads2_last-edited": "Zuletzt bearbeitet", + "ep_adminpads2_loading": "Lädt...", + "ep_adminpads2_manage-pads": "Pads verwalten", + "ep_adminpads2_no-results": "Keine Ergebnisse", + "ep_adminpads2_pad-user-count": "Nutzerzahl des Pads", + "ep_adminpads2_padname": "Padname", + "ep_adminpads2_search-box.placeholder": "Suchbegriff", + "ep_adminpads2_search-button.value": "Suche", + "ep_adminpads2_search-done": "Suche vollendet", + "ep_adminpads2_search-error-explanation": "Der Server ist bei der Suche nach Pads auf einen Fehler gestoßen:", + "ep_adminpads2_search-error-title": "Pad-Liste konnte nicht abgerufen werden", + "ep_adminpads2_search-heading": "Nach Pads suchen", + "ep_adminpads2_title": "Pad-Verwaltung", + "ep_adminpads2_unknown-error": "Unbekannter Fehler", + "ep_adminpads2_unknown-status": "Unbekannter Status" +} diff --git a/admin/public/ep_admin_pads/diq.json b/admin/public/ep_admin_pads/diq.json new file mode 100644 index 000000000..983680965 --- /dev/null +++ b/admin/public/ep_admin_pads/diq.json @@ -0,0 +1,28 @@ +{ + "@metadata": { + "authors": [ + "1917 Ekim Devrimi", + "Mirzali" + ] + }, + "ep_adminpads2_action": "Hereketi", + "ep_adminpads2_autoupdate-label": "Vurnayışanê pedi otomatik rocane kerê", + "ep_adminpads2_autoupdate.title": "Persê mewcudi rê rocaneyışanê otomatika aktiv ke ya zi dewrê ra vecê", + "ep_adminpads2_confirm": "Şıma qayılê pedê {{padID}} bıesternê?", + "ep_adminpads2_delete.value": "Bestere", + "ep_adminpads2_last-edited": "Vurnayışo peyên", + "ep_adminpads2_loading": "Bar beno...", + "ep_adminpads2_manage-pads": "Pedan idare kerê", + "ep_adminpads2_no-results": "Netice çıniyo", + "ep_adminpads2_pad-user-count": "Amarê karberanê pedi", + "ep_adminpads2_padname": "Padname", + "ep_adminpads2_search-box.placeholder": "termê cıgêrayış", + "ep_adminpads2_search-button.value": "Cı geyre", + "ep_adminpads2_search-done": "Cıgeyrayışi temam", + "ep_adminpads2_search-error-explanation": "Server cıgeyrayışê pedan de yew xetaya raşt ame", + "ep_adminpads2_search-error-title": "Lista pedi nêgêriye", + "ep_adminpads2_search-heading": "Pedan cıgeyrayış", + "ep_adminpads2_title": "İdarey pedi", + "ep_adminpads2_unknown-error": "Xetaya nêzanıtiye", + "ep_adminpads2_unknown-status": "Weziyeto nêzanaye" +} diff --git a/admin/public/ep_admin_pads/dsb.json b/admin/public/ep_admin_pads/dsb.json new file mode 100644 index 000000000..363732a20 --- /dev/null +++ b/admin/public/ep_admin_pads/dsb.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Michawiki" + ] + }, + "ep_adminpads2_action": "Akcija", + "ep_adminpads2_autoupdate-label": "Pśi změnach na zapisniku awtomatiski aktualizěrowaś", + "ep_adminpads2_autoupdate.title": "Zmóžnja abo znjemóžnja awtomatiske aktualizacije za aktualne wótpšašowanje.", + "ep_adminpads2_confirm": "Cośo napšawdu zapisnik {{padID}} lašowaś?", + "ep_adminpads2_delete.value": "Lašowaś", + "ep_adminpads2_last-edited": "Slědna změna", + "ep_adminpads2_loading": "Zacytujo se...", + "ep_adminpads2_manage-pads": "Zapisniki zastojaś", + "ep_adminpads2_no-results": "Žedne wuslědki", + "ep_adminpads2_pad-user-count": "Licba wužywarjow zapisnika", + "ep_adminpads2_padname": "Mě zapisnika", + "ep_adminpads2_search-box.placeholder": "Pytańske zapśimjeśe", + "ep_adminpads2_search-button.value": "Pytaś", + "ep_adminpads2_search-done": "Pytanje dokóńcone", + "ep_adminpads2_search-error-explanation": "Serwer jo starcył na zmólku, mjaztym až jo pytał za zapisnikami:", + "ep_adminpads2_search-error-title": "Lisćina zapisnikow njedajo se wobstaraś", + "ep_adminpads2_search-heading": "Za zapisnikami pytaś", + "ep_adminpads2_title": "Zapisnikowa administracija", + "ep_adminpads2_unknown-error": "Njeznata zmólka", + "ep_adminpads2_unknown-status": "Njeznaty status" +} diff --git a/admin/public/ep_admin_pads/el.json b/admin/public/ep_admin_pads/el.json new file mode 100644 index 000000000..77b6af3dd --- /dev/null +++ b/admin/public/ep_admin_pads/el.json @@ -0,0 +1,16 @@ +{ + "@metadata": { + "authors": [ + "Norhorn" + ] + }, + "ep_adminpads2_delete.value": "Διαγραφή", + "ep_adminpads2_last-edited": "Τελευταία απεξεργασία", + "ep_adminpads2_loading": "Φόρτωση…", + "ep_adminpads2_no-results": "Κανένα αποτέλεσμα", + "ep_adminpads2_search-box.placeholder": "Αναζήτηση όρων", + "ep_adminpads2_search-button.value": "Αναζήτηση", + "ep_adminpads2_search-done": "Ολοκλήρωση αναζήτησης", + "ep_adminpads2_unknown-error": "Άγνωστο σφάλμα", + "ep_adminpads2_unknown-status": "Άγνωστη κατάσταση" +} diff --git a/admin/public/ep_admin_pads/en.json b/admin/public/ep_admin_pads/en.json new file mode 100644 index 000000000..76354c640 --- /dev/null +++ b/admin/public/ep_admin_pads/en.json @@ -0,0 +1,23 @@ +{ + "ep_adminpads2_action": "Action", + "ep_adminpads2_autoupdate-label": "Auto-update on pad changes", + "ep_adminpads2_autoupdate.title": "Enables or disables automatic updates for the current query.", + "ep_adminpads2_confirm": "Do you really want to delete the pad {{padID}}?", + "ep_adminpads2_delete.value": "Delete", + "ep_adminpads2_cleanup": "Cleanup revisions", + "ep_adminpads2_last-edited": "Last edited", + "ep_adminpads2_loading": "Loading…", + "ep_adminpads2_manage-pads": "Manage pads", + "ep_adminpads2_no-results": "No results", + "ep_adminpads2_pad-user-count": "Pad user count", + "ep_adminpads2_padname": "Padname", + "ep_adminpads2_search-box.placeholder": "Search term", + "ep_adminpads2_search-button.value": "Search", + "ep_adminpads2_search-done": "Search complete", + "ep_adminpads2_search-error-explanation": "The server encountered an error while searching for pads:", + "ep_adminpads2_search-error-title": "Failed to get pad list", + "ep_adminpads2_search-heading": "Search for pads", + "ep_adminpads2_title": "Pad administration", + "ep_adminpads2_unknown-error": "Unknown error", + "ep_adminpads2_unknown-status": "Unknown status" +} diff --git a/admin/public/ep_admin_pads/eu.json b/admin/public/ep_admin_pads/eu.json new file mode 100644 index 000000000..71d9dfe79 --- /dev/null +++ b/admin/public/ep_admin_pads/eu.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Izendegi" + ] + }, + "ep_adminpads2_action": "Ekintza", + "ep_adminpads2_autoupdate-label": "Automatikoki eguneratu pad-aren aldaketak daudenean", + "ep_adminpads2_autoupdate.title": "Oraingo kontsultarako eguneratze automatikoak gaitu edo desgaitzen du.", + "ep_adminpads2_confirm": "Ziur zaude {{padID}} pad-a ezabatu nahi duzula?", + "ep_adminpads2_delete.value": "Ezabatu", + "ep_adminpads2_last-edited": "Azkenengoz editatua", + "ep_adminpads2_loading": "Kargatzen...", + "ep_adminpads2_manage-pads": "Kudeatu pad-ak", + "ep_adminpads2_no-results": "Emaitzarik ez", + "ep_adminpads2_pad-user-count": "Pad-erabiltzaile kopurua", + "ep_adminpads2_padname": "Pad-izena", + "ep_adminpads2_search-box.placeholder": "Bilaketa testua", + "ep_adminpads2_search-button.value": "Bilatu", + "ep_adminpads2_search-done": "Bilaketa osatu da", + "ep_adminpads2_search-error-explanation": "Zerbitzariak errore bat izan du pad-ak bilatzean:", + "ep_adminpads2_search-error-title": "Pad-zerrenda eskuratzeak huts egin du", + "ep_adminpads2_search-heading": "Bilatu pad-ak", + "ep_adminpads2_title": "Pad-en kudeaketa", + "ep_adminpads2_unknown-error": "Errore ezezaguna", + "ep_adminpads2_unknown-status": "Egoera ezezaguna" +} diff --git a/admin/public/ep_admin_pads/ff.json b/admin/public/ep_admin_pads/ff.json new file mode 100644 index 000000000..8cb5aea99 --- /dev/null +++ b/admin/public/ep_admin_pads/ff.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Ibrahima Malal Sarr" + ] + }, + "ep_adminpads2_action": "Baɗal", + "ep_adminpads2_autoupdate-label": "Hesɗitin e jaajol tuma baylagol faɗo", + "ep_adminpads2_autoupdate.title": "Hurminat walla daaƴa kesɗitine jaaje wonannde ɗaɓɓitannde wonaande.", + "ep_adminpads2_confirm": "Aɗa yiɗi e jaati momtude faɗo {{padID}}?", + "ep_adminpads2_delete.value": "Momtu", + "ep_adminpads2_last-edited": "Taƴtaa sakket", + "ep_adminpads2_loading": "Nana loowa…", + "ep_adminpads2_manage-pads": "Toppito paɗe", + "ep_adminpads2_no-results": "Alaa njaltudi", + "ep_adminpads2_pad-user-count": "Limoore huutorɓe faɗo", + "ep_adminpads2_padname": "Innde faɗo", + "ep_adminpads2_search-box.placeholder": "Helmere njiilaw", + "ep_adminpads2_search-button.value": "Yiylo", + "ep_adminpads2_search-done": "Njiylaw timmii", + "ep_adminpads2_search-error-explanation": "Sarworde ndee hawrii e juumre tuma nde yiylotoo faɗo:", + "ep_adminpads2_search-error-title": "Horiima heɓde doggol paɗe", + "ep_adminpads2_search-heading": "Yiylo paɗe", + "ep_adminpads2_title": "Yiylorde paɗe", + "ep_adminpads2_unknown-error": "Juumre nde anndaaka", + "ep_adminpads2_unknown-status": "Ngonka ka anndaaka" +} diff --git a/admin/public/ep_admin_pads/fi.json b/admin/public/ep_admin_pads/fi.json new file mode 100644 index 000000000..708b2bef8 --- /dev/null +++ b/admin/public/ep_admin_pads/fi.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Artnay", + "Kyykaarme", + "MITO", + "Maantietäjä", + "Yupik" + ] + }, + "ep_adminpads2_action": "Toiminto", + "ep_adminpads2_delete.value": "Poista", + "ep_adminpads2_last-edited": "Viimeksi muokattu", + "ep_adminpads2_loading": "Ladataan...", + "ep_adminpads2_manage-pads": "Hallitse muistioita", + "ep_adminpads2_no-results": "Ei tuloksia", + "ep_adminpads2_pad-user-count": "Pad-käyttäjien määrä", + "ep_adminpads2_padname": "Muistion nimi", + "ep_adminpads2_search-box.placeholder": "Haettava teksti", + "ep_adminpads2_search-button.value": "Etsi", + "ep_adminpads2_search-done": "Haku valmis", + "ep_adminpads2_search-error-explanation": "Palvelimessa tapahtui virhe etsiessään muistioita:", + "ep_adminpads2_search-error-title": "Pad-luettelon hakeminen epäonnistui", + "ep_adminpads2_search-heading": "Etsi sisältöä", + "ep_adminpads2_unknown-error": "Tuntematon virhe", + "ep_adminpads2_unknown-status": "Tuntematon tila" +} diff --git a/admin/public/ep_admin_pads/fr.json b/admin/public/ep_admin_pads/fr.json new file mode 100644 index 000000000..e6c8a8703 --- /dev/null +++ b/admin/public/ep_admin_pads/fr.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Verdy p" + ] + }, + "ep_adminpads2_action": "Action", + "ep_adminpads2_autoupdate-label": "Mise à jour automatique en cas de changements du bloc-notes", + "ep_adminpads2_autoupdate.title": "Active ou désactive les mises à jour automatiques pour la requête actuelle.", + "ep_adminpads2_confirm": "Voulez-vous vraiment supprimer le bloc-notes {{padID}} ?", + "ep_adminpads2_delete.value": "Supprimer", + "ep_adminpads2_last-edited": "Dernière modification", + "ep_adminpads2_loading": "Chargement en cours...", + "ep_adminpads2_manage-pads": "Gérer les bloc-notes", + "ep_adminpads2_no-results": "Aucun résultat", + "ep_adminpads2_pad-user-count": "Nombre d’utilisateurs du bloc-notes", + "ep_adminpads2_padname": "Nom du bloc-notes", + "ep_adminpads2_search-box.placeholder": "Terme de recherche", + "ep_adminpads2_search-button.value": "Rechercher", + "ep_adminpads2_search-done": "Recherche terminée", + "ep_adminpads2_search-error-explanation": "Le serveur a rencontré une erreur en cherchant des blocs-notes :", + "ep_adminpads2_search-error-title": "Échec d’obtention de la liste de blocs-notes", + "ep_adminpads2_search-heading": "Rechercher des blocs-notes", + "ep_adminpads2_title": "Administration du bloc-notes", + "ep_adminpads2_unknown-error": "Erreur inconnue", + "ep_adminpads2_unknown-status": "État inconnu" +} diff --git a/admin/public/ep_admin_pads/gl.json b/admin/public/ep_admin_pads/gl.json new file mode 100644 index 000000000..5e6b66549 --- /dev/null +++ b/admin/public/ep_admin_pads/gl.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Ghose" + ] + }, + "ep_adminpads2_action": "Accións", + "ep_adminpads2_autoupdate-label": "Actualización automática dos cambios", + "ep_adminpads2_autoupdate.title": "Activa ou desactiva as actualizacións automáticas para a consulta actual.", + "ep_adminpads2_confirm": "Tes a certeza de querer eliminar o pad {{padID}}?", + "ep_adminpads2_delete.value": "Eliminar", + "ep_adminpads2_last-edited": "Última edición", + "ep_adminpads2_loading": "Cargando…", + "ep_adminpads2_manage-pads": "Xestionar pads", + "ep_adminpads2_no-results": "Sen resultados", + "ep_adminpads2_pad-user-count": "Usuarias neste pad", + "ep_adminpads2_padname": "Nome do pad", + "ep_adminpads2_search-box.placeholder": "Buscar termo", + "ep_adminpads2_search-button.value": "Buscar", + "ep_adminpads2_search-done": "Busca completa", + "ep_adminpads2_search-error-explanation": "O servidor atopou un fallo cando buscaba pads:", + "ep_adminpads2_search-error-title": "Non se obtivo a lista de pads", + "ep_adminpads2_search-heading": "Buscar pads", + "ep_adminpads2_title": "Administración do pad", + "ep_adminpads2_unknown-error": "Erro descoñecido", + "ep_adminpads2_unknown-status": "Estado descoñecido" +} diff --git a/admin/public/ep_admin_pads/he.json b/admin/public/ep_admin_pads/he.json new file mode 100644 index 000000000..8b506946b --- /dev/null +++ b/admin/public/ep_admin_pads/he.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "YaronSh" + ] + }, + "ep_adminpads2_action": "פעולה", + "ep_adminpads2_autoupdate-label": "לעדכן אוטומטית כשהמחברת נערכת", + "ep_adminpads2_autoupdate.title": "הפעלה או השבתה של עדכונים אוטומטיים לשאילתה הנוכחית.", + "ep_adminpads2_confirm": "למחוק את המחברת {{padID}}?", + "ep_adminpads2_delete.value": "מחיקה", + "ep_adminpads2_last-edited": "עריכה אחרונה", + "ep_adminpads2_loading": "בטעינה…", + "ep_adminpads2_manage-pads": "ניהול מחברות", + "ep_adminpads2_no-results": "אין תוצאות", + "ep_adminpads2_pad-user-count": "ספירת משתמשים במחברת", + "ep_adminpads2_padname": "שם המחברת", + "ep_adminpads2_search-box.placeholder": "הביטוי לחיפוש", + "ep_adminpads2_search-button.value": "חיפוש", + "ep_adminpads2_search-done": "החיפוש הושלם", + "ep_adminpads2_search-error-explanation": "השרת נתקל בשגיאה בעת חיפוש מחברות:", + "ep_adminpads2_search-error-title": "קבלת רשימת המחברות נכשלה", + "ep_adminpads2_search-heading": "חיפוש אחר מחברות", + "ep_adminpads2_title": "ניהול מחברות", + "ep_adminpads2_unknown-error": "שגיאה בלתי־ידועה", + "ep_adminpads2_unknown-status": "מצב לא ידוע" +} diff --git a/admin/public/ep_admin_pads/hsb.json b/admin/public/ep_admin_pads/hsb.json new file mode 100644 index 000000000..a6c29611f --- /dev/null +++ b/admin/public/ep_admin_pads/hsb.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Michawiki" + ] + }, + "ep_adminpads2_action": "Akcija", + "ep_adminpads2_autoupdate-label": "Při změnach na zapisniku awtomatisce aktualizować", + "ep_adminpads2_autoupdate.title": "Zmóžnja abo znjemóžnja awtomatiske aktualizacije za aktualne wotprašowanje.", + "ep_adminpads2_confirm": "Chceće woprawdźe zapisnik {{padID}} zhašeć?", + "ep_adminpads2_delete.value": "Zhašeć", + "ep_adminpads2_last-edited": "Poslednja změna", + "ep_adminpads2_loading": "Začituje so...", + "ep_adminpads2_manage-pads": "Zapisniki rjadować", + "ep_adminpads2_no-results": "Žane wuslědki.", + "ep_adminpads2_pad-user-count": "Ličba wužiwarjow zapisnika", + "ep_adminpads2_padname": "Mjeno zapisnika", + "ep_adminpads2_search-box.placeholder": "Pytanske zapřijeće", + "ep_adminpads2_search-button.value": "Pytać", + "ep_adminpads2_search-done": "Pytanje dokónčene", + "ep_adminpads2_search-error-explanation": "Serwer je na zmylk storčił, mjeztym zo je za zapisnikami pytał:", + "ep_adminpads2_search-error-title": "Lisćina zapisnikow njeda so wobstarać", + "ep_adminpads2_search-heading": "Za zapisnikami pytać", + "ep_adminpads2_title": "Zapisnikowa administracija", + "ep_adminpads2_unknown-error": "Njeznaty zmylk", + "ep_adminpads2_unknown-status": "Njeznaty status" +} diff --git a/admin/public/ep_admin_pads/hu.json b/admin/public/ep_admin_pads/hu.json new file mode 100644 index 000000000..9210761bc --- /dev/null +++ b/admin/public/ep_admin_pads/hu.json @@ -0,0 +1,25 @@ +{ + "@metadata": { + "authors": [] + }, + "ep_adminpads2_action": "Művelet", + "ep_adminpads2_autoupdate-label": "Változáskor jegyzetfüzet önműködő frissítése", + "ep_adminpads2_autoupdate.title": "Önműködő frissítése az jelenlegi lekérdezéshez be- vagy kikapcsolása.", + "ep_adminpads2_confirm": "Biztosan törölni szeretné a(z) {{padID}} jegyzetfüzetet?", + "ep_adminpads2_delete.value": "Törlés", + "ep_adminpads2_last-edited": "Utoljára szerkesztve", + "ep_adminpads2_loading": "Betöltés folyamatban…", + "ep_adminpads2_manage-pads": "Jegyzetfüzetek kezelése", + "ep_adminpads2_no-results": "Nincs találat", + "ep_adminpads2_pad-user-count": "Jegyzetfüzet felhasználók száma", + "ep_adminpads2_padname": "Jegyzetfüzet név", + "ep_adminpads2_search-box.placeholder": "Keresési kifejezés", + "ep_adminpads2_search-button.value": "Keresés", + "ep_adminpads2_search-done": "Keresés befejezve", + "ep_adminpads2_search-error-explanation": "A kiszolgáló hibát észlelt a jegyzetfüzetek keresésekor:", + "ep_adminpads2_search-error-title": "Nem sikerült lekérni a jegyzetfüzet listát", + "ep_adminpads2_search-heading": "Jegyzetfüzetek keresése", + "ep_adminpads2_title": "Jegyzetfüzet felügyelete", + "ep_adminpads2_unknown-error": "Ismeretlen hiba", + "ep_adminpads2_unknown-status": "Ismeretlen állapot" +} diff --git a/admin/public/ep_admin_pads/ia.json b/admin/public/ep_admin_pads/ia.json new file mode 100644 index 000000000..f0e00e5ca --- /dev/null +++ b/admin/public/ep_admin_pads/ia.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "McDutchie" + ] + }, + "ep_adminpads2_action": "Action", + "ep_adminpads2_autoupdate-label": "Actualisar automaticamente le pad in caso de cambiamentos", + "ep_adminpads2_autoupdate.title": "Activa o disactiva le actualisationes automatic pro le consulta actual.", + "ep_adminpads2_confirm": "Es tu secur de voler deler le pad {{padID}}?", + "ep_adminpads2_delete.value": "Deler", + "ep_adminpads2_last-edited": "Ultime modification", + "ep_adminpads2_loading": "Cargamento in curso…", + "ep_adminpads2_manage-pads": "Gerer pads", + "ep_adminpads2_no-results": "Nulle resultato", + "ep_adminpads2_pad-user-count": "Numero de usatores del pad", + "ep_adminpads2_padname": "Nomine del pad", + "ep_adminpads2_search-box.placeholder": "Termino de recerca", + "ep_adminpads2_search-button.value": "Cercar", + "ep_adminpads2_search-done": "Recerca terminate", + "ep_adminpads2_search-error-explanation": "Le servitor ha incontrate un error durante le recerca de pads:", + "ep_adminpads2_search-error-title": "Non poteva obtener le lista de pads", + "ep_adminpads2_search-heading": "Cercar pads", + "ep_adminpads2_title": "Administration de pads", + "ep_adminpads2_unknown-error": "Error incognite", + "ep_adminpads2_unknown-status": "Stato incognite" +} diff --git a/admin/public/ep_admin_pads/it.json b/admin/public/ep_admin_pads/it.json new file mode 100644 index 000000000..493cbb4d5 --- /dev/null +++ b/admin/public/ep_admin_pads/it.json @@ -0,0 +1,16 @@ +{ + "@metadata": { + "authors": [ + "Beta16", + "Luca.favorido" + ] + }, + "ep_adminpads2_action": "Azione", + "ep_adminpads2_delete.value": "Cancella", + "ep_adminpads2_last-edited": "Ultima modifica", + "ep_adminpads2_loading": "Caricamento…", + "ep_adminpads2_no-results": "Nessun risultato", + "ep_adminpads2_search-button.value": "Cerca", + "ep_adminpads2_unknown-error": "Errore sconosciuto", + "ep_adminpads2_unknown-status": "Stato sconosciuto" +} diff --git a/admin/public/ep_admin_pads/kn.json b/admin/public/ep_admin_pads/kn.json new file mode 100644 index 000000000..1e9019611 --- /dev/null +++ b/admin/public/ep_admin_pads/kn.json @@ -0,0 +1,13 @@ +{ + "@metadata": { + "authors": [ + "ಮಲ್ನಾಡಾಚ್ ಕೊಂಕ್ಣೊ" + ] + }, + "ep_adminpads2_action": "ಕ್ರಿಯೆ", + "ep_adminpads2_delete.value": "ಅಳಿಸು", + "ep_adminpads2_loading": "ತುಂಬಿಸಲಾಗುತ್ತಿದೆ…", + "ep_adminpads2_no-results": "ಯಾವ ಫಲಿತಾಂಶಗಳೂ ಇಲ್ಲ", + "ep_adminpads2_search-button.value": "ಹುಡುಕು", + "ep_adminpads2_unknown-error": "ಅಪರಿಚಿತ ದೋಷ" +} diff --git a/admin/public/ep_admin_pads/ko.json b/admin/public/ep_admin_pads/ko.json new file mode 100644 index 000000000..9ab8feed3 --- /dev/null +++ b/admin/public/ep_admin_pads/ko.json @@ -0,0 +1,28 @@ +{ + "@metadata": { + "authors": [ + "Ykhwong", + "그냥기여자" + ] + }, + "ep_adminpads2_action": "동작", + "ep_adminpads2_autoupdate-label": "패드 변경 시 자동 업데이트", + "ep_adminpads2_autoupdate.title": "현재 쿼리의 자동 업데이트를 활성화하거나 비활성화합니다.", + "ep_adminpads2_confirm": "{{padID}} 패드를 삭제하시겠습니까?", + "ep_adminpads2_delete.value": "삭제", + "ep_adminpads2_last-edited": "최근 편집", + "ep_adminpads2_loading": "불러오는 중...", + "ep_adminpads2_manage-pads": "패드 관리", + "ep_adminpads2_no-results": "결과 없음", + "ep_adminpads2_pad-user-count": "패드 사용자 수", + "ep_adminpads2_padname": "패드 이름", + "ep_adminpads2_search-box.placeholder": "검색어", + "ep_adminpads2_search-button.value": "검색", + "ep_adminpads2_search-done": "검색 완료", + "ep_adminpads2_search-error-explanation": "패드 검색 중 서버에 오류가 발생했습니다:", + "ep_adminpads2_search-error-title": "패드 목록 가져오기 실패", + "ep_adminpads2_search-heading": "패드 검색", + "ep_adminpads2_title": "패드 관리", + "ep_adminpads2_unknown-error": "알 수 없는 오류", + "ep_adminpads2_unknown-status": "알 수 없는 상태" +} diff --git a/admin/public/ep_admin_pads/krc.json b/admin/public/ep_admin_pads/krc.json new file mode 100644 index 000000000..2caf4f099 --- /dev/null +++ b/admin/public/ep_admin_pads/krc.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Къарачайлы" + ] + }, + "ep_adminpads2_action": "Этиу", + "ep_adminpads2_autoupdate-label": "Блокнот тюрлендириулеринде автомат халда джангыртыу", + "ep_adminpads2_autoupdate.title": "Баргъан излем ючюн автомат халда джангыртыуланы джандын неда джукълат.", + "ep_adminpads2_confirm": "{{padID}} блокнотну керти да кетерирге излеймисиз?", + "ep_adminpads2_delete.value": "Кетер", + "ep_adminpads2_last-edited": "Ахыр тюзетиу", + "ep_adminpads2_loading": "Джюклениу…", + "ep_adminpads2_manage-pads": "Блокнотланы оноуун эт", + "ep_adminpads2_no-results": "Эсебле джокъдула", + "ep_adminpads2_pad-user-count": "Блокнот хайырланыучуланы саны", + "ep_adminpads2_padname": "Блокнот ат", + "ep_adminpads2_search-box.placeholder": "Терминни изле", + "ep_adminpads2_search-button.value": "Изле", + "ep_adminpads2_search-done": "Излеу тамамланды", + "ep_adminpads2_search-error-explanation": "Сервер, блокнотланы излеген заманда халат табды:", + "ep_adminpads2_search-error-title": "Блокнот тизмеси алынамады", + "ep_adminpads2_search-heading": "Блокнотла ючюн излеу", + "ep_adminpads2_title": "Блокнот башчылыкъ", + "ep_adminpads2_unknown-error": "Билинмеген халат", + "ep_adminpads2_unknown-status": "Билинмеген турум" +} diff --git a/admin/public/ep_admin_pads/lb.json b/admin/public/ep_admin_pads/lb.json new file mode 100644 index 000000000..61aa2588d --- /dev/null +++ b/admin/public/ep_admin_pads/lb.json @@ -0,0 +1,16 @@ +{ + "@metadata": { + "authors": [ + "Robby", + "Volvox" + ] + }, + "ep_adminpads2_confirm": "Wëllt Dir de Pad {{padID}} wierklech läschen?", + "ep_adminpads2_delete.value": "Läschen", + "ep_adminpads2_loading": "Lueden...", + "ep_adminpads2_no-results": "Keng Resultater", + "ep_adminpads2_padname": "Padnumm", + "ep_adminpads2_search-box.placeholder": "Sichbegrëff", + "ep_adminpads2_search-button.value": "Sichen", + "ep_adminpads2_unknown-error": "Onbekannte Feeler" +} diff --git a/admin/public/ep_admin_pads/lt.json b/admin/public/ep_admin_pads/lt.json new file mode 100644 index 000000000..59b2a13b3 --- /dev/null +++ b/admin/public/ep_admin_pads/lt.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Nokeoo" + ] + }, + "ep_adminpads2_action": "Veiksmas", + "ep_adminpads2_autoupdate-label": "Automatinis bloknoto keitimų naujinimas", + "ep_adminpads2_autoupdate.title": "Įjungia arba išjungia automatinius dabartinės užklausos atnaujinimus.", + "ep_adminpads2_confirm": "Ar tikrai norite ištrinti bloknotą {{padID}}?", + "ep_adminpads2_delete.value": "Ištrinti", + "ep_adminpads2_last-edited": "Paskutinis pakeitimas", + "ep_adminpads2_loading": "Įkeliama…", + "ep_adminpads2_manage-pads": "Tvarkyti bloknotą", + "ep_adminpads2_no-results": "Nėra rezultatų", + "ep_adminpads2_pad-user-count": "Bloknoto naudotojų skaičius", + "ep_adminpads2_padname": "Bloknoto pavadinimas", + "ep_adminpads2_search-box.placeholder": "Paieškos terminas", + "ep_adminpads2_search-button.value": "Paieška", + "ep_adminpads2_search-done": "Paieška baigta", + "ep_adminpads2_search-error-explanation": "Serveris susidūrė su klaida ieškant bloknotų:", + "ep_adminpads2_search-error-title": "Nepavyko gauti bloknotų sąrašo", + "ep_adminpads2_search-heading": "Ieškokite bloknotų", + "ep_adminpads2_title": "Bloknotų administravimas", + "ep_adminpads2_unknown-error": "Nežinoma klaida", + "ep_adminpads2_unknown-status": "Nežinoma būsena" +} diff --git a/admin/public/ep_admin_pads/mk.json b/admin/public/ep_admin_pads/mk.json new file mode 100644 index 000000000..72affd86c --- /dev/null +++ b/admin/public/ep_admin_pads/mk.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Bjankuloski06" + ] + }, + "ep_adminpads2_action": "Дејство", + "ep_adminpads2_autoupdate-label": "Самоподнова при измени во тетратката", + "ep_adminpads2_autoupdate.title": "Овозможува или оневозможува самоподнова на тековното барање.", + "ep_adminpads2_confirm": "Дали навистина сакате да ја избришете тетратката {{padID}}?", + "ep_adminpads2_delete.value": "Избриши", + "ep_adminpads2_last-edited": "Последно уредување", + "ep_adminpads2_loading": "Вчитувам…", + "ep_adminpads2_manage-pads": "Раководење со тетратки", + "ep_adminpads2_no-results": "Нема исход", + "ep_adminpads2_pad-user-count": "Корисници на тетратката", + "ep_adminpads2_padname": "Назив на тетратката", + "ep_adminpads2_search-box.placeholder": "Пребаран поим", + "ep_adminpads2_search-button.value": "Пребарај", + "ep_adminpads2_search-done": "Пребарувањето заврши", + "ep_adminpads2_search-error-explanation": "Опслужувачот наиде на грешка при пребарувањето на тетратки:", + "ep_adminpads2_search-error-title": "Не можев да го добијам списокот на тетратки", + "ep_adminpads2_search-heading": "Пребарај по тетратките", + "ep_adminpads2_title": "Администрација на тетратки", + "ep_adminpads2_unknown-error": "Непозната грешка", + "ep_adminpads2_unknown-status": "Непозната состојба" +} diff --git a/admin/public/ep_admin_pads/my.json b/admin/public/ep_admin_pads/my.json new file mode 100644 index 000000000..6b94ba702 --- /dev/null +++ b/admin/public/ep_admin_pads/my.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Andibecker" + ] + }, + "ep_adminpads2_action": "လုပ်ဆောင်ချက်", + "ep_adminpads2_autoupdate-label": "pad အပြောင်းအလဲများတွင်အလိုအလျောက်အပ်ဒိတ်လုပ်ပါ", + "ep_adminpads2_autoupdate.title": "လက်ရှိမေးမြန်းမှုအတွက်အလိုအလျောက်အပ်ဒိတ်များကိုဖွင့်ပါသို့မဟုတ်ပိတ်ပါ။", + "ep_adminpads2_confirm": "pad {{padID}} ကိုသင်တကယ်ဖျက်ချင်လား။", + "ep_adminpads2_delete.value": "ဖျက်ပါ", + "ep_adminpads2_last-edited": "နောက်ဆုံးတည်းဖြတ်သည်", + "ep_adminpads2_loading": "ဖွင့်နေသည်…", + "ep_adminpads2_manage-pads": "pads များကိုစီမံပါ", + "ep_adminpads2_no-results": "ရလဒ်မရှိပါ", + "ep_adminpads2_pad-user-count": "Pad အသုံးပြုသူအရေအတွက်", + "ep_adminpads2_padname": "Padname", + "ep_adminpads2_search-box.placeholder": "ဝေါဟာရရှာဖွေပါ", + "ep_adminpads2_search-button.value": "ရှာဖွေပါ", + "ep_adminpads2_search-done": "ရှာဖွေမှုပြီးပါပြီ", + "ep_adminpads2_search-error-explanation": "pads များကိုရှာဖွေစဉ်ဆာဗာသည်အမှားတစ်ခုကြုံခဲ့သည်။", + "ep_adminpads2_search-error-title": "pad စာရင်းရယူရန်မအောင်မြင်ပါ", + "ep_adminpads2_search-heading": "pads များကိုရှာဖွေပါ", + "ep_adminpads2_title": "Pad စီမံခန့်ခွဲမှု", + "ep_adminpads2_unknown-error": "အမည်မသိအမှား", + "ep_adminpads2_unknown-status": "အခြေအနေမသိ" +} diff --git a/admin/public/ep_admin_pads/nb.json b/admin/public/ep_admin_pads/nb.json new file mode 100644 index 000000000..acd194397 --- /dev/null +++ b/admin/public/ep_admin_pads/nb.json @@ -0,0 +1,13 @@ +{ + "@metadata": { + "authors": [ + "EdoAug" + ] + }, + "ep_adminpads2_action": "Handling", + "ep_adminpads2_last-edited": "Sist redigert", + "ep_adminpads2_loading": "Laster …", + "ep_adminpads2_no-results": "Ingen resultater", + "ep_adminpads2_search-button.value": "Søk", + "ep_adminpads2_search-done": "Søk fullført" +} diff --git a/admin/public/ep_admin_pads/nl.json b/admin/public/ep_admin_pads/nl.json new file mode 100644 index 000000000..f4d97b351 --- /dev/null +++ b/admin/public/ep_admin_pads/nl.json @@ -0,0 +1,29 @@ +{ + "@metadata": { + "authors": [ + "Aranka", + "McDutchie", + "Spinster" + ] + }, + "ep_adminpads2_action": "Handeling", + "ep_adminpads2_autoupdate-label": "Automatisch bijwerken bij aanpassingen aan de pad", + "ep_adminpads2_autoupdate.title": "Schakelt automatische updates voor de huidige query in of uit.", + "ep_adminpads2_confirm": "Wil je de pad {{padID}} echt verwijderen?", + "ep_adminpads2_delete.value": "Verwijderen", + "ep_adminpads2_last-edited": "Laatst bewerkt", + "ep_adminpads2_loading": "Bezig met laden...", + "ep_adminpads2_manage-pads": "Pads beheren", + "ep_adminpads2_no-results": "Geen resultaten", + "ep_adminpads2_pad-user-count": "Aantal gebruikers van de pad", + "ep_adminpads2_padname": "Naam van de pad", + "ep_adminpads2_search-box.placeholder": "Zoekterm", + "ep_adminpads2_search-button.value": "Zoeken", + "ep_adminpads2_search-done": "Zoekopdracht voltooid", + "ep_adminpads2_search-error-explanation": "De server heeft een fout aangetroffen tijdens het zoeken naar pads:", + "ep_adminpads2_search-error-title": "Kan lijst met pads niet ophalen", + "ep_adminpads2_search-heading": "Pads zoeken", + "ep_adminpads2_title": "Administratie van pad", + "ep_adminpads2_unknown-error": "Onbekende fout", + "ep_adminpads2_unknown-status": "Onbekende status" +} diff --git a/admin/public/ep_admin_pads/oc.json b/admin/public/ep_admin_pads/oc.json new file mode 100644 index 000000000..ae0169faf --- /dev/null +++ b/admin/public/ep_admin_pads/oc.json @@ -0,0 +1,21 @@ +{ + "@metadata": { + "authors": [ + "Quentí" + ] + }, + "ep_adminpads2_action": "Accion", + "ep_adminpads2_delete.value": "Suprimir", + "ep_adminpads2_last-edited": "Darrièra edicion", + "ep_adminpads2_loading": "Cargament…", + "ep_adminpads2_manage-pads": "Gerir los pads", + "ep_adminpads2_no-results": "Pas cap de resultat", + "ep_adminpads2_padname": "Nom del pad", + "ep_adminpads2_search-box.placeholder": "Tèrme de recèrca", + "ep_adminpads2_search-button.value": "Recercar", + "ep_adminpads2_search-done": "Recèrca acabada", + "ep_adminpads2_search-heading": "Cercar de pads", + "ep_adminpads2_title": "Administracion de pad", + "ep_adminpads2_unknown-error": "Error desconeguda", + "ep_adminpads2_unknown-status": "Estat desconegut" +} diff --git a/admin/public/ep_admin_pads/pms.json b/admin/public/ep_admin_pads/pms.json new file mode 100644 index 000000000..ac0542b85 --- /dev/null +++ b/admin/public/ep_admin_pads/pms.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Borichèt" + ] + }, + "ep_adminpads2_action": "Assion", + "ep_adminpads2_autoupdate-label": "Agiornament automàtich an sle modìfiche ëd plancia", + "ep_adminpads2_autoupdate.title": "Abilité o disabilité j'agiornament automàtich për l'arcesta atual.", + "ep_adminpads2_confirm": "Veul-lo për da bon dëscancelé la plancia {{padID}}?", + "ep_adminpads2_delete.value": "Dëscancelé", + "ep_adminpads2_last-edited": "Modificà l'ùltima vira", + "ep_adminpads2_loading": "Cariament…", + "ep_adminpads2_manage-pads": "Gestì le plance", + "ep_adminpads2_no-results": "Gnun arzultà", + "ep_adminpads2_pad-user-count": "Conteur ëd plancia dl'utent", + "ep_adminpads2_padname": "Nòm ëd plancia", + "ep_adminpads2_search-box.placeholder": "Tèrmin d'arserca", + "ep_adminpads2_search-button.value": "Arserca", + "ep_adminpads2_search-done": "Arserca completà", + "ep_adminpads2_search-error-explanation": "Ël servent a l'ha rancontrà n'eror an sërcand dle plance:", + "ep_adminpads2_search-error-title": "Falì a oten-e la lista ëd plance", + "ep_adminpads2_search-heading": "Arserca ëd plance", + "ep_adminpads2_title": "Aministrassion ëd plance", + "ep_adminpads2_unknown-error": "Eror nen conossù", + "ep_adminpads2_unknown-status": "Statù nen conossù" +} diff --git a/admin/public/ep_admin_pads/pt-br.json b/admin/public/ep_admin_pads/pt-br.json new file mode 100644 index 000000000..28a7874ee --- /dev/null +++ b/admin/public/ep_admin_pads/pt-br.json @@ -0,0 +1,30 @@ +{ + "@metadata": { + "authors": [ + "Duke of Wikipädia", + "Eduardo Addad de Oliveira", + "Eduardoaddad", + "YuriNikolai" + ] + }, + "ep_adminpads2_action": "Ação", + "ep_adminpads2_autoupdate-label": "Atualizar notas automaticamente", + "ep_adminpads2_autoupdate.title": "Habilita ou desabilita atualizações automáticas para a consulta atual.", + "ep_adminpads2_confirm": "Você realmente deseja excluir a nota {{padID}}?", + "ep_adminpads2_delete.value": "Excluir", + "ep_adminpads2_last-edited": "Última edição", + "ep_adminpads2_loading": "Carregando…", + "ep_adminpads2_manage-pads": "Gerenciar notas", + "ep_adminpads2_no-results": "Sem resultados", + "ep_adminpads2_pad-user-count": "Número de utilizadores na nota", + "ep_adminpads2_padname": "Nome da nota", + "ep_adminpads2_search-box.placeholder": "Termo de pesquisa", + "ep_adminpads2_search-button.value": "Pesquisar", + "ep_adminpads2_search-done": "Busca completa", + "ep_adminpads2_search-error-explanation": "O servidor encontrou um erro enquanto procurava por notas:", + "ep_adminpads2_search-error-title": "Falha ao buscar lista de notas", + "ep_adminpads2_search-heading": "Pesquisar por notas", + "ep_adminpads2_title": "Administração de notas", + "ep_adminpads2_unknown-error": "Erro desconhecido", + "ep_adminpads2_unknown-status": "Status desconhecido" +} diff --git a/admin/public/ep_admin_pads/pt.json b/admin/public/ep_admin_pads/pt.json new file mode 100644 index 000000000..b7abf2f3f --- /dev/null +++ b/admin/public/ep_admin_pads/pt.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Guilha" + ] + }, + "ep_adminpads2_action": "Ação", + "ep_adminpads2_autoupdate-label": "Atualizar automaticamente as notas", + "ep_adminpads2_autoupdate.title": "Ativa ou desativa atualizações automáticas na consulta atual.", + "ep_adminpads2_confirm": "Tencionas mesmo eliminar a nota {{padID}}?", + "ep_adminpads2_delete.value": "Eliminar", + "ep_adminpads2_last-edited": "Última edição", + "ep_adminpads2_loading": "A carregar...", + "ep_adminpads2_manage-pads": "Gerir notas", + "ep_adminpads2_no-results": "Sem resultados", + "ep_adminpads2_pad-user-count": "Número de utilizadores na nota", + "ep_adminpads2_padname": "Nome da nota", + "ep_adminpads2_search-box.placeholder": "Procurar termo", + "ep_adminpads2_search-button.value": "Procurar", + "ep_adminpads2_search-done": "Procura completa", + "ep_adminpads2_search-error-explanation": "O servidor encontrou um erro enquanto procurava por notas:", + "ep_adminpads2_search-error-title": "Falha ao obter lista de notas", + "ep_adminpads2_search-heading": "Procurar por notas", + "ep_adminpads2_title": "Administração da nota", + "ep_adminpads2_unknown-error": "Erro desconhecido", + "ep_adminpads2_unknown-status": "Estado desconhecido" +} diff --git a/admin/public/ep_admin_pads/qqq.json b/admin/public/ep_admin_pads/qqq.json new file mode 100644 index 000000000..de36e2ae6 --- /dev/null +++ b/admin/public/ep_admin_pads/qqq.json @@ -0,0 +1,10 @@ +{ + "@metadata": { + "authors": [ + "BryanDavis" + ] + }, + "ep_adminpads2_action": "{{Identical|Action}}", + "ep_adminpads2_delete.value": "{{Identical|Delete}}", + "ep_adminpads2_search-button.value": "{{Identical|Search}}" +} diff --git a/admin/public/ep_admin_pads/ru.json b/admin/public/ep_admin_pads/ru.json new file mode 100644 index 000000000..6d0d163d0 --- /dev/null +++ b/admin/public/ep_admin_pads/ru.json @@ -0,0 +1,31 @@ +{ + "@metadata": { + "authors": [ + "DDPAT", + "Ice bulldog", + "Megakott", + "Okras", + "Pacha Tchernof" + ] + }, + "ep_adminpads2_action": "Действие", + "ep_adminpads2_autoupdate-label": "Автообновление при изменении документа", + "ep_adminpads2_autoupdate.title": "Включает или отключает автоматические обновления для текущего запроса.", + "ep_adminpads2_confirm": "Вы действительно хотите удалить документ {{padID}}?", + "ep_adminpads2_delete.value": "Удалить", + "ep_adminpads2_last-edited": "Последнее изменение", + "ep_adminpads2_loading": "Загружается…", + "ep_adminpads2_manage-pads": "Управление документами", + "ep_adminpads2_no-results": "Нет результатов", + "ep_adminpads2_pad-user-count": "Количество пользователей документа", + "ep_adminpads2_padname": "Название документа", + "ep_adminpads2_search-box.placeholder": "Искать термин", + "ep_adminpads2_search-button.value": "Найти", + "ep_adminpads2_search-done": "Поиск завершён", + "ep_adminpads2_search-error-explanation": "Сервер обнаружил ошибку при поиске документов:", + "ep_adminpads2_search-error-title": "Не удалось получить список документов", + "ep_adminpads2_search-heading": "Поиск документов", + "ep_adminpads2_title": "Администрирование документов", + "ep_adminpads2_unknown-error": "Неизвестная ошибка", + "ep_adminpads2_unknown-status": "Неизвестный статус" +} diff --git a/admin/public/ep_admin_pads/sc.json b/admin/public/ep_admin_pads/sc.json new file mode 100644 index 000000000..a37bba5a2 --- /dev/null +++ b/admin/public/ep_admin_pads/sc.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Adr mm" + ] + }, + "ep_adminpads2_action": "Atzione", + "ep_adminpads2_autoupdate-label": "Atualizatzione automàtica de is modìficas de su pad", + "ep_adminpads2_autoupdate.title": "Ativat o disativat is atualizatziones automàticas pro sa chirca atuale.", + "ep_adminpads2_confirm": "Seguru chi boles cantzellare su pad {{padID}}?", + "ep_adminpads2_delete.value": "Cantzella", + "ep_adminpads2_last-edited": "Ùrtima modìfica", + "ep_adminpads2_loading": "Carrighende...", + "ep_adminpads2_manage-pads": "Gesti is pads", + "ep_adminpads2_no-results": "Nissunu resurtadu", + "ep_adminpads2_pad-user-count": "Nùmeru de utentes de pads", + "ep_adminpads2_padname": "Nòmine de su pad", + "ep_adminpads2_search-box.placeholder": "Tèrmine de chirca", + "ep_adminpads2_search-button.value": "Chirca", + "ep_adminpads2_search-done": "Chirca cumpleta", + "ep_adminpads2_search-error-explanation": "Su serbidore at agatadu un'errore chirchende pads:", + "ep_adminpads2_search-error-title": "Impossìbile otènnere sa lista de pads", + "ep_adminpads2_search-heading": "Chirca pads", + "ep_adminpads2_title": "Amministratzione de su pad", + "ep_adminpads2_unknown-error": "Errore disconnotu", + "ep_adminpads2_unknown-status": "Istadu disconnotu" +} diff --git a/admin/public/ep_admin_pads/sdc.json b/admin/public/ep_admin_pads/sdc.json new file mode 100644 index 000000000..c4672fd7f --- /dev/null +++ b/admin/public/ep_admin_pads/sdc.json @@ -0,0 +1,14 @@ +{ + "@metadata": { + "authors": [ + "F Samaritani" + ] + }, + "ep_adminpads2_action": "Azioni", + "ep_adminpads2_delete.value": "Canzella", + "ep_adminpads2_loading": "carrigghendi...", + "ep_adminpads2_no-results": "Nisciun risulthaddu", + "ep_adminpads2_search-button.value": "Zercha", + "ep_adminpads2_search-heading": "Zirchà dati", + "ep_adminpads2_unknown-error": "Errori ischunisciddu" +} diff --git a/admin/public/ep_admin_pads/sk.json b/admin/public/ep_admin_pads/sk.json new file mode 100644 index 000000000..ab0392d4e --- /dev/null +++ b/admin/public/ep_admin_pads/sk.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Yardom78" + ] + }, + "ep_adminpads2_action": "Akcia", + "ep_adminpads2_autoupdate-label": "Automatická aktualizácia zmien na poznámkovom bloku", + "ep_adminpads2_autoupdate.title": "Zapne alebo vypne automatickú aktualizáciu.", + "ep_adminpads2_confirm": "Skutočne chcete vymazať poznámkový blok {{padID}}?", + "ep_adminpads2_delete.value": "Vymazať", + "ep_adminpads2_last-edited": "Posledná úprava", + "ep_adminpads2_loading": "Načítavanie...", + "ep_adminpads2_manage-pads": "Spravovať poznámkové bloky", + "ep_adminpads2_no-results": "Žiadne výsledky", + "ep_adminpads2_pad-user-count": "Počet používateľov poznámkového bloku", + "ep_adminpads2_padname": "Názov poznámkového bloku", + "ep_adminpads2_search-box.placeholder": "Hľadať výraz", + "ep_adminpads2_search-button.value": "Hľadať", + "ep_adminpads2_search-done": "Hľadanie dokončené", + "ep_adminpads2_search-error-explanation": "Pri hľadaní poznámkového bloku došlo k chybe:", + "ep_adminpads2_search-error-title": "Nepodarilo sa získať zoznam poznámkových blokov", + "ep_adminpads2_search-heading": "Hľadať poznámkový blok", + "ep_adminpads2_title": "Správa poznámkového bloku", + "ep_adminpads2_unknown-error": "Neznáma chyba", + "ep_adminpads2_unknown-status": "Neznámy stav" +} diff --git a/admin/public/ep_admin_pads/skr-arab.json b/admin/public/ep_admin_pads/skr-arab.json new file mode 100644 index 000000000..08162f849 --- /dev/null +++ b/admin/public/ep_admin_pads/skr-arab.json @@ -0,0 +1,20 @@ +{ + "@metadata": { + "authors": [ + "Saraiki" + ] + }, + "ep_adminpads2_action": "عمل", + "ep_adminpads2_delete.value": "مٹاؤ", + "ep_adminpads2_last-edited": "چھیکڑی تبدیلی", + "ep_adminpads2_loading": "لوڈ تھین٘دا پئے۔۔۔", + "ep_adminpads2_manage-pads": "پیڈ منیج کرو", + "ep_adminpads2_no-results": "کوئی نتیجہ کائنی", + "ep_adminpads2_padname": "پیڈ ناں", + "ep_adminpads2_search-box.placeholder": "ٹرم ڳولو", + "ep_adminpads2_search-button.value": "ڳولو", + "ep_adminpads2_search-done": "ڳولݨ پورا تھیا", + "ep_adminpads2_search-heading": "پیڈاں دی ڳول", + "ep_adminpads2_unknown-error": "نامعلوم غلطی", + "ep_adminpads2_unknown-status": "نامعلوم حالت" +} diff --git a/admin/public/ep_admin_pads/sl.json b/admin/public/ep_admin_pads/sl.json new file mode 100644 index 000000000..3bebe1972 --- /dev/null +++ b/admin/public/ep_admin_pads/sl.json @@ -0,0 +1,28 @@ +{ + "@metadata": { + "authors": [ + "Eleassar", + "HairyFotr" + ] + }, + "ep_adminpads2_action": "Dejanje", + "ep_adminpads2_autoupdate-label": "Samodejno posodabljanje ob spremembah blokcev", + "ep_adminpads2_autoupdate.title": "Omogoči ali onemogoči samodejne posodobitve za trenutno poizvedbo.", + "ep_adminpads2_confirm": "Ali res želite izbrisati blokec {{padID}}?", + "ep_adminpads2_delete.value": "Izbriši", + "ep_adminpads2_last-edited": "Zadnje urejanje", + "ep_adminpads2_loading": "Nalaganje ...", + "ep_adminpads2_manage-pads": "Upravljanje blokcev", + "ep_adminpads2_no-results": "Ni zadetkov", + "ep_adminpads2_pad-user-count": "Število urejevalcev blokca", + "ep_adminpads2_padname": "Ime blokca", + "ep_adminpads2_search-box.placeholder": "Iskalni izraz", + "ep_adminpads2_search-button.value": "Išči", + "ep_adminpads2_search-done": "Iskanje končano", + "ep_adminpads2_search-error-explanation": "Strežnik je med iskanjem blokcev naletel na napako:", + "ep_adminpads2_search-error-title": "Ni bilo mogoče pridobiti seznama blokcev", + "ep_adminpads2_search-heading": "Iskanje blokcev", + "ep_adminpads2_title": "Upravljanje blokcev", + "ep_adminpads2_unknown-error": "Neznana napaka", + "ep_adminpads2_unknown-status": "Neznano stanje" +} diff --git a/admin/public/ep_admin_pads/smn.json b/admin/public/ep_admin_pads/smn.json new file mode 100644 index 000000000..9d57cc73c --- /dev/null +++ b/admin/public/ep_admin_pads/smn.json @@ -0,0 +1,13 @@ +{ + "@metadata": { + "authors": [ + "Yupik" + ] + }, + "ep_adminpads2_delete.value": "Siho", + "ep_adminpads2_last-edited": "Majemustáá nubástittum", + "ep_adminpads2_search-box.placeholder": "Uuccâmsääni", + "ep_adminpads2_search-button.value": "Uusâ", + "ep_adminpads2_unknown-error": "Tubdâmettum feilâ", + "ep_adminpads2_unknown-status": "Tubdâmettum tile" +} diff --git a/admin/public/ep_admin_pads/sms.json b/admin/public/ep_admin_pads/sms.json new file mode 100644 index 000000000..8d3cf5797 --- /dev/null +++ b/admin/public/ep_admin_pads/sms.json @@ -0,0 +1,16 @@ +{ + "@metadata": { + "authors": [ + "Yupik" + ] + }, + "ep_adminpads2_delete.value": "Jaukkâd", + "ep_adminpads2_last-edited": "Mââimõssân muttum", + "ep_adminpads2_no-results": "Ij käunnʼjam ni mii", + "ep_adminpads2_padname": "Mošttʼtõspõʹmmai nõmm", + "ep_adminpads2_search-box.placeholder": "Ooccâmsääʹnn", + "ep_adminpads2_search-button.value": "Ooʒʒ", + "ep_adminpads2_search-heading": "Ooʒʒ mošttʼtõspõʹmmjid", + "ep_adminpads2_unknown-error": "Toobdteʹmes vââʹǩǩ", + "ep_adminpads2_unknown-status": "Toobdteʹmes status" +} diff --git a/admin/public/ep_admin_pads/sq.json b/admin/public/ep_admin_pads/sq.json new file mode 100644 index 000000000..cc4740763 --- /dev/null +++ b/admin/public/ep_admin_pads/sq.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Besnik b" + ] + }, + "ep_adminpads2_action": "Veprim", + "ep_adminpads2_autoupdate-label": "Vetëpërditësohu, kur nga ndryshime blloku", + "ep_adminpads2_autoupdate.title": "Aktivizon ose çaktivizon përditësim të automatizuara për kërkesën e tanishme.", + "ep_adminpads2_confirm": "Doni vërtet të fshihet blloku {{padID}}?", + "ep_adminpads2_delete.value": "Fshije", + "ep_adminpads2_last-edited": "Përpunuar së fundi më", + "ep_adminpads2_loading": "Po ngarkohet…", + "ep_adminpads2_manage-pads": "Administroni blloqe", + "ep_adminpads2_no-results": "S’ka përfundime", + "ep_adminpads2_pad-user-count": "Numër përdoruesish blloku", + "ep_adminpads2_padname": "Emër blloku", + "ep_adminpads2_search-box.placeholder": "Term kërkimi", + "ep_adminpads2_search-button.value": "Kërko", + "ep_adminpads2_search-done": "Kërkim i plotë", + "ep_adminpads2_search-error-explanation": "Shërbyesi hasi një gabim teksa kërkohej për blloqe:", + "ep_adminpads2_search-error-title": "S’u arrit të merrej listë blloqesh", + "ep_adminpads2_search-heading": "Kërkoni për blloqe", + "ep_adminpads2_title": "Administrim blloku", + "ep_adminpads2_unknown-error": "Gabim i panjohur", + "ep_adminpads2_unknown-status": "Gjendje e panjohur" +} diff --git a/admin/public/ep_admin_pads/sv.json b/admin/public/ep_admin_pads/sv.json new file mode 100644 index 000000000..e77aaf2c4 --- /dev/null +++ b/admin/public/ep_admin_pads/sv.json @@ -0,0 +1,28 @@ +{ + "@metadata": { + "authors": [ + "Bengtsson96", + "WikiPhoenix" + ] + }, + "ep_adminpads2_action": "Åtgärd", + "ep_adminpads2_autoupdate-label": "Uppdatera automatiskt när blocket ändras", + "ep_adminpads2_autoupdate.title": "Aktivera eller inaktivera automatiska uppdatering för nuvarande förfrågan.", + "ep_adminpads2_confirm": "Vill du verkligen radera blocket {{padID}}?", + "ep_adminpads2_delete.value": "Radera", + "ep_adminpads2_last-edited": "Senast redigerad", + "ep_adminpads2_loading": "Läser in …", + "ep_adminpads2_manage-pads": "Hantera block", + "ep_adminpads2_no-results": "Inga resultat", + "ep_adminpads2_pad-user-count": "Antal blockanvändare", + "ep_adminpads2_padname": "Blocknamn", + "ep_adminpads2_search-box.placeholder": "Sökord", + "ep_adminpads2_search-button.value": "Sök", + "ep_adminpads2_search-done": "Sökning slutförd", + "ep_adminpads2_search-error-explanation": "Servern stötte på ett fel vid sökning efter block:", + "ep_adminpads2_search-error-title": "Misslyckades att hämta blocklista", + "ep_adminpads2_search-heading": "Sök efter block", + "ep_adminpads2_title": "Blockadministration", + "ep_adminpads2_unknown-error": "Okänt fel", + "ep_adminpads2_unknown-status": "Okänd status" +} diff --git a/admin/public/ep_admin_pads/sw.json b/admin/public/ep_admin_pads/sw.json new file mode 100644 index 000000000..f1beeecbb --- /dev/null +++ b/admin/public/ep_admin_pads/sw.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Andibecker" + ] + }, + "ep_adminpads2_action": "Hatua", + "ep_adminpads2_autoupdate-label": "Sasisha kiotomatiki kwenye mabadiliko ya pedi", + "ep_adminpads2_autoupdate.title": "Huwasha au kulemaza sasisho otomatiki kwa hoja ya sasa.", + "ep_adminpads2_confirm": "Je! Kweli unataka kufuta pedi {{padID}}?", + "ep_adminpads2_delete.value": "Futa", + "ep_adminpads2_last-edited": "Ilihaririwa mwisho", + "ep_adminpads2_loading": "Inapakia...", + "ep_adminpads2_manage-pads": "Dhibiti pedi", + "ep_adminpads2_no-results": "Hakuna matokeo", + "ep_adminpads2_pad-user-count": "Hesabu ya mtumiaji wa pedi", + "ep_adminpads2_padname": "Jina la utani", + "ep_adminpads2_search-box.placeholder": "Neno la utaftaji", + "ep_adminpads2_search-button.value": "Tafuta", + "ep_adminpads2_search-done": "Utafutaji umekamilika", + "ep_adminpads2_search-error-explanation": "Seva ilipata hitilafu wakati wa kutafuta pedi:", + "ep_adminpads2_search-error-title": "Imeshindwa kupata orodha ya pedi", + "ep_adminpads2_search-heading": "Tafuta pedi", + "ep_adminpads2_title": "Usimamizi wa pedi", + "ep_adminpads2_unknown-error": "Hitilafu isiyojulikana", + "ep_adminpads2_unknown-status": "Hali isiyojulikana" +} diff --git a/admin/public/ep_admin_pads/th.json b/admin/public/ep_admin_pads/th.json new file mode 100644 index 000000000..693e3f797 --- /dev/null +++ b/admin/public/ep_admin_pads/th.json @@ -0,0 +1,27 @@ +{ + "@metadata": { + "authors": [ + "Andibecker" + ] + }, + "ep_adminpads2_action": "การกระทำ", + "ep_adminpads2_autoupdate-label": "อัปเดตอัตโนมัติเมื่อเปลี่ยนแผ่น", + "ep_adminpads2_autoupdate.title": "เปิดหรือปิดการอัปเดตอัตโนมัติสำหรับคิวรีปัจจุบัน", + "ep_adminpads2_confirm": "คุณต้องการลบแพด {{padID}} จริงหรือไม่", + "ep_adminpads2_delete.value": "ลบ", + "ep_adminpads2_last-edited": "แก้ไขล่าสุด", + "ep_adminpads2_loading": "กำลังโหลด…", + "ep_adminpads2_manage-pads": "จัดการแผ่นรอง", + "ep_adminpads2_no-results": "ไม่มีผลลัพธ์", + "ep_adminpads2_pad-user-count": "จำนวนผู้ใช้แพด", + "ep_adminpads2_padname": "นามแฝง", + "ep_adminpads2_search-box.placeholder": "คำที่ต้องการค้นหา", + "ep_adminpads2_search-button.value": "ค้นหา", + "ep_adminpads2_search-done": "ค้นหาเสร็จสมบูรณ์", + "ep_adminpads2_search-error-explanation": "เซิร์ฟเวอร์พบข้อผิดพลาดขณะค้นหาแผ่นอิเล็กโทรด:", + "ep_adminpads2_search-error-title": "ไม่สามารถรับรายการแผ่นรอง", + "ep_adminpads2_search-heading": "ค้นหาแผ่นรอง", + "ep_adminpads2_title": "การบริหารแผ่น", + "ep_adminpads2_unknown-error": "ข้อผิดพลาดที่ไม่รู้จัก", + "ep_adminpads2_unknown-status": "ไม่ทราบสถานะ" +} diff --git a/admin/public/ep_admin_pads/tl.json b/admin/public/ep_admin_pads/tl.json new file mode 100644 index 000000000..238e01236 --- /dev/null +++ b/admin/public/ep_admin_pads/tl.json @@ -0,0 +1,17 @@ +{ + "@metadata": { + "authors": [ + "Mrkczr" + ] + }, + "ep_adminpads2_action": "Kilos", + "ep_adminpads2_delete.value": "Burahin", + "ep_adminpads2_last-edited": "Huling binago", + "ep_adminpads2_loading": "Naglo-load...", + "ep_adminpads2_no-results": "Walang mga resulta", + "ep_adminpads2_search-box.placeholder": "Mga katagang hahanapin:", + "ep_adminpads2_search-button.value": "Hanapin", + "ep_adminpads2_search-done": "Natapos na ang paghahanap", + "ep_adminpads2_unknown-error": "Hindi nalalamang kamalian", + "ep_adminpads2_unknown-status": "Hindi alam na katayuan" +} diff --git a/admin/public/ep_admin_pads/tr.json b/admin/public/ep_admin_pads/tr.json new file mode 100644 index 000000000..7e2e9d402 --- /dev/null +++ b/admin/public/ep_admin_pads/tr.json @@ -0,0 +1,28 @@ +{ + "@metadata": { + "authors": [ + "Hedda", + "MuratTheTurkish" + ] + }, + "ep_adminpads2_action": "Eylem", + "ep_adminpads2_autoupdate-label": "Bloknot değişikliklerinde otomatik güncelleme", + "ep_adminpads2_autoupdate.title": "Mevcut sorgu için otomatik güncellemeleri etkinleştirir veya devre dışı bırakır.", + "ep_adminpads2_confirm": "{{padID}} bloknotunu gerçekten silmek istiyor musunuz?", + "ep_adminpads2_delete.value": "Sil", + "ep_adminpads2_last-edited": "Son düzenleme", + "ep_adminpads2_loading": "Yükleniyor...", + "ep_adminpads2_manage-pads": "Bloknotları yönet", + "ep_adminpads2_no-results": "Sonuç yok", + "ep_adminpads2_pad-user-count": "Bloknot kullanıcı sayısı", + "ep_adminpads2_padname": "Bloknot adı", + "ep_adminpads2_search-box.placeholder": "Terimi ara", + "ep_adminpads2_search-button.value": "Ara", + "ep_adminpads2_search-done": "Arama tamamlandı", + "ep_adminpads2_search-error-explanation": "Sunucu, bloknotları ararken bir hatayla karşılaştı:", + "ep_adminpads2_search-error-title": "Bloknot listesi alınamadı", + "ep_adminpads2_search-heading": "Bloknotları ara", + "ep_adminpads2_title": "Bloknot yönetimi", + "ep_adminpads2_unknown-error": "Bilinmeyen hata", + "ep_adminpads2_unknown-status": "Bilinmeyen durum" +} diff --git a/admin/public/ep_admin_pads/uk.json b/admin/public/ep_admin_pads/uk.json new file mode 100644 index 000000000..c5c95f722 --- /dev/null +++ b/admin/public/ep_admin_pads/uk.json @@ -0,0 +1,28 @@ +{ + "@metadata": { + "authors": [ + "DDPAT", + "Ice bulldog" + ] + }, + "ep_adminpads2_action": "Дія", + "ep_adminpads2_autoupdate-label": "Автоматичне оновлення при зміні майданчика", + "ep_adminpads2_autoupdate.title": "Вмикає або вимикає автоматичне оновлення поточного запиту.", + "ep_adminpads2_confirm": "Ви дійсно хочете видалити панель {{padID}}?", + "ep_adminpads2_delete.value": "Видалити", + "ep_adminpads2_last-edited": "Останнє редагування", + "ep_adminpads2_loading": "Завантаження…", + "ep_adminpads2_manage-pads": "Управління майданчиками", + "ep_adminpads2_no-results": "Немає результатів", + "ep_adminpads2_pad-user-count": "Кількість майданчиків користувача", + "ep_adminpads2_padname": "Назва майданчика", + "ep_adminpads2_search-box.placeholder": "Пошуковий термін", + "ep_adminpads2_search-button.value": "Пошук", + "ep_adminpads2_search-done": "Пошук завершено", + "ep_adminpads2_search-error-explanation": "Під час пошуку педів сервер виявив помилку:", + "ep_adminpads2_search-error-title": "Не вдалося отримати список панелей", + "ep_adminpads2_search-heading": "Пошук майданчиків", + "ep_adminpads2_title": "Введення майданчиків", + "ep_adminpads2_unknown-error": "Невідома помилка", + "ep_adminpads2_unknown-status": "Невідомий статус" +} diff --git a/admin/public/ep_admin_pads/zh-hans.json b/admin/public/ep_admin_pads/zh-hans.json new file mode 100644 index 000000000..cdf0d945f --- /dev/null +++ b/admin/public/ep_admin_pads/zh-hans.json @@ -0,0 +1,29 @@ +{ + "@metadata": { + "authors": [ + "GuoPC", + "Lakejason0", + "沈澄心" + ] + }, + "ep_adminpads2_action": "操作", + "ep_adminpads2_autoupdate-label": "在记事本更改时自动更新", + "ep_adminpads2_autoupdate.title": "启用或禁用目前查询的自动更新", + "ep_adminpads2_confirm": "您确定要删除记事本 {{padID}}?", + "ep_adminpads2_delete.value": "删除", + "ep_adminpads2_last-edited": "上次编辑于", + "ep_adminpads2_loading": "正在加载…", + "ep_adminpads2_manage-pads": "管理记事本", + "ep_adminpads2_no-results": "没有结果", + "ep_adminpads2_pad-user-count": "记事本用户数", + "ep_adminpads2_padname": "记事本名称", + "ep_adminpads2_search-box.placeholder": "搜索关键词", + "ep_adminpads2_search-button.value": "搜索", + "ep_adminpads2_search-done": "搜索完成", + "ep_adminpads2_search-error-explanation": "搜索记事本时服务器发生错误:", + "ep_adminpads2_search-error-title": "获取记事本列表失败", + "ep_adminpads2_search-heading": "搜索记事本", + "ep_adminpads2_title": "记事本管理", + "ep_adminpads2_unknown-error": "未知错误", + "ep_adminpads2_unknown-status": "未知状态" +} diff --git a/admin/public/ep_admin_pads/zh-hant.json b/admin/public/ep_admin_pads/zh-hant.json new file mode 100644 index 000000000..daeed55f5 --- /dev/null +++ b/admin/public/ep_admin_pads/zh-hant.json @@ -0,0 +1,28 @@ +{ + "@metadata": { + "authors": [ + "HellojoeAoPS", + "Kly" + ] + }, + "ep_adminpads2_action": "操作", + "ep_adminpads2_autoupdate-label": "在記事本更改時自動更新", + "ep_adminpads2_autoupdate.title": "啟用或停用目前查詢的自動更新。", + "ep_adminpads2_confirm": "您確定要刪除記事本 {{padID}}?", + "ep_adminpads2_delete.value": "刪除", + "ep_adminpads2_last-edited": "上一次編輯", + "ep_adminpads2_loading": "載入中…", + "ep_adminpads2_manage-pads": "管理記事本", + "ep_adminpads2_no-results": "沒有結果", + "ep_adminpads2_pad-user-count": "記事本使用者數", + "ep_adminpads2_padname": "記事本名稱", + "ep_adminpads2_search-box.placeholder": "搜尋關鍵字", + "ep_adminpads2_search-button.value": "搜尋", + "ep_adminpads2_search-done": "搜尋完成", + "ep_adminpads2_search-error-explanation": "當搜尋記事本時伺服器發生錯誤:", + "ep_adminpads2_search-error-title": "取得記事本清單失敗", + "ep_adminpads2_search-heading": "搜尋記事本", + "ep_adminpads2_title": "記事本管理", + "ep_adminpads2_unknown-error": "不明錯誤", + "ep_adminpads2_unknown-status": "不明狀態" +} diff --git a/admin/public/fond.jpg b/admin/public/fond.jpg new file mode 100644 index 000000000..81357c7bb Binary files /dev/null and b/admin/public/fond.jpg differ diff --git a/admin/src/App.css b/admin/src/App.css new file mode 100644 index 000000000..e69de29bb diff --git a/admin/src/App.tsx b/admin/src/App.tsx new file mode 100644 index 000000000..ae23ab3d3 --- /dev/null +++ b/admin/src/App.tsx @@ -0,0 +1,120 @@ +import {useEffect, useState} from 'react' +import './App.css' +import {connect} from 'socket.io-client' +import {isJSONClean} from './utils/utils.ts' +import {NavLink, Outlet, useNavigate} from "react-router-dom"; +import {useStore} from "./store/store.ts"; +import {LoadingScreen} from "./utils/LoadingScreen.tsx"; +import {Trans, useTranslation} from "react-i18next"; +import {Cable, Construction, Crown, NotepadText, Wrench, PhoneCall, LucideMenu} from "lucide-react"; + +const WS_URL = import.meta.env.DEV ? 'http://localhost:9001' : '' +export const App = () => { + const setSettings = useStore(state => state.setSettings); + const {t} = useTranslation() + const navigate = useNavigate() + const [sidebarOpen, setSidebarOpen] = useState(true) + + useEffect(() => { + fetch('/admin-auth/', { + method: 'POST' + }).then((value) => { + if (!value.ok) { + navigate('/login') + } + }).catch(() => { + navigate('/login') + }) + }, []); + + useEffect(() => { + document.title = t('admin.page-title') + + useStore.getState().setShowLoading(true); + const settingSocket = connect(`${WS_URL}/settings`, { + transports: ['websocket'], + }); + + const pluginsSocket = connect(`${WS_URL}/pluginfw/installer`, { + transports: ['websocket'], + }) + + pluginsSocket.on('connect', () => { + useStore.getState().setPluginsSocket(pluginsSocket); + }); + + + settingSocket.on('connect', () => { + useStore.getState().setSettingsSocket(settingSocket); + useStore.getState().setShowLoading(false) + settingSocket.emit('load'); + console.log('connected'); + }); + + settingSocket.on('disconnect', (reason) => { + // The settingSocket.io client will automatically try to reconnect for all reasons other than "io + // server disconnect". + useStore.getState().setShowLoading(true) + if (reason === 'io server disconnect') { + settingSocket.connect(); + } + }); + + settingSocket.on('settings', (settings) => { + /* Check whether the settings.json is authorized to be viewed */ + if (settings.results === 'NOT_ALLOWED') { + console.log('Not allowed to view settings.json') + return; + } + + /* Check to make sure the JSON is clean before proceeding */ + if (isJSONClean(settings.results)) { + setSettings(settings.results); + } else { + alert('Invalid JSON'); + } + useStore.getState().setShowLoading(false); + }); + + settingSocket.on('saveprogress', (status) => { + console.log(status) + }) + + return () => { + settingSocket.disconnect(); + pluginsSocket.disconnect() + } + }, []); + + return
+ +
+
+ + +

Etherpad

+
+
    { + if (window.innerWidth < 768) { + setSidebarOpen(false) + } + }}> +
  • +
  • +
  • +
  • +
  • Communication
  • +
+
+
+ +
+ +
+
+} + +export default App diff --git a/admin/src/components/IconButton.tsx b/admin/src/components/IconButton.tsx new file mode 100644 index 000000000..876a55779 --- /dev/null +++ b/admin/src/components/IconButton.tsx @@ -0,0 +1,16 @@ +import {FC, JSX, ReactElement} from "react"; + +export type IconButtonProps = { + icon: JSX.Element, + title: string|ReactElement, + onClick: ()=>void, + className?: string, + disabled?: boolean +} + +export const IconButton:FC = ({icon,className,onClick,title, disabled})=>{ + return +} diff --git a/admin/src/components/SearchField.tsx b/admin/src/components/SearchField.tsx new file mode 100644 index 000000000..62a965d40 --- /dev/null +++ b/admin/src/components/SearchField.tsx @@ -0,0 +1,14 @@ +import {ChangeEventHandler, FC} from "react"; +import {Search} from 'lucide-react' +export type SearchFieldProps = { + value: string, + onChange: ChangeEventHandler, + placeholder?: string +} + +export const SearchField:FC = ({onChange,value, placeholder})=>{ + return + + + +} diff --git a/admin/src/components/ShoutType.ts b/admin/src/components/ShoutType.ts new file mode 100644 index 000000000..f7e8b1df3 --- /dev/null +++ b/admin/src/components/ShoutType.ts @@ -0,0 +1,13 @@ +export type ShoutType = { + type: string, + data:{ + type: string, + payload: { + message: { + message: string, + sticky: boolean + }, + timestamp: number + } + } +} diff --git a/admin/src/index.css b/admin/src/index.css new file mode 100644 index 000000000..acc0d2e97 --- /dev/null +++ b/admin/src/index.css @@ -0,0 +1,870 @@ +:root { + --etherpad-color: #0f775b; + --etherpad-comp: #9C8840; + --etherpad-light: #99FF99; + --sidebar-width: 20em; +} + +@font-face { + font-family: Karla; + src: url(/Karla-Regular.ttf); +} + +html, body, #root { + box-sizing: border-box; + height: 100%; + font-family: "Karla", sans-serif; +} + +*, *:before, *:after { + box-sizing: inherit; + font-size: 16px; +} + +body { + margin: 0; + color: #333; + font: 14px helvetica, sans-serif; + background: #eee; +} + +div.menu { + left: 0; + transition: left .3s; + height: 100vh; + font-size: 16px; + font-weight: bolder; + display: flex; + align-items: center; + justify-content: center; + width: var(--sidebar-width); + z-index: 99; + position: fixed; +} + + +.icon-button { + display: flex; + gap: 10px; + background-color: var(--etherpad-color); + color: white; + border: none; + padding: 10px 20px; + border-radius: 5px; + cursor: pointer; +} + +.icon-button svg { + align-self: center; +} + +.icon-button span { + align-self: center; +} + + +div.menu span:first-child { + display: flex; + justify-content: center; +} + +div.menu span:first-child svg { + margin-right: 10px; + align-self: center; +} + + +div.menu h1 { + font-size: 50px; + text-align: center; +} + +.inner-menu { + border-radius: 0 20px 20px 0; + padding: 10px; + flex-grow: 100; + background-color: var(--etherpad-comp); + color: white; + height: 100vh; +} + +div.menu ul { + color: white; + padding: 0; +} + +div.menu li a { + display: flex; + gap: 10px; + margin-bottom: 20px; +} + +div.menu svg { + align-self: center; +} + +div.menu li { + padding: 10px; + color: white; + list-style: none; + margin-left: 3px; + line-height: 3; +} + + +div.menu li:has(.active) { + background-color: #9C885C; +} + +div.menu li a { + color: lightgray; +} + + +div.innerwrapper { + transition: margin-left .3s; + isolation: isolate; + background-color: #F0F0F0; + overflow: auto; + height: 100vh; + flex-grow: 100; + margin-left: var(--sidebar-width); + padding: 20px 20px 20px; +} + +div.innerwrapper-err { + display: none; +} + +#wrapper { + background: none repeat scroll 0px 0px #FFFFFF; + box-shadow: 0px 1px 10px rgba(0, 0, 0, 0.2); + min-height: 100%; /*always display a scrollbar*/ +} + +h1 { + font-size: 29px; +} + +h2 { + font-size: 24px; +} + +.separator { + margin: 10px 0; + height: 1px; + background: #aaa; + background: -webkit-linear-gradient(left, #fff, #aaa 20%, #aaa 80%, #fff); + background: -moz-linear-gradient(left, #fff, #aaa 20%, #aaa 80%, #fff); + background: -ms-linear-gradient(left, #fff, #aaa 20%, #aaa 80%, #fff); + background: -o-linear-gradient(left, #fff, #aaa 20%, #aaa 80%, #fff); +} + +form { + margin-bottom: 0; +} + +#inner { + width: 300px; + margin: 0 auto; +} + +input { + font-weight: bold; + font-size: 15px; +} + + +.sort { + cursor: pointer; +} + +.sort:after { + content: '▲▼' +} + +.sort.up:after { + content: '▲' +} + +.sort.down:after { + content: '▼' +} + + +#installed-plugins thead tr th:nth-child(3) { + width: 15%; +} + +table { + border: 1px solid #ddd; + border-radius: 3px; + border-spacing: 0; + width: 100%; + margin: 20px 0; +} + +.table-container { + width: 100%; + overflow: auto; + max-height: 90vh; +} + + +#available-plugins th:first-child, #available-plugins th:nth-child(2) { + text-align: center; +} + +td, th { + padding: 5px; +} + +.template { + display: none; +} + +#installed-plugins td > div { + position: relative; /* Allows us to position the loading indicator relative to this row */ + display: inline-block; /*make this fill the whole cell*/ + width: 100%; +} + +.messages { + height: 5em; +} + +.messages * { + display: none; + text-align: center; +} + +.messages .fetching { + display: block; +} + +.progress { + position: absolute; + top: 0; + left: 0; + bottom: 0; + right: 0; + padding: auto; + + background: rgb(255, 255, 255); + display: none; +} + +#search-progress.progress { + padding-top: 20%; + background: rgba(255, 255, 255, 0.3); +} + +.progress * { + display: block; + margin: 0 auto; + text-align: center; + color: #666; +} + + +.settings-page { + display: flex; + flex-direction: column; + gap: 20px; + height: 100%; +} + +.settings { + flex-grow: max(1, 1); + outline: none; + width: 100%; + resize: none; + font-family: monospace; +} + +#response { + display: inline; +} + +a:link, a:visited, a:hover, a:focus { + color: #333333; + text-decoration: none; +} + +a:focus, a:hover { + text-decoration: underline; +} + +.installed-results a:link, +.search-results a:link, +.installed-results a:visited, +.search-results a:visited, +.installed-results a:hover, +.search-results a:hover, +.installed-results a:focus, +.search-results a:focus { + text-decoration: underline; +} + +.installed-results a:focus, +.search-results a:focus, +.installed-results a:hover, +.search-results a:hover { + text-decoration: none; +} + +pre { + white-space: pre-wrap; + word-wrap: break-word; +} + + +#icon-button { + color: var(--etherpad-color); + top: 10px; + background-color: transparent; + border: none; + z-index: 99; + position: absolute; + left: 10px; +} + + +.inner-menu span:nth-child(2) { + display: flex; + margin-top: 30px; +} + +#wrapper.closed .menu { + left: calc(-1 * var(--sidebar-width)); +} + +#wrapper.closed .innerwrapper { + margin-left: 0; +} + +@media (max-width: 800px) { + + div.innerwrapper { + margin-left: 0; + } + + .inner-menu { + border-radius: 0; + } + + div.menu { + height: auto; + border-right: none; + --sidebar-width: 100%; + float: left; + } + + table { + border: none; + } + + table, thead, tbody, td, tr { + display: block; + } + + thead tr { + display: none; + } + + tr { + border: 1px solid #ccc; + margin-bottom: 5px; + border-radius: 3px; + } + + td { + border: none; + border-bottom: 1px solid #eee; + position: relative; + padding-left: 50%; + white-space: normal; + text-align: left; + } + + td.name { + word-wrap: break-word; + } + + td:before { + position: absolute; + top: 6px; + left: 6px; + text-align: left; + padding-right: 10px; + white-space: nowrap; + font-weight: bold; + content: attr(data-label); + } + + td:last-child { + border-bottom: none; + } + + table input[type="button"] { + float: none; + } +} + + +.settings-button-bar { + margin-top: 10px; + display: flex; + gap: 10px; +} + +.login-background { + background-image: url("/fond.jpg"); + background-position: center; + background-repeat: no-repeat; + background-size: cover; + display: flex; + justify-content: center; + align-items: center; + height: 100vh; + background-color: #f0f0f0; +} + +.login-inner-box div { + margin-top: 1rem; +} + +.login-inner-box [type=submit] { + margin-top: 2rem; +} + + +.login-textinput { + width: 100%; + padding: 10px; + background-color: #fffacc; + border-radius: 5px; + border: 1px solid #ccc; + margin-bottom: 10px; +} + +.login-box { + padding: 20px; + border-radius: 40px; + box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); + background-color: #fff; +} + + +@media (max-width: 900px) { + .login-box { + width: 90% + } +} + +.login-inner-box { + position: relative; + padding: 20px; +} + +.login-title { + padding: 0; + margin: 0; + text-align: center; + color: var(--etherpad-color); + font-size: 4rem; + font-weight: 1000; +} + +.login-button { + padding: 10px; + background-color: var(--etherpad-color); + color: white; + border: none; + border-radius: 5px; + cursor: pointer; + width: 100%; + height: 40px; +} + +.dialog-overlay { + position: fixed; + inset: 0; + background-color: white; + z-index: 100; +} + + +.dialog-confirm-overlay { + position: fixed; + inset: 0; + background-color: rgba(0, 0, 0, 0.5); + z-index: 100; +} + + +.dialog-confirm-content { + position: fixed; + top: 50%; + left: 50%; + background-color: white; + transform: translate(-50%, -50%); + padding: 20px; + z-index: 101; +} + + +.dialog-content { + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + padding: 20px; + z-index: 101; +} + +.dialog-title { + color: var(--etherpad-color); + font-size: 2em; + margin-bottom: 20px; +} + + +.ToastViewport { + position: fixed; + top: 10px; + right: 20px; + display: flex; + flex-direction: column; + gap: 10px; + width: 390px; + max-width: 100vw; + margin: 0; + list-style: none; + z-index: 2147483647; + outline: none; +} + +.ToastRootSuccess { + background-color: lawngreen; +} + +.ToastRootFailure { + background-color: red; +} + +.ToastRootFailure > .ToastTitle { + color: white; +} + +.ToastRoot { + border-radius: 20px; + box-shadow: hsl(206 22% 7% / 35%) 0px 10px 38px -10px, hsl(206 22% 7% / 20%) 0px 10px 20px -15px; + padding: 15px; + display: grid; + grid-template-areas: 'title action' 'description action'; + grid-template-columns: auto max-content; + column-gap: 15px; + align-items: center; +} + +.ToastRoot[data-state='open'] { + animation: slideIn 150ms cubic-bezier(0.16, 1, 0.3, 1); +} + +.ToastRoot[data-state='closed'] { + animation: hide 100ms ease-in; +} + +.ToastRoot[data-swipe='move'] { + transform: translateX(var(--radix-toast-swipe-move-x)); +} + +.ToastRoot[data-swipe='cancel'] { + transform: translateX(0); + transition: transform 200ms ease-out; +} + +.ToastRoot[data-swipe='end'] { + animation: swipeOut 100ms ease-out; +} + +@keyframes hide { + from { + opacity: 1; + } + to { + opacity: 0; + } +} + +@keyframes slideIn { + from { + transform: translateX(calc(100% + var(--viewport-padding))); + } + to { + transform: translateX(0); + } +} + +@keyframes swipeOut { + from { + transform: translateX(var(--radix-toast-swipe-end-x)); + } + to { + transform: translateX(calc(100% + var(--viewport-padding))); + } +} + +.ToastTitle { + grid-area: title; + margin-bottom: 5px; + font-weight: 500; + color: var(--slate-12); + padding: 10px; + font-size: 15px; +} + +.ToastDescription { + grid-area: description; + margin: 0; + color: var(--slate-11); + font-size: 13px; + line-height: 1.3; +} + +.ToastAction { + grid-area: action; +} + +.help-block { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 20px +} + +.search-field { + position: relative; +} + +.search-field input { + border-color: transparent; + border-radius: 20px; + height: 2.5rem; + width: 100%; + padding: 5px 5px 5px 30px; +} + +.search-field input:focus { + outline: none; +} + + +.send-message { + position: relative; +} + +.send-message input { + width: auto; +} + +.send-message { +} + +.send-message svg { + position: absolute; + right: 3px; + bottom: -3px; + left: auto !important; +} + +.search-field svg { + position: absolute; + left: 3px; + bottom: -3px; +} + + +.search-field svg { + color: gray +} + +table { + margin: 25px 0; + font-size: 0.9em; + font-family: sans-serif; + min-width: 400px; + box-shadow: 0 0 20px rgba(0, 0, 0, 0.15); +} + +th:first-child { + border-top-left-radius: 10px; +} + +th:last-child { + border-top-right-radius: 10px; +} + +table thead tr { + font-size: 25px; + background-color: var(--etherpad-color); + color: #ffffff; + text-align: left; +} + +table tbody tr { + border-bottom: 1px solid #dddddd; +} + +table tr:nth-child(even) td { + background-color: lightgray; +} + +table tr td { + padding: 12px 15px; +} + +table tbody tr:nth-of-type(even) { + background-color: #f3f3f3; +} + +table tbody tr:last-of-type { + border-bottom: 2px solid #009879; +} + +table tbody tr.active-row { + font-weight: bold; + color: #009879; +} + + +.pad-pagination { + display: flex; + justify-content: center; + gap: 10px; + margin-top: 20px; +} + +.pad-pagination button { + display: flex; + padding: 10px 20px; + border-radius: 5px; + border: none; + color: black; + cursor: pointer; +} + + +.pad-pagination button:disabled { + background: transparent; + color: lightgrey; + cursor: not-allowed; +} + +.pad-pagination span { + align-self: center; +} + +.pad-pagination > span { + font-size: 20px; +} + + +.login-page .login-form .input-control input[type=text], .login-page .login-form .input-control input[type=email], .login-page .login-form .input-control input[type=password], .login-page .signup-form .input-control input[type=text], .login-page .signup-form .input-control input[type=email], .login-page .signup-form .input-control input[type=password], .login-page .forgot-form .input-control input[type=text], .login-page .forgot-form .input-control input[type=email], .login-page .forgot-form .input-control input[type=password] { + width: 100%; + padding: 12px 20px; + margin: 8px 0; + display: inline-block; + border-bottom: 2px solid #ccc; + border-top: 0; + border-left: 0; + border-right: 0; + -webkit-box-sizing: border-box; + box-sizing: border-box; + border-radius: 5px; + font-size: 14px; + color: #666; + background-color: #f8f8f8; + -webkit-transition: all 0.3s ease-in-out; + transition: all 0.3s ease-in-out; +} + +input, button, select, optgroup, textarea { + margin: 0; + font-family: inherit; + font-size: inherit; + line-height: inherit; +} + +.icon-input { + position: relative; +} + +.icon-input svg { + position: absolute; + top: 50%; + transform: translateY(-50%); + right: 10px; + color: #666; +} + + +.SwitchRoot { + align-self: center; + width: 60px; + height: 30px; + background-color: black; + border-radius: 9999px; + position: relative; + box-shadow: 0 2px 10px var(--black-a7); + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); +} + +.SwitchRoot:focus { + box-shadow: 0 0 0 2px black; +} + +.SwitchRoot[data-state='checked'] { + background-color: var(--etherpad-color); +} + +.SwitchThumb { + display: block; + width: 20px; + height: 20px; + background-color: white; + border-radius: 9999px; + box-shadow: 0 2px 2px var(--black-a7); + transition: transform 100ms; + transform: translateX(2px); + will-change: transform; +} + +.SwitchThumb[data-state='checked'] { + transform: translateX(25px); +} + +.Label { + color: white; + font-size: 15px; + line-height: 1; +} + +.message { + position: relative; + padding: 10px; + border: 1px solid #e0e0e0; + margin: 10px 20px 10px 10px; + border-radius: 10px 0 10px 10px; + background-color: var(--etherpad-color); + color: white +} + +.search-pads { + text-align: center; +} + +.search-pads-body tr td:last-child { + display: flex; + justify-content: center; +} diff --git a/admin/src/localization/i18n.ts b/admin/src/localization/i18n.ts new file mode 100644 index 000000000..67ae140e7 --- /dev/null +++ b/admin/src/localization/i18n.ts @@ -0,0 +1,57 @@ +import i18n from 'i18next' +import {initReactI18next} from "react-i18next"; +import LanguageDetector from 'i18next-browser-languagedetector' + + +import { BackendModule } from 'i18next'; + +const LazyImportPlugin: BackendModule = { + type: 'backend', + init: function () { + }, + read: async function (language, namespace, callback) { + + let baseURL = import.meta.env.BASE_URL + if(namespace === "translation") { + // If default we load the translation file + baseURL+=`/locales/${language}.json` + } else { + // Else we load the former plugin translation file + baseURL+=`/${namespace}/${language}.json` + } + + const localeJSON = await fetch(baseURL, { + cache: "force-cache" + }) + let json; + + try { + json = JSON.parse(await localeJSON.text()) + } catch(e) { + callback(new Error("Error loading"), null); + } + + + callback(null, json); + }, + + save: function () { + }, + + create: function () { + /* save the missing translation */ + }, +}; + +i18n + .use(LanguageDetector) + .use(LazyImportPlugin) + .use(initReactI18next) + .init( + { + ns: ['translation','ep_admin_pads'], + fallbackLng: 'en' + } + ) + +export default i18n diff --git a/admin/src/main.tsx b/admin/src/main.tsx new file mode 100644 index 000000000..5efc26de6 --- /dev/null +++ b/admin/src/main.tsx @@ -0,0 +1,42 @@ +import React from 'react' +import ReactDOM from 'react-dom/client' +import App from './App.tsx' +import './index.css' +import {createBrowserRouter, createRoutesFromElements, Route, RouterProvider} from "react-router-dom"; +import {HomePage} from "./pages/HomePage.tsx"; +import {SettingsPage} from "./pages/SettingsPage.tsx"; +import {LoginScreen} from "./pages/LoginScreen.tsx"; +import {HelpPage} from "./pages/HelpPage.tsx"; +import * as Toast from '@radix-ui/react-toast' +import {I18nextProvider} from "react-i18next"; +import i18n from "./localization/i18n.ts"; +import {PadPage} from "./pages/PadPage.tsx"; +import {ToastDialog} from "./utils/Toast.tsx"; +import {ShoutPage} from "./pages/ShoutPage.tsx"; + +const router = createBrowserRouter(createRoutesFromElements( + <>}> + }/> + }/> + }/> + }/> + }/> + }/> + + }/> + +), { + basename: import.meta.env.BASE_URL +}) + + +ReactDOM.createRoot(document.getElementById('root')!).render( + + + + + + + + , +) diff --git a/admin/src/pages/HelpPage.tsx b/admin/src/pages/HelpPage.tsx new file mode 100644 index 000000000..dd9695b0a --- /dev/null +++ b/admin/src/pages/HelpPage.tsx @@ -0,0 +1,70 @@ +import {Trans} from "react-i18next"; +import {useStore} from "../store/store.ts"; +import {useEffect, useState} from "react"; +import {HelpObj} from "./Plugin.ts"; + +export const HelpPage = () => { + const settingsSocket = useStore(state=>state.settingsSocket) + const [helpData, setHelpData] = useState(); + + useEffect(() => { + if(!settingsSocket) return; + settingsSocket?.on('reply:help', (data) => { + setHelpData(data) + }); + + settingsSocket?.emit('help'); + }, [settingsSocket]); + + const renderHooks = (hooks:Record>) => { + return Object.keys(hooks).map((hookName, i) => { + return
+

{hookName}

+
    + {Object.keys(hooks[hookName]).map((hook, i) =>
  • {hook} +
      + {Object.keys(hooks[hookName][hook]).map((subHook, i) =>
    • {subHook}
    • )} +
    +
  • )} +
+
+ }) + } + + + if (!helpData) return
+ + return
+

+
+
+
{helpData?.epVersion}
+
+
{helpData.latestVersion}
+
Git sha
+
{helpData.gitCommit}
+
+

+
    + {helpData.installedPlugins.map((plugin, i) =>
  • {plugin}
  • )} +
+ +

+
    + {helpData.installedParts.map((part, i) =>
  • {part}
  • )} +
+ +

+ { + renderHooks(helpData.installedServerHooks) + } + +

+ + { + renderHooks(helpData.installedClientHooks) + } +

+ +
+} diff --git a/admin/src/pages/HomePage.tsx b/admin/src/pages/HomePage.tsx new file mode 100644 index 000000000..f5ce0a5ab --- /dev/null +++ b/admin/src/pages/HomePage.tsx @@ -0,0 +1,247 @@ +import {useStore} from "../store/store.ts"; +import {useEffect, useMemo, useState} from "react"; +import {InstalledPlugin, PluginDef, SearchParams} from "./Plugin.ts"; +import {useDebounce} from "../utils/useDebounce.ts"; +import {Trans, useTranslation} from "react-i18next"; +import {SearchField} from "../components/SearchField.tsx"; +import {ArrowUpFromDot, Download, Trash} from "lucide-react"; +import {IconButton} from "../components/IconButton.tsx"; +import {determineSorting} from "../utils/sorting.ts"; + + +export const HomePage = () => { + const pluginsSocket = useStore(state=>state.pluginsSocket) + const [plugins,setPlugins] = useState([]) + const installedPlugins = useStore(state=>state.installedPlugins) + const setInstalledPlugins = useStore(state=>state.setInstalledPlugins) + const [searchParams, setSearchParams] = useState({ + offset: 0, + limit: 99999, + sortBy: 'name', + sortDir: 'asc', + searchTerm: '' + }) + + const filteredInstallablePlugins = useMemo(()=>{ + return plugins.sort((a, b)=>{ + if(searchParams.sortBy === "version"){ + if(searchParams.sortDir === "asc"){ + return a.version.localeCompare(b.version) + } + return b.version.localeCompare(a.version) + } + + if(searchParams.sortBy === "last-updated"){ + if(searchParams.sortDir === "asc"){ + return a.time.localeCompare(b.time) + } + return b.time.localeCompare(a.time) + } + + + if (searchParams.sortBy === "name") { + if(searchParams.sortDir === "asc"){ + return a.name.localeCompare(b.name) + } + return b.name.localeCompare(a.name) + } + return 0 + }) + }, [plugins, searchParams]) + + const sortedInstalledPlugins = useMemo(()=>{ + return useStore.getState().installedPlugins.sort((a, b)=>{ + + if(a.name < b.name){ + return -1 + } + if(a.name > b.name){ + return 1 + } + return 0 + }) + + } ,[installedPlugins, searchParams]) + + const [searchTerm, setSearchTerm] = useState('') + const {t} = useTranslation() + + + useEffect(() => { + if(!pluginsSocket){ + return + } + + pluginsSocket.on('results:installed', (data:{ + installed: InstalledPlugin[] + })=>{ + setInstalledPlugins(data.installed) + }) + + pluginsSocket.on('results:updatable', (data) => { + const newInstalledPlugins = useStore.getState().installedPlugins.map(plugin => { + if (data.updatable.includes(plugin.name)) { + return { + ...plugin, + updatable: true + } + } + return plugin + }) + setInstalledPlugins(newInstalledPlugins) + }) + + pluginsSocket.on('finished:install', () => { + pluginsSocket!.emit('getInstalled'); + }) + + pluginsSocket.on('finished:uninstall', () => { + console.log("Finished uninstall") + }) + + + // Reload on reconnect + pluginsSocket.on('connect', ()=>{ + // Initial retrieval of installed plugins + pluginsSocket.emit('getInstalled'); + pluginsSocket.emit('search', searchParams) + }) + + pluginsSocket.emit('getInstalled'); + + // check for updates every 5mins + const interval = setInterval(() => { + pluginsSocket.emit('checkUpdates'); + }, 1000 * 60 * 5); + + return ()=>{ + clearInterval(interval) + } + }, [pluginsSocket]); + + + useEffect(() => { + if (!pluginsSocket) { + return + } + pluginsSocket?.emit('search', searchParams) + pluginsSocket!.on('results:search', (data: { + results: PluginDef[] + }) => { + setPlugins(data.results) + }) + pluginsSocket!.on('results:searcherror', (data: {error: string}) => { + console.log(data.error) + useStore.getState().setToastState({ + open: true, + title: "Error retrieving plugins", + success: false + }) + }) + }, [searchParams, pluginsSocket]); + + const uninstallPlugin = (pluginName: string)=>{ + pluginsSocket!.emit('uninstall', pluginName); + // Remove plugin + setInstalledPlugins(installedPlugins.filter(i=>i.name !== pluginName)) + } + + const installPlugin = (pluginName: string)=>{ + pluginsSocket!.emit('install', pluginName); + setPlugins(plugins.filter(plugin=>plugin.name !== pluginName)) + } + + useDebounce(()=>{ + setSearchParams({ + ...searchParams, + offset: 0, + searchTerm: searchTerm + }) + }, 500, [searchTerm]) + + + return
+

+ +

+ + + + + + + + + + + {sortedInstalledPlugins.map((plugin, index) => { + return + + + + + })} + +
{plugin.name}{plugin.version} + { + plugin.updatable ? + installPlugin(plugin.name)} icon={} title="Update"> + : } title={} onClick={() => uninstallPlugin(plugin.name)}/> + } +
+ + +

+ {setSearchTerm(v.target.value)}} placeholder={t('admin_plugins.available_search.placeholder')} value={searchTerm}/> + +
+ + + + + + + + + + + + {(filteredInstallablePlugins.length > 0) ? + filteredInstallablePlugins.map((plugin) => { + return + + + + + + + }) + : + + } + +
{ + setSearchParams({ + ...searchParams, + sortBy: 'name', + sortDir: searchParams.sortDir === "asc"? "desc": "asc" + }) + }}> + { + setSearchParams({ + ...searchParams, + sortBy: 'version', + sortDir: searchParams.sortDir === "asc"? "desc": "asc" + }) + }}>{ + setSearchParams({ + ...searchParams, + sortBy: 'last-updated', + sortDir: searchParams.sortDir === "asc"? "desc": "asc" + }) + }}>
{plugin.name}{plugin.description}{plugin.version}{plugin.time} + } onClick={() => installPlugin(plugin.name)} title={}/> +
{searchTerm == '' ? : }
+
+
+} diff --git a/admin/src/pages/LoginScreen.tsx b/admin/src/pages/LoginScreen.tsx new file mode 100644 index 000000000..61ac8993e --- /dev/null +++ b/admin/src/pages/LoginScreen.tsx @@ -0,0 +1,61 @@ +import {useStore} from "../store/store.ts"; +import {useNavigate} from "react-router-dom"; +import {SubmitHandler, useForm} from "react-hook-form"; +import {Eye, EyeOff} from "lucide-react"; +import {useState} from "react"; + +type Inputs = { + username: string + password: string +} + +export const LoginScreen = ()=>{ + const navigate = useNavigate() + const [passwordVisible, setPasswordVisible] = useState(false) + + const { + register, + handleSubmit} = useForm() + + const login: SubmitHandler = ({username,password})=>{ + fetch('/admin-auth/', { + method: 'POST', + headers:{ + Authorization: `Basic ${btoa(`${username}:${password}`)}` + } + }).then(r=>{ + if(!r.ok) { + useStore.getState().setToastState({ + open: true, + title: "Login failed", + success: false + }) + } else { + navigate('/') + } + }).catch(e=>{ + console.error(e) + }) + } + + return
+
+

Etherpad

+
+
Username
+ +
Password
+ + + {passwordVisible? setPasswordVisible(!passwordVisible)}/> : + setPasswordVisible(!passwordVisible)}/>} + + +
+
+
+} diff --git a/admin/src/pages/PadPage.tsx b/admin/src/pages/PadPage.tsx new file mode 100644 index 000000000..b5db854f5 --- /dev/null +++ b/admin/src/pages/PadPage.tsx @@ -0,0 +1,221 @@ +import {Trans, useTranslation} from "react-i18next"; +import {useEffect, useMemo, useState} from "react"; +import {useStore} from "../store/store.ts"; +import {PadSearchQuery, PadSearchResult} from "../utils/PadSearch.ts"; +import {useDebounce} from "../utils/useDebounce.ts"; +import {determineSorting} from "../utils/sorting.ts"; +import * as Dialog from "@radix-ui/react-dialog"; +import {IconButton} from "../components/IconButton.tsx"; +import {ChevronLeft, ChevronRight, Eye, Trash2, FileStack} from "lucide-react"; +import {SearchField} from "../components/SearchField.tsx"; + +export const PadPage = ()=>{ + const settingsSocket = useStore(state=>state.settingsSocket) + const [searchParams, setSearchParams] = useState({ + offset: 0, + limit: 12, + pattern: '', + sortBy: 'padName', + ascending: true + }) + const {t} = useTranslation() + const [searchTerm, setSearchTerm] = useState('') + const pads = useStore(state=>state.pads) + const [currentPage, setCurrentPage] = useState(0) + const [deleteDialog, setDeleteDialog] = useState(false) + const [errorText, setErrorText] = useState(null) + const [padToDelete, setPadToDelete] = useState('') + const pages = useMemo(()=>{ + if(!pads){ + return 0; + } + + return Math.ceil(pads!.total / searchParams.limit) + },[pads, searchParams.limit]) + + useDebounce(()=>{ + setSearchParams({ + ...searchParams, + pattern: searchTerm + }) + + }, 500, [searchTerm]) + + useEffect(() => { + if(!settingsSocket){ + return + } + + settingsSocket.emit('padLoad', searchParams) + + }, [settingsSocket, searchParams]); + + useEffect(() => { + if(!settingsSocket){ + return + } + + settingsSocket.on('results:padLoad', (data: PadSearchResult)=>{ + useStore.getState().setPads(data); + }) + + + settingsSocket.on('results:deletePad', (padID: string)=>{ + const newPads = useStore.getState().pads?.results?.filter((pad)=>{ + return pad.padName !== padID + }) + useStore.getState().setPads({ + total: useStore.getState().pads!.total-1, + results: newPads + }) + }) + + settingsSocket.on('results:cleanupPadRevisions', (data)=>{ + let newPads = useStore.getState().pads?.results ?? [] + + if (data.error) { + setErrorText(data.error) + return + } + + newPads.forEach((pad)=>{ + if (pad.padName === data.padId) { + pad.revisionNumber = data.keepRevisions + } + }) + + useStore.getState().setPads({ + results: newPads, + total: useStore.getState().pads!.total + }) + }) + }, [settingsSocket, pads]); + + const deletePad = (padID: string)=>{ + settingsSocket?.emit('deletePad', padID) + } + + const cleanupPad = (padID: string)=>{ + settingsSocket?.emit('cleanupPadRevisions', padID) + } + + + return
+ + + +
+
+
+ {t("ep_admin_pads:ep_adminpads2_confirm", { + padID: padToDelete, + })} +
+
+ + +
+
+
+
+
+ + + + +
+
Error occured: {errorText}
+
+ +
+
+
+
+
+

+ setSearchTerm(v.target.value)} placeholder={t('ep_admin_pads:ep_adminpads2_search-heading')}/> + + + + + + + + + + + + { + pads?.results?.map((pad)=>{ + return + + + + + + + }) + } + +
{ + setSearchParams({ + ...searchParams, + sortBy: 'padName', + ascending: !searchParams.ascending + }) + }}>{ + setSearchParams({ + ...searchParams, + sortBy: 'userCount', + ascending: !searchParams.ascending + }) + }}>{ + setSearchParams({ + ...searchParams, + sortBy: 'lastEdited', + ascending: !searchParams.ascending + }) + }}>{ + setSearchParams({ + ...searchParams, + sortBy: 'revisionNumber', + ascending: !searchParams.ascending + }) + }}>Revision number
{pad.padName}{pad.userCount}{new Date(pad.lastEdited).toLocaleString()}{pad.revisionNumber} +
+ } title={} onClick={()=>{ + setPadToDelete(pad.padName) + setDeleteDialog(true) + }}/> + } title={} onClick={()=>{ + cleanupPad(pad.padName) + }}/> + } title="view" onClick={()=>window.open(`/p/${pad.padName}`, '_blank')}/> +
+
+
+ + {currentPage+1} out of {pages} + +
+
+} diff --git a/admin/src/pages/Plugin.ts b/admin/src/pages/Plugin.ts new file mode 100644 index 000000000..f5563863b --- /dev/null +++ b/admin/src/pages/Plugin.ts @@ -0,0 +1,36 @@ +export type PluginDef = { + name: string, + description: string, + version: string, + time: string, + official: boolean, +} + + +export type InstalledPlugin = { + name: string, + path: string, + realPath: string, + version:string, + updatable?: boolean +} + + +export type SearchParams = { + searchTerm: string, + offset: number, + limit: number, + sortBy: 'name'|'version'|'last-updated', + sortDir: 'asc'|'desc' +} + + +export type HelpObj = { + epVersion: string + gitCommit: string + installedClientHooks: Record>, + installedParts: string[], + installedPlugins: string[], + installedServerHooks: Record, + latestVersion: string +} diff --git a/admin/src/pages/SettingsPage.tsx b/admin/src/pages/SettingsPage.tsx new file mode 100644 index 000000000..f781f67e1 --- /dev/null +++ b/admin/src/pages/SettingsPage.tsx @@ -0,0 +1,50 @@ +import {useStore} from "../store/store.ts"; +import {isJSONClean, cleanComments} from "../utils/utils.ts"; +import {Trans} from "react-i18next"; +import {IconButton} from "../components/IconButton.tsx"; +import {RotateCw, Save} from "lucide-react"; + +export const SettingsPage = ()=>{ + const settingsSocket = useStore(state=>state.settingsSocket) + const settings = cleanComments(useStore(state=>state.settings)) + + return
+

+ "; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; + + // Support: IE <=9 only + // IE <=9 replaces "; + support.option = !!div.lastChild; + } )(); + + +// We have to close these tags to support XHTML (trac-13200) + var wrapMap = { + + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting or other required elements. + thead: [ 1, "", "
" ], + col: [ 2, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + _default: [ 0, "", "" ] + }; + + wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; + wrapMap.th = wrapMap.td; + +// Support: IE <=9 only + if ( !support.option ) { + wrapMap.optgroup = wrapMap.option = [ 1, "" ]; + } + + + function getAll( context, tag ) { + + // Support: IE <=9 - 11 only + // Use typeof to avoid zero-argument method invocation on host objects (trac-15151) + var ret; + + if ( typeof context.getElementsByTagName !== "undefined" ) { + ret = context.getElementsByTagName( tag || "*" ); + + } else if ( typeof context.querySelectorAll !== "undefined" ) { + ret = context.querySelectorAll( tag || "*" ); + + } else { + ret = []; + } + + if ( tag === undefined || tag && nodeName( context, tag ) ) { + return jQuery.merge( [ context ], ret ); + } + + return ret; + } + + +// Mark scripts as having already been evaluated + function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } + } + + + var rhtml = /<|&#?\w+;/; + + function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, attached, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( toType( elem ) === "object" ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (trac-12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + attached = isAttached( elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( attached ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; + } + + + var rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + + function returnTrue() { + return true; + } + + function returnFalse() { + return false; + } + + function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); + } + + /* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ + jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Only attach events to objects that accept data + if ( !acceptData( elem ) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Ensure that invalid selectors throw exceptions at attach time + // Evaluate against documentElement in case elem is a non-element node (e.g., document) + if ( selector ) { + jQuery.find.matchesSelector( documentElement, selector ); + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = Object.create( null ); + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { + + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( nativeEvent ) { + + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( nativeEvent ), + + handlers = ( + dataPriv.get( this, "events" ) || Object.create( null ) + )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + + for ( i = 1; i < arguments.length; i++ ) { + args[ i ] = arguments[ i ]; + } + + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { + + // If the event is namespaced, then each handler is only invoked if it is + // specially universal or its namespaces are a superset of the event's. + if ( !event.rnamespace || handleObj.namespace === false || + event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, handleObj, sel, matchedHandlers, matchedSelectors, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + if ( delegateCount && + + // Support: IE <=9 + // Black-hole SVG instance trees (trac-13180) + cur.nodeType && + + // Support: Firefox <=42 + // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) + // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click + // Support: IE 11 only + // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) + !( event.type === "click" && event.button >= 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (trac-13208) + // Don't process clicks on disabled elements (trac-6911, trac-8165, trac-11382, trac-11764) + if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { + matchedHandlers = []; + matchedSelectors = {}; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (trac-13203) + sel = handleObj.selector + " "; + + if ( matchedSelectors[ sel ] === undefined ) { + matchedSelectors[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matchedSelectors[ sel ] ) { + matchedHandlers.push( handleObj ); + } + } + if ( matchedHandlers.length ) { + handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + cur = this; + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, + + get: isFunction( hook ) ? + function() { + if ( this.originalEvent ) { + return hook( this.originalEvent ); + } + } : + function() { + if ( this.originalEvent ) { + return this.originalEvent[ name ]; + } + }, + + set: function( value ) { + Object.defineProperty( this, name, { + enumerable: true, + configurable: true, + writable: true, + value: value + } ); + } + } ); + }, + + fix: function( originalEvent ) { + return originalEvent[ jQuery.expando ] ? + originalEvent : + new jQuery.Event( originalEvent ); + }, + + special: { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + click: { + + // Utilize native event to ensure correct state for checkable inputs + setup: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Claim the first handler + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + // dataPriv.set( el, "click", ... ) + leverageNative( el, "click", true ); + } + + // Return false to allow normal processing in the caller + return false; + }, + trigger: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Force setup before triggering a click + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + leverageNative( el, "click" ); + } + + // Return non-false to allow normal event-path propagation + return true; + }, + + // For cross-browser consistency, suppress native .click() on links + // Also prevent it if we're currently inside a leveraged native-event stack + _default: function( event ) { + var target = event.target; + return rcheckableType.test( target.type ) && + target.click && nodeName( target, "input" ) && + dataPriv.get( target, "click" ) || + nodeName( target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + } + }; + +// Ensure the presence of an event listener that handles manually-triggered +// synthetic events by interrupting progress until reinvoked in response to +// *native* events that it fires directly, ensuring that state changes have +// already occurred before other listeners are invoked. + function leverageNative( el, type, isSetup ) { + + // Missing `isSetup` indicates a trigger call, which must force setup through jQuery.event.add + if ( !isSetup ) { + if ( dataPriv.get( el, type ) === undefined ) { + jQuery.event.add( el, type, returnTrue ); + } + return; + } + + // Register the controller as a special universal handler for all event namespaces + dataPriv.set( el, type, false ); + jQuery.event.add( el, type, { + namespace: false, + handler: function( event ) { + var result, + saved = dataPriv.get( this, type ); + + if ( ( event.isTrigger & 1 ) && this[ type ] ) { + + // Interrupt processing of the outer synthetic .trigger()ed event + if ( !saved ) { + + // Store arguments for use when handling the inner native event + // There will always be at least one argument (an event object), so this array + // will not be confused with a leftover capture object. + saved = slice.call( arguments ); + dataPriv.set( this, type, saved ); + + // Trigger the native event and capture its result + this[ type ](); + result = dataPriv.get( this, type ); + dataPriv.set( this, type, false ); + + if ( saved !== result ) { + + // Cancel the outer synthetic event + event.stopImmediatePropagation(); + event.preventDefault(); + + return result; + } + + // If this is an inner synthetic event for an event with a bubbling surrogate + // (focus or blur), assume that the surrogate already propagated from triggering + // the native event and prevent that from happening again here. + // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the + // bubbling surrogate propagates *after* the non-bubbling base), but that seems + // less bad than duplication. + } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { + event.stopPropagation(); + } + + // If this is a native event triggered above, everything is now in order + // Fire an inner synthetic event with the original arguments + } else if ( saved ) { + + // ...and capture the result + dataPriv.set( this, type, jQuery.event.trigger( + saved[ 0 ], + saved.slice( 1 ), + this + ) ); + + // Abort handling of the native event by all jQuery handlers while allowing + // native handlers on the same element to run. On target, this is achieved + // by stopping immediate propagation just on the jQuery event. However, + // the native event is re-wrapped by a jQuery one on each level of the + // propagation so the only way to stop it for jQuery is to stop it for + // everyone via native `stopPropagation()`. This is not a problem for + // focus/blur which don't bubble, but it does also stop click on checkboxes + // and radios. We accept this limitation. + event.stopPropagation(); + event.isImmediatePropagationStopped = returnTrue; + } + } + } ); + } + + jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } + }; + + jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + + // Support: Android <=2.3 only + src.returnValue === false ? + returnTrue : + returnFalse; + + // Create target properties + // Support: Safari <=6 - 7 only + // Target should not be a text node (trac-504, trac-13143) + this.target = ( src.target && src.target.nodeType === 3 ) ? + src.target.parentNode : + src.target; + + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || Date.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; + }; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html + jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + isSimulated: false, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && !this.isSimulated ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } + }; + +// Includes all common event props including KeyEvent and MouseEvent specific props + jQuery.each( { + altKey: true, + bubbles: true, + cancelable: true, + changedTouches: true, + ctrlKey: true, + detail: true, + eventPhase: true, + metaKey: true, + pageX: true, + pageY: true, + shiftKey: true, + view: true, + "char": true, + code: true, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + which: true + }, jQuery.event.addProp ); + + jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { + + function focusMappedHandler( nativeEvent ) { + if ( document.documentMode ) { + + // Support: IE 11+ + // Attach a single focusin/focusout handler on the document while someone wants + // focus/blur. This is because the former are synchronous in IE while the latter + // are async. In other browsers, all those handlers are invoked synchronously. + + // `handle` from private data would already wrap the event, but we need + // to change the `type` here. + var handle = dataPriv.get( this, "handle" ), + event = jQuery.event.fix( nativeEvent ); + event.type = nativeEvent.type === "focusin" ? "focus" : "blur"; + event.isSimulated = true; + + // First, handle focusin/focusout + handle( nativeEvent ); + + // ...then, handle focus/blur + // + // focus/blur don't bubble while focusin/focusout do; simulate the former by only + // invoking the handler at the lower level. + if ( event.target === event.currentTarget ) { + + // The setup part calls `leverageNative`, which, in turn, calls + // `jQuery.event.add`, so event handle will already have been set + // by this point. + handle( event ); + } + } else { + + // For non-IE browsers, attach a single capturing handler on the document + // while someone wants focusin/focusout. + jQuery.event.simulate( delegateType, nativeEvent.target, + jQuery.event.fix( nativeEvent ) ); + } + } + + jQuery.event.special[ type ] = { + + // Utilize native event if possible so blur/focus sequence is correct + setup: function() { + + var attaches; + + // Claim the first handler + // dataPriv.set( this, "focus", ... ) + // dataPriv.set( this, "blur", ... ) + leverageNative( this, type, true ); + + if ( document.documentMode ) { + + // Support: IE 9 - 11+ + // We use the same native handler for focusin & focus (and focusout & blur) + // so we need to coordinate setup & teardown parts between those events. + // Use `delegateType` as the key as `type` is already used by `leverageNative`. + attaches = dataPriv.get( this, delegateType ); + if ( !attaches ) { + this.addEventListener( delegateType, focusMappedHandler ); + } + dataPriv.set( this, delegateType, ( attaches || 0 ) + 1 ); + } else { + + // Return false to allow normal processing in the caller + return false; + } + }, + trigger: function() { + + // Force setup before trigger + leverageNative( this, type ); + + // Return non-false to allow normal event-path propagation + return true; + }, + + teardown: function() { + var attaches; + + if ( document.documentMode ) { + attaches = dataPriv.get( this, delegateType ) - 1; + if ( !attaches ) { + this.removeEventListener( delegateType, focusMappedHandler ); + dataPriv.remove( this, delegateType ); + } else { + dataPriv.set( this, delegateType, attaches ); + } + } else { + + // Return false to indicate standard teardown should be applied + return false; + } + }, + + // Suppress native focus or blur if we're currently inside + // a leveraged native-event stack + _default: function( event ) { + return dataPriv.get( event.target, type ); + }, + + delegateType: delegateType + }; + + // Support: Firefox <=44 + // Firefox doesn't have focus(in | out) events + // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 + // + // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 + // focus(in | out) events fire after focus & blur events, + // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order + // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 + // + // Support: IE 9 - 11+ + // To preserve relative focusin/focus & focusout/blur event order guaranteed on the 3.x branch, + // attach a single handler for both events in IE. + jQuery.event.special[ delegateType ] = { + setup: function() { + + // Handle: regular nodes (via `this.ownerDocument`), window + // (via `this.document`) & document (via `this`). + var doc = this.ownerDocument || this.document || this, + dataHolder = document.documentMode ? this : doc, + attaches = dataPriv.get( dataHolder, delegateType ); + + // Support: IE 9 - 11+ + // We use the same native handler for focusin & focus (and focusout & blur) + // so we need to coordinate setup & teardown parts between those events. + // Use `delegateType` as the key as `type` is already used by `leverageNative`. + if ( !attaches ) { + if ( document.documentMode ) { + this.addEventListener( delegateType, focusMappedHandler ); + } else { + doc.addEventListener( type, focusMappedHandler, true ); + } + } + dataPriv.set( dataHolder, delegateType, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this.document || this, + dataHolder = document.documentMode ? this : doc, + attaches = dataPriv.get( dataHolder, delegateType ) - 1; + + if ( !attaches ) { + if ( document.documentMode ) { + this.removeEventListener( delegateType, focusMappedHandler ); + } else { + doc.removeEventListener( type, focusMappedHandler, true ); + } + dataPriv.remove( dataHolder, delegateType ); + } else { + dataPriv.set( dataHolder, delegateType, attaches ); + } + } + }; + } ); + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). + jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" + }, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; + } ); + + jQuery.fn.extend( { + + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + } + } ); + + + var + + // Support: IE <=10 - 11, Edge 12 - 13 only + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /\s*$/g; + +// Prefer a tbody over its parent table for containing new rows + function manipulationTarget( elem, content ) { + if ( nodeName( elem, "table" ) && + nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { + + return jQuery( elem ).children( "tbody" )[ 0 ] || elem; + } + + return elem; + } + +// Replace/restore the type attribute of script elements for safe DOM manipulation + function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; + } + function restoreScript( elem ) { + if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { + elem.type = elem.type.slice( 5 ); + } else { + elem.removeAttribute( "type" ); + } + + return elem; + } + + function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.get( src ); + events = pdataOld.events; + + if ( events ) { + dataPriv.remove( dest, "handle events" ); + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } + } + +// Fix IE bugs, see support tests + function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } + } + + function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = flat( args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + valueIsFunction = isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( valueIsFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( valueIsFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (trac-8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Re-enable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl && !node.noModule ) { + jQuery._evalUrl( node.src, { + nonce: node.nonce || node.getAttribute( "nonce" ) + }, doc ); + } + } else { + + // Unwrap a CDATA section containing script contents. This shouldn't be + // needed as in XML documents they're already not visible when + // inspecting element contents and in HTML documents they have no + // meaning but we're preserving that logic for backwards compatibility. + // This will be removed completely in 4.0. See gh-4904. + DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); + } + } + } + } + } + } + + return collection; + } + + function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && isAttached( node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; + } + + jQuery.extend( { + htmlPrefilter: function( html ) { + return html; + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = isAttached( elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew jQuery#find here for performance reasons: + // https://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } + } ); + + jQuery.fn.extend( { + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + } ); + }, + + before: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + } ); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch ( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } + } ); + + jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" + }, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: Android <=4.0 only, PhantomJS 1 only + // .get() because push.apply(_, arraylike) throws on ancient WebKit + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; + } ); + var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + + var rcustomProp = /^--/; + + + var getStyles = function( elem ) { + + // Support: IE <=11 only, Firefox <=30 (trac-15098, trac-14150) + // IE throws on elements created in popups + // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" + var view = elem.ownerDocument.defaultView; + + if ( !view || !view.opener ) { + view = window; + } + + return view.getComputedStyle( elem ); + }; + + var swap = function( elem, options, callback ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; + }; + + + var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); + + + + ( function() { + + // Executing both pixelPosition & boxSizingReliable tests require only one layout + // so they're executed at the same time to save the second computation. + function computeStyleTests() { + + // This is a singleton, we need to execute it only once + if ( !div ) { + return; + } + + container.style.cssText = "position:absolute;left:-11111px;width:60px;" + + "margin-top:1px;padding:0;border:0"; + div.style.cssText = + "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + + "margin:auto;border:1px;padding:1px;" + + "width:60%;top:1%"; + documentElement.appendChild( container ).appendChild( div ); + + var divStyle = window.getComputedStyle( div ); + pixelPositionVal = divStyle.top !== "1%"; + + // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 + reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; + + // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 + // Some styles come back with percentage values, even though they shouldn't + div.style.right = "60%"; + pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; + + // Support: IE 9 - 11 only + // Detect misreporting of content dimensions for box-sizing:border-box elements + boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; + + // Support: IE 9 only + // Detect overflow:scroll screwiness (gh-3699) + // Support: Chrome <=64 + // Don't get tricked when zoom affects offsetWidth (gh-4029) + div.style.position = "absolute"; + scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; + + documentElement.removeChild( container ); + + // Nullify the div so it wouldn't be stored in the memory and + // it will also be a sign that checks already performed + div = null; + } + + function roundPixelMeasures( measure ) { + return Math.round( parseFloat( measure ) ); + } + + var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, + reliableTrDimensionsVal, reliableMarginLeftVal, + container = document.createElement( "div" ), + div = document.createElement( "div" ); + + // Finish early in limited (non-browser) environments + if ( !div.style ) { + return; + } + + // Support: IE <=9 - 11 only + // Style of cloned element affects source element cloned (trac-8908) + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + jQuery.extend( support, { + boxSizingReliable: function() { + computeStyleTests(); + return boxSizingReliableVal; + }, + pixelBoxStyles: function() { + computeStyleTests(); + return pixelBoxStylesVal; + }, + pixelPosition: function() { + computeStyleTests(); + return pixelPositionVal; + }, + reliableMarginLeft: function() { + computeStyleTests(); + return reliableMarginLeftVal; + }, + scrollboxSize: function() { + computeStyleTests(); + return scrollboxSizeVal; + }, + + // Support: IE 9 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Behavior in IE 9 is more subtle than in newer versions & it passes + // some versions of this test; make sure not to make it pass there! + // + // Support: Firefox 70+ + // Only Firefox includes border widths + // in computed dimensions. (gh-4529) + reliableTrDimensions: function() { + var table, tr, trChild, trStyle; + if ( reliableTrDimensionsVal == null ) { + table = document.createElement( "table" ); + tr = document.createElement( "tr" ); + trChild = document.createElement( "div" ); + + table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate"; + tr.style.cssText = "box-sizing:content-box;border:1px solid"; + + // Support: Chrome 86+ + // Height set through cssText does not get applied. + // Computed height then comes back as 0. + tr.style.height = "1px"; + trChild.style.height = "9px"; + + // Support: Android 8 Chrome 86+ + // In our bodyBackground.html iframe, + // display for all div elements is set to "inline", + // which causes a problem only in Android 8 Chrome 86. + // Ensuring the div is `display: block` + // gets around this issue. + trChild.style.display = "block"; + + documentElement + .appendChild( table ) + .appendChild( tr ) + .appendChild( trChild ); + + trStyle = window.getComputedStyle( tr ); + reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) + + parseInt( trStyle.borderTopWidth, 10 ) + + parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight; + + documentElement.removeChild( table ); + } + return reliableTrDimensionsVal; + } + } ); + } )(); + + + function curCSS( elem, name, computed ) { + var width, minWidth, maxWidth, ret, + isCustomProp = rcustomProp.test( name ), + + // Support: Firefox 51+ + // Retrieving style before computed somehow + // fixes an issue with getting wrong values + // on detached elements + style = elem.style; + + computed = computed || getStyles( elem ); + + // getPropertyValue is needed for: + // .css('filter') (IE 9 only, trac-12537) + // .css('--customProperty) (gh-3144) + if ( computed ) { + + // Support: IE <=9 - 11+ + // IE only supports `"float"` in `getPropertyValue`; in computed styles + // it's only available as `"cssFloat"`. We no longer modify properties + // sent to `.css()` apart from camelCasing, so we need to check both. + // Normally, this would create difference in behavior: if + // `getPropertyValue` returns an empty string, the value returned + // by `.css()` would be `undefined`. This is usually the case for + // disconnected elements. However, in IE even disconnected elements + // with no styles return `"none"` for `getPropertyValue( "float" )` + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( isCustomProp && ret ) { + + // Support: Firefox 105+, Chrome <=105+ + // Spec requires trimming whitespace for custom properties (gh-4926). + // Firefox only trims leading whitespace. Chrome just collapses + // both leading & trailing whitespace to a single space. + // + // Fall back to `undefined` if empty string returned. + // This collapses a missing definition with property defined + // and set to an empty string but there's no standard API + // allowing us to differentiate them without a performance penalty + // and returning `undefined` aligns with older jQuery. + // + // rtrimCSS treats U+000D CARRIAGE RETURN and U+000C FORM FEED + // as whitespace while CSS does not, but this is not a problem + // because CSS preprocessing replaces them with U+000A LINE FEED + // (which *is* CSS whitespace) + // https://www.w3.org/TR/css-syntax-3/#input-preprocessing + ret = ret.replace( rtrimCSS, "$1" ) || undefined; + } + + if ( ret === "" && !isAttached( elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Android Browser returns percentage for some values, + // but width seems to be reliably pixels. + // This is against the CSSOM draft spec: + // https://drafts.csswg.org/cssom/#resolved-values + if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret !== undefined ? + + // Support: IE <=9 - 11 only + // IE returns zIndex value as an integer. + ret + "" : + ret; + } + + + function addGetHookIf( conditionFn, hookFn ) { + + // Define the hook, we'll check on the first run if it's really needed. + return { + get: function() { + if ( conditionFn() ) { + + // Hook not needed (or it's not possible to use it due + // to missing dependency), remove it. + delete this.get; + return; + } + + // Hook needed; redefine it so that the support test is not executed again. + return ( this.get = hookFn ).apply( this, arguments ); + } + }; + } + + + var cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style, + vendorProps = {}; + +// Return a vendor-prefixed property or undefined + function vendorPropName( name ) { + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } + } + +// Return a potentially-mapped jQuery.cssProps or vendor prefixed property + function finalPropName( name ) { + var final = jQuery.cssProps[ name ] || vendorProps[ name ]; + + if ( final ) { + return final; + } + if ( name in emptyStyle ) { + return name; + } + return vendorProps[ name ] = vendorPropName( name ) || name; + } + + + var + + // Swappable if display is none or starts with table + // except "table", "table-cell", or "table-caption" + // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }; + + function setPositiveNumber( _elem, value, subtract ) { + + // Any relative (+/-) values have already been + // normalized at this point + var matches = rcssNum.exec( value ); + return matches ? + + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : + value; + } + + function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { + var i = dimension === "width" ? 1 : 0, + extra = 0, + delta = 0, + marginDelta = 0; + + // Adjustment may not be necessary + if ( box === ( isBorderBox ? "border" : "content" ) ) { + return 0; + } + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin + // Count margin delta separately to only add it after scroll gutter adjustment. + // This is needed to make negative margins work with `outerHeight( true )` (gh-3982). + if ( box === "margin" ) { + marginDelta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); + } + + // If we get here with a content-box, we're seeking "padding" or "border" or "margin" + if ( !isBorderBox ) { + + // Add padding + delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // For "border" or "margin", add border + if ( box !== "padding" ) { + delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + + // But still keep track of it otherwise + } else { + extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + + // If we get here with a border-box (content + padding + border), we're seeking "content" or + // "padding" or "margin" + } else { + + // For "content", subtract padding + if ( box === "content" ) { + delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // For "content" or "padding", subtract border + if ( box !== "margin" ) { + delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + // Account for positive content-box scroll gutter when requested by providing computedVal + if ( !isBorderBox && computedVal >= 0 ) { + + // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border + // Assuming integer scroll gutter, subtract the rest and round down + delta += Math.max( 0, Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + computedVal - + delta - + extra - + 0.5 + + // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter + // Use an explicit zero to avoid NaN (gh-3964) + ) ) || 0; + } + + return delta + marginDelta; + } + + function getWidthOrHeight( elem, dimension, extra ) { + + // Start with computed style + var styles = getStyles( elem ), + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). + // Fake content-box until we know it's needed to know the true value. + boxSizingNeeded = !support.boxSizingReliable() || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + valueIsBorderBox = isBorderBox, + + val = curCSS( elem, dimension, styles ), + offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); + + // Support: Firefox <=54 + // Return a confounding non-pixel value or feign ignorance, as appropriate. + if ( rnumnonpx.test( val ) ) { + if ( !extra ) { + return val; + } + val = "auto"; + } + + + // Support: IE 9 - 11 only + // Use offsetWidth/offsetHeight for when box sizing is unreliable. + // In those cases, the computed value can be trusted to be border-box. + if ( ( !support.boxSizingReliable() && isBorderBox || + + // Support: IE 10 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Interestingly, in some cases IE 9 doesn't suffer from this issue. + !support.reliableTrDimensions() && nodeName( elem, "tr" ) || + + // Fall back to offsetWidth/offsetHeight when value is "auto" + // This happens for inline elements with no explicit setting (gh-3571) + val === "auto" || + + // Support: Android <=4.1 - 4.3 only + // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) + !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && + + // Make sure the element is visible & connected + elem.getClientRects().length ) { + + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // Where available, offsetWidth/offsetHeight approximate border box dimensions. + // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the + // retrieved value as a content box dimension. + valueIsBorderBox = offsetProp in elem; + if ( valueIsBorderBox ) { + val = elem[ offsetProp ]; + } + } + + // Normalize "" and auto + val = parseFloat( val ) || 0; + + // Adjust for the element's box model + return ( val + + boxModelAdjustment( + elem, + dimension, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles, + + // Provide the current computed size to request scroll gutter calculation (gh-3589) + val + ) + ) + "px"; + } + + jQuery.extend( { + + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + animationIterationCount: true, + aspectRatio: true, + borderImageSlice: true, + columnCount: true, + flexGrow: true, + flexShrink: true, + fontWeight: true, + gridArea: true, + gridColumn: true, + gridColumnEnd: true, + gridColumnStart: true, + gridRow: true, + gridRowEnd: true, + gridRowStart: true, + lineHeight: true, + opacity: true, + order: true, + orphans: true, + scale: true, + widows: true, + zIndex: true, + zoom: true, + + // SVG-related + fillOpacity: true, + floodOpacity: true, + stopOpacity: true, + strokeMiterlimit: true, + strokeOpacity: true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: {}, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ), + style = elem.style; + + // Make sure that we're working with the right name. We don't + // want to query the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (trac-7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug trac-9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (trac-7116) + if ( value == null || value !== value ) { + return; + } + + // If a number was passed in, add the unit (except for certain CSS properties) + // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append + // "px" to a few hardcoded values. + if ( type === "number" && !isCustomProp ) { + value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); + } + + // background-* props affect original clone's values + if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !( "set" in hooks ) || + ( value = hooks.set( elem, value, extra ) ) !== undefined ) { + + if ( isCustomProp ) { + style.setProperty( name, value ); + } else { + style[ name ] = value; + } + } + + } else { + + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && + ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { + + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ); + + // Make sure that we're working with the right name. We don't + // want to modify the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Try prefixed name followed by the unprefixed name + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + // Convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Make numeric if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || isFinite( num ) ? num || 0 : val; + } + + return val; + } + } ); + + jQuery.each( [ "height", "width" ], function( _i, dimension ) { + jQuery.cssHooks[ dimension ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + + // Certain elements can have dimension info if we invisibly show them + // but it must have a current display style that would benefit + return rdisplayswap.test( jQuery.css( elem, "display" ) ) && + + // Support: Safari 8+ + // Table columns in Safari have non-zero offsetWidth & zero + // getBoundingClientRect().width unless display is changed. + // Support: IE <=11 only + // Running getBoundingClientRect on a disconnected node + // in IE throws an error. + ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, dimension, extra ); + } ) : + getWidthOrHeight( elem, dimension, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = getStyles( elem ), + + // Only read styles.position if the test has a chance to fail + // to avoid forcing a reflow. + scrollboxSizeBuggy = !support.scrollboxSize() && + styles.position === "absolute", + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) + boxSizingNeeded = scrollboxSizeBuggy || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + subtract = extra ? + boxModelAdjustment( + elem, + dimension, + extra, + isBorderBox, + styles + ) : + 0; + + // Account for unreliable border-box dimensions by comparing offset* to computed and + // faking a content-box to get border and padding (gh-3699) + if ( isBorderBox && scrollboxSizeBuggy ) { + subtract -= Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + parseFloat( styles[ dimension ] ) - + boxModelAdjustment( elem, dimension, "border", false, styles ) - + 0.5 + ); + } + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ dimension ] = value; + value = jQuery.css( elem, dimension ); + } + + return setPositiveNumber( elem, value, subtract ); + } + }; + } ); + + jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, + function( elem, computed ) { + if ( computed ) { + return ( parseFloat( curCSS( elem, "marginLeft" ) ) || + elem.getBoundingClientRect().left - + swap( elem, { marginLeft: 0 }, function() { + return elem.getBoundingClientRect().left; + } ) + ) + "px"; + } + } + ); + +// These hooks are used by animate to expand properties + jQuery.each( { + margin: "", + padding: "", + border: "Width" + }, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i = 0, + expanded = {}, + + // Assumes a single number if not a string + parts = typeof value === "string" ? value.split( " " ) : [ value ]; + + for ( ; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( prefix !== "margin" ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } + } ); + + jQuery.fn.extend( { + css: function( name, value ) { + return access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( Array.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + } + } ); + + + function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); + } + jQuery.Tween = Tween; + + Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || jQuery.easing._default; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } + }; + + Tween.prototype.init.prototype = Tween.prototype; + + Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + // Use a property on the element directly when it is not a DOM element, + // or when there is no matching style property that exists. + if ( tween.elem.nodeType !== 1 || + tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { + return tween.elem[ tween.prop ]; + } + + // Passing an empty string as a 3rd parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails. + // Simple values such as "10px" are parsed to Float; + // complex values such as "rotate(1rad)" are returned as-is. + result = jQuery.css( tween.elem, tween.prop, "" ); + + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + + // Use step hook for back compat. + // Use cssHook if its there. + // Use .style if available and use plain properties where available. + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.nodeType === 1 && ( + jQuery.cssHooks[ tween.prop ] || + tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } + }; + +// Support: IE <=9 only +// Panic based approach to setting things on disconnected nodes + Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } + }; + + jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p * Math.PI ) / 2; + }, + _default: "swing" + }; + + jQuery.fx = Tween.prototype.init; + +// Back compat <1.8 extension point + jQuery.fx.step = {}; + + + + + var + fxNow, inProgress, + rfxtypes = /^(?:toggle|show|hide)$/, + rrun = /queueHooks$/; + + function schedule() { + if ( inProgress ) { + if ( document.hidden === false && window.requestAnimationFrame ) { + window.requestAnimationFrame( schedule ); + } else { + window.setTimeout( schedule, jQuery.fx.interval ); + } + + jQuery.fx.tick(); + } + } + +// Animations created synchronously will run synchronously + function createFxNow() { + window.setTimeout( function() { + fxNow = undefined; + } ); + return ( fxNow = Date.now() ); + } + +// Generate parameters to create a standard animation + function genFx( type, includeWidth ) { + var which, + i = 0, + attrs = { height: type }; + + // If we include width, step value is 1 to do all cssExpand values, + // otherwise step value is 2 to skip over Left and Right + includeWidth = includeWidth ? 1 : 0; + for ( ; i < 4; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; + } + + function createTween( value, prop, animation ) { + var tween, + collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { + + // We're done with this property + return tween; + } + } + } + + function defaultPrefilter( elem, props, opts ) { + var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, + isBox = "width" in props || "height" in props, + anim = this, + orig = {}, + style = elem.style, + hidden = elem.nodeType && isHiddenWithinTree( elem ), + dataShow = dataPriv.get( elem, "fxshow" ); + + // Queue-skipping animations hijack the fx hooks + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always( function() { + + // Ensure the complete handler is called before this completes + anim.always( function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + } ); + } ); + } + + // Detect show/hide animations + for ( prop in props ) { + value = props[ prop ]; + if ( rfxtypes.test( value ) ) { + delete props[ prop ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + + // Pretend to be hidden if this is a "show" and + // there is still data from a stopped show/hide + if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { + hidden = true; + + // Ignore all other no-op show/hide data + } else { + continue; + } + } + orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); + } + } + + // Bail out if this is a no-op like .hide().hide() + propTween = !jQuery.isEmptyObject( props ); + if ( !propTween && jQuery.isEmptyObject( orig ) ) { + return; + } + + // Restrict "overflow" and "display" styles during box animations + if ( isBox && elem.nodeType === 1 ) { + + // Support: IE <=9 - 11, Edge 12 - 15 + // Record all 3 overflow attributes because IE does not infer the shorthand + // from identically-valued overflowX and overflowY and Edge just mirrors + // the overflowX value there. + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Identify a display type, preferring old show/hide data over the CSS cascade + restoreDisplay = dataShow && dataShow.display; + if ( restoreDisplay == null ) { + restoreDisplay = dataPriv.get( elem, "display" ); + } + display = jQuery.css( elem, "display" ); + if ( display === "none" ) { + if ( restoreDisplay ) { + display = restoreDisplay; + } else { + + // Get nonempty value(s) by temporarily forcing visibility + showHide( [ elem ], true ); + restoreDisplay = elem.style.display || restoreDisplay; + display = jQuery.css( elem, "display" ); + showHide( [ elem ] ); + } + } + + // Animate inline elements as inline-block + if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { + if ( jQuery.css( elem, "float" ) === "none" ) { + + // Restore the original display value at the end of pure show/hide animations + if ( !propTween ) { + anim.done( function() { + style.display = restoreDisplay; + } ); + if ( restoreDisplay == null ) { + display = style.display; + restoreDisplay = display === "none" ? "" : display; + } + } + style.display = "inline-block"; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + anim.always( function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + } ); + } + + // Implement show/hide animations + propTween = false; + for ( prop in orig ) { + + // General show/hide setup for this element animation + if ( !propTween ) { + if ( dataShow ) { + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + } else { + dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); + } + + // Store hidden/visible for toggle so `.stop().toggle()` "reverses" + if ( toggle ) { + dataShow.hidden = !hidden; + } + + // Show elements before animating them + if ( hidden ) { + showHide( [ elem ], true ); + } + + /* eslint-disable no-loop-func */ + + anim.done( function() { + + /* eslint-enable no-loop-func */ + + // The final step of a "hide" animation is actually hiding the element + if ( !hidden ) { + showHide( [ elem ] ); + } + dataPriv.remove( elem, "fxshow" ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + } ); + } + + // Per-property setup + propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = propTween.start; + if ( hidden ) { + propTween.end = propTween.start; + propTween.start = 0; + } + } + } + } + + function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( Array.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } + } + + function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + // Support: Android 2.3 only + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (trac-12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + // If there's more to do, yield + if ( percent < 1 && length ) { + return remaining; + } + + // If this was an empty animation, synthesize a final progress notification + if ( !length ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + } + + // Resolve the animation and report its conclusion + deferred.resolveWith( elem, [ animation ] ); + return false; + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( isFunction( result.stop ) ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + result.stop.bind( result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + // Attach callbacks from options + animation + .progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); + + jQuery.fx.timer( + jQuery.extend( tick, { + elem: elem, + anim: animation, + queue: animation.opts.queue + } ) + ); + + return animation; + } + + jQuery.Animation = jQuery.extend( Animation, { + + tweeners: { + "*": [ function( prop, value ) { + var tween = this.createTween( prop, value ); + adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); + return tween; + } ] + }, + + tweener: function( props, callback ) { + if ( isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.match( rnothtmlwhite ); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length; index++ ) { + prop = props[ index ]; + Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; + Animation.tweeners[ prop ].unshift( callback ); + } + }, + + prefilters: [ defaultPrefilter ], + + prefilter: function( callback, prepend ) { + if ( prepend ) { + Animation.prefilters.unshift( callback ); + } else { + Animation.prefilters.push( callback ); + } + } + } ); + + jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !isFunction( easing ) && easing + }; + + // Go to the end state if fx are off + if ( jQuery.fx.off ) { + opt.duration = 0; + + } else { + if ( typeof opt.duration !== "number" ) { + if ( opt.duration in jQuery.fx.speeds ) { + opt.duration = jQuery.fx.speeds[ opt.duration ]; + + } else { + opt.duration = jQuery.fx.speeds._default; + } + } + } + + // Normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; + }; + + jQuery.fn.extend( { + fadeTo: function( speed, to, easing, callback ) { + + // Show any hidden elements after setting opacity to 0 + return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() + + // Animate to the value specified + .end().animate( { opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations, or finishing resolves immediately + if ( empty || dataPriv.get( this, "finish" ) ) { + anim.stop( true ); + } + }; + + doAnimation.finish = doAnimation; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue ) { + this.queue( type || "fx", [] ); + } + + return this.each( function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = dataPriv.get( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && + ( type == null || timers[ index ].queue === type ) ) { + + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // Start the next in the queue if the last step wasn't forced. + // Timers currently will call their complete callbacks, which + // will dequeue but only if they were gotoEnd. + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + } ); + }, + finish: function( type ) { + if ( type !== false ) { + type = type || "fx"; + } + return this.each( function() { + var index, + data = dataPriv.get( this ), + queue = data[ type + "queue" ], + hooks = data[ type + "queueHooks" ], + timers = jQuery.timers, + length = queue ? queue.length : 0; + + // Enable finishing flag on private data + data.finish = true; + + // Empty the queue first + jQuery.queue( this, type, [] ); + + if ( hooks && hooks.stop ) { + hooks.stop.call( this, true ); + } + + // Look for any active animations, and finish them + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && timers[ index ].queue === type ) { + timers[ index ].anim.stop( true ); + timers.splice( index, 1 ); + } + } + + // Look for any animations in the old queue and finish them + for ( index = 0; index < length; index++ ) { + if ( queue[ index ] && queue[ index ].finish ) { + queue[ index ].finish.call( this ); + } + } + + // Turn off finishing flag + delete data.finish; + } ); + } + } ); + + jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; + } ); + +// Generate shortcuts for custom animations + jQuery.each( { + slideDown: genFx( "show" ), + slideUp: genFx( "hide" ), + slideToggle: genFx( "toggle" ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } + }, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; + } ); + + jQuery.timers = []; + jQuery.fx.tick = function() { + var timer, + i = 0, + timers = jQuery.timers; + + fxNow = Date.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Run the timer and safely remove it when done (allowing for external removal) + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; + }; + + jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + jQuery.fx.start(); + }; + + jQuery.fx.interval = 13; + jQuery.fx.start = function() { + if ( inProgress ) { + return; + } + + inProgress = true; + schedule(); + }; + + jQuery.fx.stop = function() { + inProgress = null; + }; + + jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 + }; + + +// Based off of the plugin by Clint Helfers, with permission. + jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); + }; + + + ( function() { + var input = document.createElement( "input" ), + select = document.createElement( "select" ), + opt = select.appendChild( document.createElement( "option" ) ); + + input.type = "checkbox"; + + // Support: Android <=4.3 only + // Default value for a checkbox should be "on" + support.checkOn = input.value !== ""; + + // Support: IE <=11 only + // Must access selectedIndex to make default options select + support.optSelected = opt.selected; + + // Support: IE <=11 only + // An input loses its value after becoming a radio + input = document.createElement( "input" ); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; + } )(); + + + var boolHook, + attrHandle = jQuery.expr.attrHandle; + + jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } + } ); + + jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // Attribute hooks are determined by the lowercase version + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + hooks = jQuery.attrHooks[ name.toLowerCase() ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); + } + + if ( value !== undefined ) { + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value + "" ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !support.radioValue && value === "radio" && + nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + removeAttr: function( elem, value ) { + var name, + i = 0, + + // Attribute names can contain non-HTML whitespace characters + // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 + attrNames = value && value.match( rnothtmlwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + elem.removeAttribute( name ); + } + } + } + } ); + +// Hooks for boolean attributes + boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } + }; + + jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { + var getter = attrHandle[ name ] || jQuery.find.attr; + + attrHandle[ name ] = function( elem, name, isXML ) { + var ret, handle, + lowercaseName = name.toLowerCase(); + + if ( !isXML ) { + + // Avoid an infinite loop by temporarily removing this function from the getter + handle = attrHandle[ lowercaseName ]; + attrHandle[ lowercaseName ] = ret; + ret = getter( elem, name, isXML ) != null ? + lowercaseName : + null; + attrHandle[ lowercaseName ] = handle; + } + return ret; + }; + } ); + + + + + var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + + jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } + } ); + + jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // Support: IE <=9 - 11 only + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // Use proper attribute retrieval (trac-12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + if ( tabindex ) { + return parseInt( tabindex, 10 ); + } + + if ( + rfocusable.test( elem.nodeName ) || + rclickable.test( elem.nodeName ) && + elem.href + ) { + return 0; + } + + return -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } + } ); + +// Support: IE <=11 only +// Accessing the selectedIndex property +// forces the browser to respect setting selected +// on the option +// The getter ensures a default option is selected +// when in an optgroup +// eslint rule "no-unused-expressions" is disabled for this code +// since it considers such accessions noop + if ( !support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + }, + set: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + }; + } + + jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" + ], function() { + jQuery.propFix[ this.toLowerCase() ] = this; + } ); + + + + + // Strip and collapse whitespace according to HTML spec + // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace + function stripAndCollapse( value ) { + var tokens = value.match( rnothtmlwhite ) || []; + return tokens.join( " " ); + } + + + function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; + } + + function classesToArray( value ) { + if ( Array.isArray( value ) ) { + return value; + } + if ( typeof value === "string" ) { + return value.match( rnothtmlwhite ) || []; + } + return []; + } + + jQuery.fn.extend( { + addClass: function( value ) { + var classNames, cur, curValue, className, i, finalValue; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + classNames = classesToArray( value ); + + if ( classNames.length ) { + return this.each( function() { + curValue = getClass( this ); + cur = this.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + if ( cur.indexOf( " " + className + " " ) < 0 ) { + cur += className + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + this.setAttribute( "class", finalValue ); + } + } + } ); + } + + return this; + }, + + removeClass: function( value ) { + var classNames, cur, curValue, className, i, finalValue; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + classNames = classesToArray( value ); + + if ( classNames.length ) { + return this.each( function() { + curValue = getClass( this ); + + // This expression is here for better compressibility (see addClass) + cur = this.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + + // Remove *all* instances + while ( cur.indexOf( " " + className + " " ) > -1 ) { + cur = cur.replace( " " + className + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + this.setAttribute( "class", finalValue ); + } + } + } ); + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var classNames, className, i, self, + type = typeof value, + isValidValue = type === "string" || Array.isArray( value ); + + if ( isFunction( value ) ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + if ( typeof stateVal === "boolean" && isValidValue ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + classNames = classesToArray( value ); + + return this.each( function() { + if ( isValidValue ) { + + // Toggle individual class names + self = jQuery( this ); + + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( value === undefined || type === "boolean" ) { + className = getClass( this ); + if ( className ) { + + // Store className if set + dataPriv.set( this, "__className__", className ); + } + + // If the element has a class name or if we're passed `false`, + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + if ( this.setAttribute ) { + this.setAttribute( "class", + className || value === false ? + "" : + dataPriv.get( this, "__className__" ) || "" + ); + } + } + } ); + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { + return true; + } + } + + return false; + } + } ); + + + + + var rreturn = /\r/g; + + jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, valueIsFunction, + elem = this[ 0 ]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || + jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && + "get" in hooks && + ( ret = hooks.get( elem, "value" ) ) !== undefined + ) { + return ret; + } + + ret = elem.value; + + // Handle most common string cases + if ( typeof ret === "string" ) { + return ret.replace( rreturn, "" ); + } + + // Handle cases where value is null/undef or number + return ret == null ? "" : ret; + } + + return; + } + + valueIsFunction = isFunction( value ); + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( valueIsFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( Array.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } + } ); + + jQuery.extend( { + valHooks: { + option: { + get: function( elem ) { + + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + + // Support: IE <=10 - 11 only + // option.text throws exceptions (trac-14686, trac-14858) + // Strip and collapse whitespace + // https://html.spec.whatwg.org/#strip-and-collapse-whitespace + stripAndCollapse( jQuery.text( elem ) ); + } + }, + select: { + get: function( elem ) { + var value, option, i, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one", + values = one ? null : [], + max = one ? index + 1 : options.length; + + if ( index < 0 ) { + i = max; + + } else { + i = one ? index : 0; + } + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Support: IE <=9 only + // IE8-9 doesn't update selected after form reset (trac-2551) + if ( ( option.selected || i === index ) && + + // Don't return options that are disabled or in a disabled optgroup + !option.disabled && + ( !option.parentNode.disabled || + !nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + + /* eslint-disable no-cond-assign */ + + if ( option.selected = + jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 + ) { + optionSet = true; + } + + /* eslint-enable no-cond-assign */ + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } + } ); + +// Radios and checkboxes getter/setter + jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( Array.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; + if ( !support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + }; + } + } ); + + + + +// Return jQuery for attributes-only inclusion + var location = window.location; + + var nonce = { guid: Date.now() }; + + var rquery = ( /\?/ ); + + + +// Cross-browser xml parsing + jQuery.parseXML = function( data ) { + var xml, parserErrorElem; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE 9 - 11 only + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) {} + + parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ]; + if ( !xml || parserErrorElem ) { + jQuery.error( "Invalid XML: " + ( + parserErrorElem ? + jQuery.map( parserErrorElem.childNodes, function( el ) { + return el.textContent; + } ).join( "\n" ) : + data + ) ); + } + return xml; + }; + + + var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + stopPropagationCallback = function( e ) { + e.stopPropagation(); + }; + + jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = lastElement = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "." ) > -1 ) { + + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (trac-9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (trac-9724) + if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + lastElement = cur; + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( ( !special._default || + special._default.apply( eventPath.pop(), data ) === false ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name as the event. + // Don't do default actions on window, that's where global variables be (trac-6170) + if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + + if ( event.isPropagationStopped() ) { + lastElement.addEventListener( type, stopPropagationCallback ); + } + + elem[ type ](); + + if ( event.isPropagationStopped() ) { + lastElement.removeEventListener( type, stopPropagationCallback ); + } + + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + // Piggyback on a donor event to simulate a different one + // Used only for `focus(in | out)` events + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true + } + ); + + jQuery.event.trigger( e, null, elem ); + } + + } ); + + jQuery.fn.extend( { + + trigger: function( type, data ) { + return this.each( function() { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler: function( type, data ) { + var elem = this[ 0 ]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } + } ); + + + var + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + + function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( Array.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && toType( obj ) === "object" ) { + + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + + // Serialize scalar item. + add( prefix, obj ); + } + } + +// Serialize an array of form elements or a set of +// key/values into a query string + jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, valueOrFunction ) { + + // If value is a function, invoke it and use its return value + var value = isFunction( valueOrFunction ) ? + valueOrFunction() : + valueOrFunction; + + s[ s.length ] = encodeURIComponent( key ) + "=" + + encodeURIComponent( value == null ? "" : value ); + }; + + if ( a == null ) { + return ""; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ); + }; + + jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ).filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ).map( function( _i, elem ) { + var val = jQuery( this ).val(); + + if ( val == null ) { + return null; + } + + if ( Array.isArray( val ) ) { + return jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ); + } + + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } + } ); + + + var + r20 = /%20/g, + rhash = /#.*$/, + rantiCache = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // trac-7653, trac-8125, trac-8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (trac-10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document.createElement( "a" ); + + originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport + function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; + + if ( isFunction( func ) ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; + } + +// Base inspection function for prefilters and transports + function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); + } + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes trac-9887 + function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; + } + + /* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ + function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } + } + + /* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ + function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; + } + + jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": JSON.parse, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // Request state (becomes false upon send and true upon completion) + completed, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // uncached part of the url + uncached, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( completed ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[ 1 ].toLowerCase() + " " ] = + ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) + .concat( match[ 2 ] ); + } + } + match = responseHeaders[ key.toLowerCase() + " " ]; + } + return match == null ? null : match.join( ", " ); + }, + + // Raw string + getAllResponseHeaders: function() { + return completed ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( completed == null ) { + name = requestHeadersNames[ name.toLowerCase() ] = + requestHeadersNames[ name.toLowerCase() ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( completed == null ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( completed ) { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } else { + + // Lazy-add the new callbacks in a way that preserves old ones + for ( code in map ) { + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ); + + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (trac-10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket trac-12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document.createElement( "a" ); + + // Support: IE <=8 - 11, Edge 12 - 15 + // IE throws exception on accessing the href property if url is malformed, + // e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE <=8 - 11 only + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( completed ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (trac-15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + // Remove hash to simplify url manipulation + cacheURL = s.url.replace( rhash, "" ); + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // Remember the hash so we can put it back + uncached = s.url.slice( cacheURL.length ); + + // If data is available and should be processed, append data to url + if ( s.data && ( s.processData || typeof s.data === "string" ) ) { + cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; + + // trac-9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add or update anti-cache param if needed + if ( s.cache === false ) { + cacheURL = cacheURL.replace( rantiCache, "$1" ); + uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + + uncached; + } + + // Put hash and anti-cache on the URL that will be requested (gh-1732) + s.url = cacheURL + uncached; + + // Change '%20' to '+' if this is encoded form body content (gh-2658) + } else if ( s.data && s.processData && + ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { + s.data = s.data.replace( r20, "+" ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); + } + if ( jQuery.etag[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? + s.accepts[ s.dataTypes[ 0 ] ] + + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && + ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { + + // Abort if not done already and return + return jqXHR.abort(); + } + + // Aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + completeDeferred.add( s.complete ); + jqXHR.done( s.success ); + jqXHR.fail( s.error ); + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + + // If request was aborted inside ajaxSend, stop there + if ( completed ) { + return jqXHR; + } + + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = window.setTimeout( function() { + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + completed = false; + transport.send( requestHeaders, done ); + } catch ( e ) { + + // Rethrow post-completion exceptions + if ( completed ) { + throw e; + } + + // Propagate others as results + done( -1, e ); + } + } + + // Callback for when everything is done + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Ignore repeat invocations + if ( completed ) { + return; + } + + completed = true; + + // Clear timeout if it exists + if ( timeoutTimer ) { + window.clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Determine if successful + isSuccess = status >= 200 && status < 300 || status === 304; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // Use a noop converter for missing script but not if jsonp + if ( !isSuccess && + jQuery.inArray( "script", s.dataTypes ) > -1 && + jQuery.inArray( "json", s.dataTypes ) < 0 ) { + s.converters[ "text script" ] = function() {}; + } + + // Convert no matter what (that way responseXXX fields are always set) + response = ajaxConvert( s, response, jqXHR, isSuccess ); + + // If successful, handle type chaining + if ( isSuccess ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + modified = jqXHR.getResponseHeader( "Last-Modified" ); + if ( modified ) { + jQuery.lastModified[ cacheURL ] = modified; + } + modified = jqXHR.getResponseHeader( "etag" ); + if ( modified ) { + jQuery.etag[ cacheURL ] = modified; + } + } + + // if no content + if ( status === 204 || s.type === "HEAD" ) { + statusText = "nocontent"; + + // if not modified + } else if ( status === 304 ) { + statusText = "notmodified"; + + // If we have data, let's convert it + } else { + statusText = response.state; + success = response.data; + error = response.error; + isSuccess = !error; + } + } else { + + // Extract error from statusText and normalize for non-aborts + error = statusText; + if ( status || !statusText ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + return jqXHR; + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + } + } ); + + jQuery.each( [ "get", "post" ], function( _i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + + // Shift arguments if data argument was omitted + if ( isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + // The url can be an options object (which then must have .url) + return jQuery.ajax( jQuery.extend( { + url: url, + type: method, + dataType: type, + data: data, + success: callback + }, jQuery.isPlainObject( url ) && url ) ); + }; + } ); + + jQuery.ajaxPrefilter( function( s ) { + var i; + for ( i in s.headers ) { + if ( i.toLowerCase() === "content-type" ) { + s.contentType = s.headers[ i ] || ""; + } + } + } ); + + + jQuery._evalUrl = function( url, options, doc ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (trac-11264) + type: "GET", + dataType: "script", + cache: true, + async: false, + global: false, + + // Only evaluate the response if it is successful (gh-4126) + // dataFilter is not invoked for failure responses, so using it instead + // of the default converter is kludgy but it works. + converters: { + "text script": function() {} + }, + dataFilter: function( response ) { + jQuery.globalEval( response, options, doc ); + } + } ); + }; + + + jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( this[ 0 ] ) { + if ( isFunction( html ) ) { + html = html.call( this[ 0 ] ); + } + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map( function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + } ).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( isFunction( html ) ) { + return this.each( function( i ) { + jQuery( this ).wrapInner( html.call( this, i ) ); + } ); + } + + return this.each( function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + } ); + }, + + wrap: function( html ) { + var htmlIsFunction = isFunction( html ); + + return this.each( function( i ) { + jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function( selector ) { + this.parent( selector ).not( "body" ).each( function() { + jQuery( this ).replaceWith( this.childNodes ); + } ); + return this; + } + } ); + + + jQuery.expr.pseudos.hidden = function( elem ) { + return !jQuery.expr.pseudos.visible( elem ); + }; + jQuery.expr.pseudos.visible = function( elem ) { + return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); + }; + + + + + jQuery.ajaxSettings.xhr = function() { + try { + return new window.XMLHttpRequest(); + } catch ( e ) {} + }; + + var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200, + + // Support: IE <=9 only + // trac-1450: sometimes IE returns 1223 when it should be 204 + 1223: 204 + }, + xhrSupported = jQuery.ajaxSettings.xhr(); + + support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); + support.ajax = xhrSupported = !!xhrSupported; + + jQuery.ajaxTransport( function( options ) { + var callback, errorCallback; + + // Cross domain only allowed if supported through XMLHttpRequest + if ( support.cors || xhrSupported && !options.crossDomain ) { + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = errorCallback = xhr.onload = + xhr.onerror = xhr.onabort = xhr.ontimeout = + xhr.onreadystatechange = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + + // Support: IE <=9 only + // On a manual native abort, IE9 throws + // errors on any property access that is not readyState + if ( typeof xhr.status !== "number" ) { + complete( 0, "error" ); + } else { + complete( + + // File: protocol always yields status 0; see trac-8605, trac-14207 + xhr.status, + xhr.statusText + ); + } + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // Support: IE <=9 only + // IE9 has no XHR2 but throws on binary (trac-11426) + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) !== "text" || + typeof xhr.responseText !== "string" ? + { binary: xhr.response } : + { text: xhr.responseText }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); + + // Support: IE 9 only + // Use onreadystatechange to replace onabort + // to handle uncaught aborts + if ( xhr.onabort !== undefined ) { + xhr.onabort = errorCallback; + } else { + xhr.onreadystatechange = function() { + + // Check readyState before timeout as it changes + if ( xhr.readyState === 4 ) { + + // Allow onerror to be called first, + // but that will not handle a native abort + // Also, save errorCallback to a variable + // as xhr.onerror cannot be accessed + window.setTimeout( function() { + if ( callback ) { + errorCallback(); + } + } ); + } + }; + } + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // trac-14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } + } ); + + + + +// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) + jQuery.ajaxPrefilter( function( s ) { + if ( s.crossDomain ) { + s.contents.script = false; + } + } ); + +// Install script dataType + jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /\b(?:java|ecma)script\b/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } + } ); + +// Handle cache's special case and crossDomain + jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + } + } ); + +// Bind script tag hack transport + jQuery.ajaxTransport( "script", function( s ) { + + // This transport only deals with cross domain or forced-by-attrs requests + if ( s.crossDomain || s.scriptAttrs ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( " + + + +<%- body %> + + diff --git a/src/templates/index.html b/src/templates/index.html index 4f6d500b9..f7d1a2c62 100644 --- a/src/templates/index.html +++ b/src/templates/index.html @@ -1,41 +1,13 @@ -<% - var settings = require("ep_etherpad-lite/node/utils/Settings"); -%> <%=settings.title%> - - - + + + - - + - - - + <% e.begin_block("indexCustomStyles"); %> + + <% e.end_block(); %>
<% e.begin_block("indexWrapper"); %>
-
-
-
- - -
+ <% if (!settings.requireSession) { %> + <% if (settings.editOnly) { %> + + <% } else {%> + + + <% } %> +
+ + +
+ <% } %>
<% e.end_block(); %>
+ - - + <% e.begin_block("indexCustomScripts"); %> + + <% e.end_block(); %> + diff --git a/src/templates/indexBootstrap.js b/src/templates/indexBootstrap.js new file mode 100644 index 000000000..faf6702e6 --- /dev/null +++ b/src/templates/indexBootstrap.js @@ -0,0 +1,6 @@ + +(async () => { + window.$ = window.jQuery = require('ep_etherpad-lite/static/js/rjquery').jQuery; + require('ep_etherpad-lite/static/js/l10n') + require('ep_etherpad-lite/static/js/index') +})() diff --git a/src/templates/javascript.html b/src/templates/javascript.html new file mode 100644 index 000000000..d93692b09 --- /dev/null +++ b/src/templates/javascript.html @@ -0,0 +1,51 @@ + + + + JavaScript license information + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
jquery-3.0.1.min.jsExpatjquery.js
html10n.jsExpathtml10n.js
l10n.jsApache-2.0-onlyl10n.js
socket.io.jsExpatsocket.io.js
require-kernel.jsExpatrequire-kernel.js
Apache-2.0-only
Expat
Apache-2.0-only
Expat
+ + diff --git a/src/templates/pad.html b/src/templates/pad.html index 1d8c069a5..6dd9a0ef8 100644 --- a/src/templates/pad.html +++ b/src/templates/pad.html @@ -1,465 +1,450 @@ <% var settings = require("ep_etherpad-lite/node/utils/Settings") , langs = require("ep_etherpad-lite/node/hooks/i18n").availableLangs + , pluginUtils = require('ep_etherpad-lite/static/js/pluginfw/shared') + ; %> -<% e.begin_block("htmlHead"); %> - -<% e.end_block(); %> + + + <% e.begin_block("htmlHead"); %> + <% e.end_block(); %> + <%=settings.title%> + + - |@licend The above is the entire license notice - for the JavaScript code in this page.| - */ - + + + + + - - - - + <% e.begin_block("styles"); %> + - <% e.begin_block("styles"); %> - - - - <% e.end_block(); %> + <% e.begin_block("customStyles"); %> + + <% e.end_block(); %> - - - + + <% e.end_block(); %> - + + + + <% e.begin_block("body"); %> - <% e.begin_block("body"); %> -
-
-
-
- - + + + +
+
+ + + + +
+ + <% e.begin_block("afterEditbar"); %><% e.end_block(); %> + +
+ + <% e.begin_block("editorContainerBox"); %> + + + + + +
+ +
+ <% e.begin_block("permissionDenied"); %> +
+

+ You do not have permission to access this pad +

+ <% e.end_block(); %> + <% e.begin_block("loading"); %> +

+
+ Loading... +

+ <% e.end_block(); %> + +
-
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + -
-
-
-
-

You need a password to access this pad

-
- -
-
-
-

You do not have permission to access this pad

-
-
-

Your password was wrong

-
-

Loading...

- -
-
- + + + - - - - - - -
+
0
- -
- loading.. +
+
+

+ + █   +
+
+
- +
+
+
+
+ + + + + <% if (settings.skinName == 'colibris') { %> + + <% } %> - <% e.begin_block("scripts"); %> - - - - + <% e.end_block(); %> - - - +
- + <% e.end_block(); %> - - - plugins.baseURL = baseURL; - plugins.update(function () { - hooks.plugins = plugins; - - // Call documentReady hook - $(function() { - hooks.aCallAll('documentReady'); - }); - - var pad = require('ep_etherpad-lite/static/js/pad'); - pad.baseURL = baseURL; - pad.init(); - }); - - /* TODO: These globals shouldn't exist. */ - pad = require('ep_etherpad-lite/static/js/pad').pad; - chat = require('ep_etherpad-lite/static/js/chat').chat; - padeditbar = require('ep_etherpad-lite/static/js/pad_editbar').padeditbar; - padimpexp = require('ep_etherpad-lite/static/js/pad_impexp').padimpexp; - }()); - - <% e.end_block(); %> + <% e.begin_block("customScripts"); %> + + <% e.end_block(); %> + + <% e.end_block(); %> + diff --git a/src/templates/padBootstrap.js b/src/templates/padBootstrap.js new file mode 100644 index 000000000..caa3692a0 --- /dev/null +++ b/src/templates/padBootstrap.js @@ -0,0 +1,45 @@ + +(async () => { + + require('ep_etherpad-lite/static/js/l10n') + + window.clientVars = { + // This is needed to fetch /pluginfw/plugin-definitions.json, which happens before the server + // sends the CLIENT_VARS message. + randomVersionString: <%-JSON.stringify(settings.randomVersionString)%>, + }; + + // Allow other frames to access this frame's modules. + //window.require.resolveTmp = require.resolve('ep_etherpad-lite/static/js/pad_cookie'); + + const basePath = new URL('..', window.location.href).pathname; + window.$ = window.jQuery = require('ep_etherpad-lite/static/js/rjquery').jQuery; + window.browser = require('ep_etherpad-lite/static/js/vendors/browser'); + const pad = require('ep_etherpad-lite/static/js/pad'); + pad.baseURL = basePath; + window.plugins = require('ep_etherpad-lite/static/js/pluginfw/client_plugins'); + const hooks = require('ep_etherpad-lite/static/js/pluginfw/hooks'); + + // TODO: These globals shouldn't exist. + window.pad = pad.pad; + window.chat = require('ep_etherpad-lite/static/js/chat').chat; + window.padeditbar = require('ep_etherpad-lite/static/js/pad_editbar').padeditbar; + window.padimpexp = require('ep_etherpad-lite/static/js/pad_impexp').padimpexp; + require('ep_etherpad-lite/static/js/skin_variants'); + require('ep_etherpad-lite/static/js/basic_error_handler') + + window.plugins.baseURL = basePath; + await window.plugins.update(new Map([ + <% for (const module of pluginModules) { %> + [<%- JSON.stringify(module) %>, require("../../src/plugin_packages/"+<%- JSON.stringify(module) %>)], + <% } %> +])); + // Mechanism for tests to register hook functions (install fake plugins). + window._postPluginUpdateForTestingDone = false; + if (window._postPluginUpdateForTesting != null) window._postPluginUpdateForTesting(); + window._postPluginUpdateForTestingDone = true; + window.pluginDefs = require('ep_etherpad-lite/static/js/pluginfw/plugin_defs'); + pad.init(); + await new Promise((resolve) => $(resolve)); + await hooks.aCallAll('documentReady'); +})(); diff --git a/src/templates/padViteBootstrap.js b/src/templates/padViteBootstrap.js new file mode 100644 index 000000000..05f759077 --- /dev/null +++ b/src/templates/padViteBootstrap.js @@ -0,0 +1,41 @@ +window.$ = window.jQuery = await import('../../src/static/js/rjquery').jQuery; +await import('../../src/static/js/l10n') + +window.clientVars = { + // This is needed to fetch /pluginfw/plugin-definitions.json, which happens before the server + // sends the CLIENT_VARS message. + randomVersionString: "7a7bdbad", +}; + +(async () => { + // Allow other frames to access this frame's modules. + //window.require.resolveTmp = require.resolve('ep_etherpad-lite/static/js/pad_cookie'); + + const basePath = new URL('..', window.location.href).pathname; + window.browser = require('../../src/static/js/vendors/browser'); + const pad = require('../../src/static/js/pad'); + pad.baseURL = basePath; + window.plugins = require('../../src/static/js/pluginfw/client_plugins'); + const hooks = require('../../src/static/js/pluginfw/hooks'); + + // TODO: These globals shouldn't exist. + window.pad = pad.pad; + window.chat = require('../../src/static/js/chat').chat; + window.padeditbar = require('../../src/static/js/pad_editbar').padeditbar; + window.padimpexp = require('../../src/static/js/pad_impexp').padimpexp; + require('../../src/static/js/skin_variants'); + require('../../src/static/js/basic_error_handler') + + window.plugins.baseURL = basePath; + await window.plugins.update(new Map([ + + ])); + // Mechanism for tests to register hook functions (install fake plugins). + window._postPluginUpdateForTestingDone = false; + if (window._postPluginUpdateForTesting != null) window._postPluginUpdateForTesting(); + window._postPluginUpdateForTestingDone = true; + window.pluginDefs = require('../../src/static/js/pluginfw/plugin_defs'); + pad.init(); + await new Promise((resolve) => $(resolve)); + await hooks.aCallAll('documentReady'); +})(); diff --git a/src/templates/timeSliderBootstrap.js b/src/templates/timeSliderBootstrap.js new file mode 100644 index 000000000..e3138cfbd --- /dev/null +++ b/src/templates/timeSliderBootstrap.js @@ -0,0 +1,37 @@ +// @license magnet:?xt=urn:btih:8e4f440f4c65981c5bf93c76d35135ba5064d8b7&dn=apache-2.0.txt +window.clientVars = { + // This is needed to fetch /pluginfw/plugin-definitions.json, which happens before the + // server sends the CLIENT_VARS message. + randomVersionString: <%-JSON.stringify(settings.randomVersionString)%>, +}; +let BroadcastSlider; + + +(function () { + const timeSlider = require('ep_etherpad-lite/static/js/timeslider') + const pathComponents = location.pathname.split('/'); + + // Strip 'p', the padname and 'timeslider' from the pathname and set as baseURL + const baseURL = pathComponents.slice(0,pathComponents.length-3).join('/') + '/'; + require('ep_etherpad-lite/static/js/l10n') + window.$ = window.jQuery = require('ep_etherpad-lite/static/js/rjquery').jQuery; // Expose jQuery #HACK + require('ep_etherpad-lite/static/js/vendors/gritter') + + window.browser = require('ep_etherpad-lite/static/js/vendors/browser'); + + window.plugins = require('ep_etherpad-lite/static/js/pluginfw/client_plugins'); + const socket = timeSlider.socket; + BroadcastSlider = timeSlider.BroadcastSlider; + plugins.baseURL = baseURL; + plugins.update(function () { + + + /* TODO: These globals shouldn't exist. */ + + }); + const padeditbar = require('ep_etherpad-lite/static/js/pad_editbar').padeditbar; + const padimpexp = require('ep_etherpad-lite/static/js/pad_impexp').padimpexp; + timeSlider.baseURL = baseURL; + timeSlider.init(); + padeditbar.init() +})(); diff --git a/src/templates/timeslider.html b/src/templates/timeslider.html index d3062449f..02db40648 100644 --- a/src/templates/timeslider.html +++ b/src/templates/timeslider.html @@ -3,235 +3,258 @@ , langs = require("ep_etherpad-lite/node/hooks/i18n").availableLangs %> - -<%=settings.title%> Timeslider - + + <%=settings.title%> Timeslider + + - + + + <% e.begin_block("timesliderStyles"); %> - - - + + + + + <% e.end_block(); %> <% e.begin_block("timesliderScripts"); %> - - <% e.end_block(); %> <% e.begin_block("timesliderBody"); %> -
-
- <% e.begin_block("timesliderTop"); %> -
- - -
-
- -
-
+ + + + +
+ <% e.begin_block("timesliderTop"); %> + + +
+ +
+

+ + +

+

+ + +

-
-
- <% e.begin_block("timesliderEditbarRight"); %> - - + - -
-

- - -

-

- - -

-
+
+
+ + +
+
+
+
+
+
+ +
+ + + + + + +
+
+ + + <% e.end_block(); %> +
+ + +
+ + + + + +
+
+
+
+ + + + + + + + + + + + + +
-
-
-
-
-
-
-
-
-
- + + + - -
+ +
+ - -
+ + + - - - - + - + <% e.end_block(); %> - + - diff --git a/src/tests/README.md b/src/tests/README.md new file mode 100644 index 000000000..6ab5dd23b --- /dev/null +++ b/src/tests/README.md @@ -0,0 +1,11 @@ +# About this folder: Tests + +Before running the tests, start an Etherpad instance on your machine. + +## Frontend + +To run the frontend tests, point your browser to `/tests/frontend` + +## Backend + +To run the backend tests, run `cd src` and then `npm test` diff --git a/src/tests/backend-new/easysync-helper.ts b/src/tests/backend-new/easysync-helper.ts new file mode 100644 index 000000000..1fc8dda95 --- /dev/null +++ b/src/tests/backend-new/easysync-helper.ts @@ -0,0 +1,220 @@ +import AttributePool from "../../static/js/AttributePool"; +import { Attribute } from "../../static/js/types/Attribute"; +import {StringAssembler} from "../../static/js/StringAssembler"; +import {SmartOpAssembler} from "../../static/js/SmartOpAssembler"; +import Op from "../../static/js/Op"; +import {numToString} from "../../static/js/ChangesetUtils"; +import {checkRep, pack} from "../../static/js/Changeset"; + +export const poolOrArray = (attribs: any) => { + if (attribs.getAttrib) { + return attribs; // it's already an attrib pool + } else { + // assume it's an array of attrib strings to be split and added + const p = new AttributePool(); + attribs.forEach((kv: { split: (arg0: string) => Attribute; }) => { + p.putAttrib(kv.split(',')); + }); + return p; + } +}; +const randInt = (maxValue: number) => Math.floor(Math.random() * maxValue); +const randomInlineString = (len: number) => { + const assem = new StringAssembler(); + for (let i = 0; i < len; i++) { + assem.append(String.fromCharCode(randInt(26) + 97)); + } + return assem.toString(); +}; +export const randomMultiline = (approxMaxLines: number, approxMaxCols: number) => { + const numParts = randInt(approxMaxLines * 2) + 1; + const txt = new StringAssembler(); + txt.append(randInt(2) ? '\n' : ''); + for (let i = 0; i < numParts; i++) { + if ((i % 2) === 0) { + if (randInt(10)) { + txt.append(randomInlineString(randInt(approxMaxCols) + 1)); + } else { + txt.append('\n'); + } + } else { + txt.append('\n'); + } + } + return txt.toString(); +}; + +const randomTwoPropAttribs = (opcode: "" | "=" | "+" | "-") => { + // assumes attrib pool like ['apple,','apple,true','banana,','banana,true'] + if (opcode === '-' || randInt(3)) { + return ''; + } else if (randInt(3)) { // eslint-disable-line no-dupe-else-if + if (opcode === '+' || randInt(2)) { + return `*${numToString(randInt(2) * 2 + 1)}`; + } else { + return `*${numToString(randInt(2) * 2)}`; + } + } else if (opcode === '+' || randInt(4) === 0) { + return '*1*3'; + } else { + return ['*0*2', '*0*3', '*1*2'][randInt(3)]; + } +}; + + +const randomStringOperation = (numCharsLeft: number) => { + let result; + switch (randInt(11)) { + case 0: + { + // insert char + result = { + insert: randomInlineString(1), + }; + break; + } + case 1: + { + // delete char + result = { + remove: 1, + }; + break; + } + case 2: + { + // skip char + result = { + skip: 1, + }; + break; + } + case 3: + { + // insert small + result = { + insert: randomInlineString(randInt(4) + 1), + }; + break; + } + case 4: + { + // delete small + result = { + remove: randInt(4) + 1, + }; + break; + } + case 5: + { + // skip small + result = { + skip: randInt(4) + 1, + }; + break; + } + case 6: + { + // insert multiline; + result = { + insert: randomMultiline(5, 20), + }; + break; + } + case 7: + { + // delete multiline + result = { + remove: Math.round(numCharsLeft * Math.random() * Math.random()), + }; + break; + } + case 8: + { + // skip multiline + result = { + skip: Math.round(numCharsLeft * Math.random() * Math.random()), + }; + break; + } + case 9: + { + // delete to end + result = { + remove: numCharsLeft, + }; + break; + } + case 10: + { + // skip to end + result = { + skip: numCharsLeft, + }; + break; + } + } + const maxOrig = numCharsLeft - 1; + if ('remove' in result!) { + result.remove = Math.min(result.remove, maxOrig); + } else if ('skip' in result!) { + result.skip = Math.min(result.skip, maxOrig); + } + return result; +}; + +export const randomTestChangeset = (origText: string, withAttribs?: any) => { + const charBank = new StringAssembler(); + let textLeft = origText; // always keep final newline + const outTextAssem = new StringAssembler(); + const opAssem = new SmartOpAssembler(); + const oldLen = origText.length; + + const nextOp = new Op(); + + const appendMultilineOp = (opcode: "" | "=" | "+" | "-", txt: string) => { + nextOp.opcode = opcode; + if (withAttribs) { + nextOp.attribs = randomTwoPropAttribs(opcode); + } + txt.replace(/\n|[^\n]+/g, (t) => { + if (t === '\n') { + nextOp.chars = 1; + nextOp.lines = 1; + opAssem.append(nextOp); + } else { + nextOp.chars = t.length; + nextOp.lines = 0; + opAssem.append(nextOp); + } + return ''; + }); + }; + + const doOp = () => { + const o = randomStringOperation(textLeft.length); + if (o!.insert) { + const txt = o!.insert; + charBank.append(txt); + outTextAssem.append(txt); + appendMultilineOp('+', txt); + } else if (o!.skip) { + const txt = textLeft.substring(0, o!.skip); + textLeft = textLeft.substring(o!.skip); + outTextAssem.append(txt); + appendMultilineOp('=', txt); + } else if (o!.remove) { + const txt = textLeft.substring(0, o!.remove); + textLeft = textLeft.substring(o!.remove); + appendMultilineOp('-', txt); + } + }; + + while (textLeft.length > 1) doOp(); + for (let i = 0; i < 5; i++) doOp(); // do some more (only insertions will happen) + const outText = `${outTextAssem.toString()}\n`; + opAssem.endDocument(); + const cs = pack(oldLen, outText.length, opAssem.toString(), charBank.toString()); + checkRep(cs); + return [cs, outText]; +}; diff --git a/src/tests/backend-new/specs/AttributeMap.ts b/src/tests/backend-new/specs/AttributeMap.ts new file mode 100644 index 000000000..ce5e61f74 --- /dev/null +++ b/src/tests/backend-new/specs/AttributeMap.ts @@ -0,0 +1,184 @@ +'use strict'; + +import AttributeMap from '../../../static/js/AttributeMap'; +import AttributePool from '../../../static/js/AttributePool'; +import attributes from '../../../static/js/attributes'; +import {expect, describe, it, beforeEach} from 'vitest' +import {Attribute} from "../../../static/js/types/Attribute"; + +describe('AttributeMap', function () { + const attribs: Attribute[] = [ + ['foo', 'bar'], + ['baz', 'bif'], + ['emptyValue', ''], + ]; + let pool: AttributePool; + + const getPoolSize = () => { + let n = 0; + pool.eachAttrib(() => ++n); + return n; + }; + + beforeEach(async function () { + pool = new AttributePool(); + for (let i = 0; i < attribs.length; ++i) expect(pool.putAttrib(attribs[i])).to.equal(i); + }); + + it('fromString works', async function () { + const got = AttributeMap.fromString('*0*1*2', pool); + for (const [k, v] of attribs) expect(got.get(k)).to.equal(v); + // Maps iterate in insertion order, so [...got] should be in the same order as attribs. + expect(JSON.stringify([...got])).to.equal(JSON.stringify(attribs)); + }); + + describe('set', function () { + it('stores the value', async function () { + const m = new AttributeMap(pool); + expect(m.size).to.equal(0); + m.set('k', 'v'); + expect(m.size).to.equal(1); + expect(m.get('k')).to.equal('v'); + }); + + it('reuses attributes in the pool', async function () { + expect(getPoolSize()).to.equal(attribs.length); + const m = new AttributeMap(pool); + const [k0, v0] = attribs[0]; + m.set(k0, v0); + expect(getPoolSize()).to.equal(attribs.length); + expect(m.size).to.equal(1); + expect(m.toString()).to.equal('*0'); + }); + + it('inserts new attributes into the pool', async function () { + const m = new AttributeMap(pool); + expect(getPoolSize()).to.equal(attribs.length); + m.set('k', 'v'); + expect(getPoolSize()).to.equal(attribs.length + 1); + expect(JSON.stringify(pool.getAttrib(attribs.length))).to.equal(JSON.stringify(['k', 'v'])); + }); + + describe('coerces key and value to string', function () { + const testCases = [ + ['object (with toString)', {toString: () => 'obj'}, 'obj'], + ['undefined', undefined, ''], + ['null', null, ''], + ['boolean', true, 'true'], + ['number', 1, '1'], + ]; + for (const [desc, input, want] of testCases) { + describe(desc as string, function () { + it('key is coerced to string', async function () { + const m = new AttributeMap(pool); + // @ts-ignore + m.set(input, 'value'); + expect(m.get(want)).to.equal('value'); + }); + + it('value is coerced to string', async function () { + const m = new AttributeMap(pool); + // @ts-ignore + m.set('key', input); + expect(m.get('key')).to.equal(want); + }); + }); + } + }); + + it('returns the map', async function () { + const m = new AttributeMap(pool); + expect(m.set('k', 'v')).to.equal(m); + }); + }); + + describe('toString', function () { + it('sorts attributes', async function () { + const m = new AttributeMap(pool).update(attribs); + const got = [...attributes.attribsFromString(m.toString(), pool)]; + const want = attributes.sort([...attribs]); + // Verify that attribs is not already sorted so that this test doesn't accidentally pass. + expect(JSON.stringify(want)).to.not.equal(JSON.stringify(attribs)); + expect(JSON.stringify(got)).to.equal(JSON.stringify(want)); + }); + + it('returns all entries', async function () { + const m = new AttributeMap(pool); + expect(m.toString()).to.equal(''); + m.set(...attribs[0]); + expect(m.toString()).to.equal('*0'); + m.delete(attribs[0][0]); + expect(m.toString()).to.equal(''); + m.set(...attribs[1]); + expect(m.toString()).to.equal('*1'); + m.set(attribs[1][0], 'new value'); + expect(m.toString()).to.equal(attributes.encodeAttribString([attribs.length])); + m.set(...attribs[2]); + expect(m.toString()).to.equal(attributes.attribsToString( + attributes.sort([attribs[2], [attribs[1][0], 'new value']]), pool)); + }); + }); + + for (const funcName of ['update', 'updateFromString']) { + const callUpdateFn = (m: any, ...args: (boolean | (string | null | undefined)[][])[]) => { + if (funcName === 'updateFromString') { + // @ts-ignore + args[0] = attributes.attribsToString(attributes.sort([...args[0]]), pool); + } + // @ts-ignore + return AttributeMap.prototype[funcName].call(m, ...args); + }; + + describe(funcName, function () { + it('works', async function () { + const m = new AttributeMap(pool); + m.set(attribs[2][0], 'value to be overwritten'); + callUpdateFn(m, attribs); + for (const [k, v] of attribs) expect(m.get(k)).to.equal(v); + expect(m.size).to.equal(attribs.length); + const wantStr = attributes.attribsToString(attributes.sort([...attribs]), pool); + expect(m.toString()).to.equal(wantStr); + callUpdateFn(m, []); + expect(m.toString()).to.equal(wantStr); + }); + + it('inserts new attributes into the pool', async function () { + const m = new AttributeMap(pool); + callUpdateFn(m, [['k', 'v']]); + expect(m.size).to.equal(1); + expect(m.get('k')).to.equal('v'); + expect(getPoolSize()).to.equal(attribs.length + 1); + expect(m.toString()).to.equal(attributes.encodeAttribString([attribs.length])); + }); + + it('returns the map', async function () { + const m = new AttributeMap(pool); + expect(callUpdateFn(m, [])).to.equal(m); + }); + + describe('emptyValueIsDelete=false inserts empty values', function () { + for (const emptyVal of ['', null, undefined]) { + it(emptyVal == null ? String(emptyVal) : JSON.stringify(emptyVal), async function () { + const m = new AttributeMap(pool); + m.set('k', 'v'); + callUpdateFn(m, [['k', emptyVal]]); + expect(m.size).to.equal(1); + expect(m.toString()).to.equal(attributes.attribsToString([['k', '']], pool)); + }); + } + }); + + describe('emptyValueIsDelete=true deletes entries', function () { + for (const emptyVal of ['', null, undefined]) { + it(emptyVal == null ? String(emptyVal) : JSON.stringify(emptyVal), async function () { + const m = new AttributeMap(pool); + m.set('k', 'v'); + callUpdateFn(m, [['k', emptyVal]], true); + expect(m.size).to.equal(0); + expect(m.toString()).to.equal(''); + }); + } + }); + }); + } +}); diff --git a/src/tests/backend-new/specs/StringIteratorTest.ts b/src/tests/backend-new/specs/StringIteratorTest.ts new file mode 100644 index 000000000..d88fa57aa --- /dev/null +++ b/src/tests/backend-new/specs/StringIteratorTest.ts @@ -0,0 +1,47 @@ +import {expect, describe, it} from 'vitest' +import {StringIterator} from "../../../static/js/StringIterator"; + + +describe('Test string iterator take', function () { + it('should iterate over a string', async function () { + const str = 'Hello, world!'; + const iter = new StringIterator(str); + let i = 0; + while (iter.remaining() > 0) { + expect(iter.remaining()).to.equal(str.length - i); + console.error(iter.remaining()); + expect(iter.take(1)).to.equal(str.charAt(i)); + i++; + } + }); +}) + + +describe('Test string iterator peek', function () { + it('should peek over a string', async function () { + const str = 'Hello, world!'; + const iter = new StringIterator(str); + let i = 0; + while (iter.remaining() > 0) { + expect(iter.remaining()).to.equal(str.length - i); + expect(iter.peek(1)).to.equal(str.charAt(i)); + i++; + iter.skip(1); + } + }); +}) + +describe('Test string iterator skip', function () { + it('should throw error when skip over a string too long', async function () { + const str = 'Hello, world!'; + const iter = new StringIterator(str); + expect(()=>iter.skip(1000)).toThrowError(); + }); + + it('should skip over a string', async function () { + const str = 'Hello, world!'; + const iter = new StringIterator(str); + iter.skip(7); + expect(iter.take(1)).to.equal('w'); + }); +}) diff --git a/src/tests/backend-new/specs/admin_utils.ts b/src/tests/backend-new/specs/admin_utils.ts new file mode 100644 index 000000000..b115a38a6 --- /dev/null +++ b/src/tests/backend-new/specs/admin_utils.ts @@ -0,0 +1,38 @@ +'use strict'; + + +import {strict as assert} from "assert"; +import {cleanComments, minify} from "admin/src/utils/utils"; +import {describe, it, expect, beforeAll} from "vitest"; +import fs from 'fs'; +const fsp = fs.promises; +let template:string; + +describe(__filename, function () { + beforeAll(async function () { + template = await fsp.readFile('../settings.json.template', 'utf8') + }); + describe('adminUtils', function () { + it('cleanComments function empty', async function () { + expect(cleanComments("")).to.equal(""); + }); + it('cleanComments function HelloWorld no comment', async function () { + expect(cleanComments("HelloWorld")).to.equal("HelloWorld"); + }); + it('cleanComments function HelloWorld with comment', async function () { + expect(cleanComments("Hello/*abc*/World/*def*/")).to.equal("HelloWorld"); + }); + it('cleanComments function HelloWorld with comment and multiline', async function () { + expect(cleanComments("Hello \n/*abc\nxyz*/World/*def*/")).to.equal("Hello\nWorld"); + }); + it('cleanComments function HelloWorld with multiple line breaks', async function () { + expect(cleanComments(" \nHello \n \n \nWorld/*def*/")).to.equal("Hello\nWorld"); + }); + it('cleanComments function same after minified', async function () { + expect(minify(cleanComments(template)!)).to.equal(minify(template)); + }); + it('minified results are smaller', async function () { + expect(minify(template).length < template.length).to.equal(true); + }); + }); +}); diff --git a/src/tests/backend-new/specs/attributes.ts b/src/tests/backend-new/specs/attributes.ts new file mode 100644 index 000000000..64a4464bd --- /dev/null +++ b/src/tests/backend-new/specs/attributes.ts @@ -0,0 +1,366 @@ +'use strict'; + +import {APool} from "../../../node/types/PadType"; + +import AttributePool from '../../../static/js/AttributePool'; +import attributes from '../../../static/js/attributes'; + +import {expect, describe, it, beforeEach} from 'vitest'; +import {Attribute} from "../../../static/js/types/Attribute"; + +describe('attributes', function () { + const attribs: Attribute[] = [['foo', 'bar'], ['baz', 'bif']]; + let pool: AttributePool; + + beforeEach(async function () { + pool = new AttributePool(); + for (let i = 0; i < attribs.length; ++i) expect(pool.putAttrib(attribs[i])).to.equal(i); + }); + + describe('decodeAttribString', function () { + it('is a generator function', async function () { + expect(attributes.decodeAttribString.constructor.name).to.equal('GeneratorFunction'); + }); + + describe('rejects invalid attribute strings', function () { + const testCases = ['x', '*0+1', '*A', '*0$', '*', '0', '*-1']; + for (const tc of testCases) { + it(JSON.stringify(tc), async function () { + expect(() => [...attributes.decodeAttribString(tc)]) + .toThrowError(/invalid character/); + }); + } + }); + + describe('accepts valid attribute strings', function () { + const testCases = [ + ['', []], + ['*0', [0]], + ['*a', [10]], + ['*z', [35]], + ['*10', [36]], + [ + '*0*1*2*3*4*5*6*7*8*9*a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*10', + [...Array(37).keys()], + ], + ]; + for (const [input, want] of testCases) { + it(`${JSON.stringify(input)} -> ${JSON.stringify(want)}`, async function () { + // @ts-ignore + const got = [...attributes.decodeAttribString(input)]; + expect(JSON.stringify(got)).to.equal(JSON.stringify(want)); + }); + } + }); + }); + + describe('encodeAttribString', function () { + describe('accepts any kind of iterable', function () { + const testCases = [ + ['generator', (function* () { yield 0; yield 1; })()], + ['list', [0, 1]], + ['set', new Set([0, 1])], + ]; + for (const [desc, input] of testCases) { + it(desc as string, async function () { + // @ts-ignore + expect(attributes.encodeAttribString(input)).to.equal('*0*1'); + }); + } + }); + + describe('rejects invalid inputs', function () { + const testCases = [ + [null, /.*/], // Different browsers may have different error messages. + [[-1], /is negative/], + [['0'], /not a number/], + [[null], /not a number/], + [[0.5], /not an integer/], + [[{}], /not a number/], + [[true], /not a number/], + ]; + for (const [input, wantErr] of testCases) { + it(JSON.stringify(input), async function () { + // @ts-ignore + expect(() => attributes.encodeAttribString(input)).toThrowError(wantErr as RegExp); + }); + } + }); + + describe('accepts valid inputs', function () { + const testCases = [ + [[], ''], + [[0], '*0'], + [[10], '*a'], + [[35], '*z'], + [[36], '*10'], + [ + [...Array(37).keys()], + '*0*1*2*3*4*5*6*7*8*9*a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*10', + ], + ]; + for (const [input, want] of testCases) { + it(`${JSON.stringify(input)} -> ${JSON.stringify(want)}`, async function () { + // @ts-ignore + expect(attributes.encodeAttribString(input)).to.equal(want); + }); + } + }); + }); + + describe('attribsFromNums', function () { + it('is a generator function', async function () { + expect(attributes.attribsFromNums.constructor.name).to.equal("GeneratorFunction"); + }); + + describe('accepts any kind of iterable', function () { + const testCases = [ + ['generator', (function* () { yield 0; yield 1; })()], + ['list', [0, 1]], + ['set', new Set([0, 1])], + ]; + + for (const [desc, input] of testCases) { + it(desc as string, async function () { + // @ts-ignore + const gotAttribs = [...attributes.attribsFromNums(input, pool)]; + expect(JSON.stringify(gotAttribs)).to.equal(JSON.stringify(attribs)); + }); + } + }); + + describe('rejects invalid inputs', function () { + const testCases = [ + [null, /.*/], // Different browsers may have different error messages. + [[-1], /is negative/], + [['0'], /not a number/], + [[null], /not a number/], + [[0.5], /not an integer/], + [[{}], /not a number/], + [[true], /not a number/], + [[9999], /does not exist in pool/], + ]; + for (const [input, wantErr] of testCases) { + it(JSON.stringify(input), async function () { + // @ts-ignore + expect(() => [...attributes.attribsFromNums(input, pool)]).toThrowError(wantErr as RegExp); + }); + } + }); + + describe('accepts valid inputs', function () { + const testCases = [ + [[], []], + [[0], [attribs[0]]], + [[1], [attribs[1]]], + [[0, 1], [attribs[0], attribs[1]]], + [[1, 0], [attribs[1], attribs[0]]], + ]; + for (const [input, want] of testCases) { + it(`${JSON.stringify(input)} -> ${JSON.stringify(want)}`, async function () { + // @ts-ignore + const gotAttribs = [...attributes.attribsFromNums(input, pool)]; + expect(JSON.stringify(gotAttribs)).to.equal(JSON.stringify(want)); + }); + } + }); + }); + + describe('attribsToNums', function () { + it('is a generator function', async function () { + expect(attributes.attribsToNums.constructor.name).to.equal("GeneratorFunction") + }); + + describe('accepts any kind of iterable', function () { + const testCases = [ + ['generator', (function* () { yield attribs[0]; yield attribs[1]; })()], + ['list', [attribs[0], attribs[1]]], + ['set', new Set([attribs[0], attribs[1]])], + ]; + + for (const [desc, input] of testCases) { + it(desc as string, async function () { + // @ts-ignore + const gotNums = [...attributes.attribsToNums(input, pool)]; + expect(JSON.stringify(gotNums)).to.equal(JSON.stringify([0, 1])); + }); + } + }); + + describe('rejects invalid inputs', function () { + const testCases = [null, [null]]; + for (const input of testCases) { + it(JSON.stringify(input), async function () { + // @ts-ignore + expect(() => [...attributes.attribsToNums(input, pool)]).toThrowError(); + }); + } + }); + + describe('reuses existing pool entries', function () { + const testCases = [ + [[], []], + [[attribs[0]], [0]], + [[attribs[1]], [1]], + [[attribs[0], attribs[1]], [0, 1]], + [[attribs[1], attribs[0]], [1, 0]], + ]; + for (const [input, want] of testCases) { + it(`${JSON.stringify(input)} -> ${JSON.stringify(want)}`, async function () { + // @ts-ignore + const got = [...attributes.attribsToNums(input, pool)]; + expect(JSON.stringify(got)).to.equal(JSON.stringify(want)); + }); + } + }); + + describe('inserts new attributes into the pool', function () { + const testCases = [ + [[['k', 'v']], [attribs.length]], + [[attribs[0], ['k', 'v']], [0, attribs.length]], + [[['k', 'v'], attribs[0]], [attribs.length, 0]], + ]; + for (const [input, want] of testCases) { + it(`${JSON.stringify(input)} -> ${JSON.stringify(want)}`, async function () { + // @ts-ignore + const got = [...attributes.attribsToNums(input, pool)]; + expect(JSON.stringify(got)).to.equal(JSON.stringify(want)); + expect(JSON.stringify(pool.getAttrib(attribs.length))) + .to.equal(JSON.stringify(['k', 'v'])); + }); + } + }); + + describe('coerces key and value to string', function () { + const testCases = [ + ['object (with toString)', {toString: () => 'obj'}, 'obj'], + ['undefined', undefined, ''], + ['null', null, ''], + ['boolean', true, 'true'], + ['number', 1, '1'], + ]; + for (const [desc, inputVal, wantVal] of testCases) { + describe(desc as string, function () { + for (const [desc, inputAttribs, wantAttribs] of [ + ['key is coerced to string', [[inputVal, 'value']], [[wantVal, 'value']]], + ['value is coerced to string', [['key', inputVal]], [['key', wantVal]]], + ]) { + it(desc as string, async function () { + // @ts-ignore + const gotNums = [...attributes.attribsToNums(inputAttribs, pool)]; + // Each attrib in inputAttribs is expected to be new to the pool. + const wantNums = [...Array(attribs.length + 1).keys()].slice(attribs.length); + expect(JSON.stringify(gotNums)).to.equal(JSON.stringify(wantNums)); + const gotAttribs = gotNums.map((n) => pool.getAttrib(n)); + expect(JSON.stringify(gotAttribs)).to.equal(JSON.stringify(wantAttribs)); + }); + } + }); + } + }); + }); + + describe('attribsFromString', function () { + it('is a generator function', async function () { + expect(attributes.attribsFromString.constructor.name).to.equal('GeneratorFunction'); + }); + + describe('rejects invalid attribute strings', function () { + const testCases = [ + ['x', /invalid character/], + ['*0+1', /invalid character/], + ['*A', /invalid character/], + ['*0$', /invalid character/], + ['*', /invalid character/], + ['0', /invalid character/], + ['*-1', /invalid character/], + ['*9999', /does not exist in pool/], + ]; + for (const [input, wantErr] of testCases) { + it(JSON.stringify(input), async function () { + // @ts-ignore + expect(() => [...attributes.attribsFromString(input, pool)]).toThrowError(wantErr); + }); + } + }); + + describe('accepts valid inputs', function () { + const testCases = [ + ['', []], + ['*0', [attribs[0]]], + ['*1', [attribs[1]]], + ['*0*1', [attribs[0], attribs[1]]], + ['*1*0', [attribs[1], attribs[0]]], + ]; + for (const [input, want] of testCases) { + it(`${JSON.stringify(input)} -> ${JSON.stringify(want)}`, async function () { + // @ts-ignore + const gotAttribs = [...attributes.attribsFromString(input, pool)]; + expect(JSON.stringify(gotAttribs)).to.equal(JSON.stringify(want)); + }); + } + }); + }); + + describe('attribsToString', function () { + describe('accepts any kind of iterable', function () { + const testCases = [ + ['generator', (function* () { yield attribs[0]; yield attribs[1]; })()], + ['list', [attribs[0], attribs[1]]], + ['set', new Set([attribs[0], attribs[1]])], + ]; + + for (const [desc, input] of testCases) { + it(desc as string, async function () { + // @ts-ignore + const got = attributes.attribsToString(input, pool); + expect(got).to.equal('*0*1'); + }); + } + }); + + describe('rejects invalid inputs', function () { + const testCases = [null, [null]]; + for (const input of testCases) { + it(JSON.stringify(input), async function () { + // @ts-ignore + expect(() => attributes.attribsToString(input, pool)).toThrowError(); + }); + } + }); + + describe('reuses existing pool entries', function () { + const testCases = [ + [[], ''], + [[attribs[0]], '*0'], + [[attribs[1]], '*1'], + [[attribs[0], attribs[1]], '*0*1'], + [[attribs[1], attribs[0]], '*1*0'], + ]; + for (const [input, want] of testCases) { + it(`${JSON.stringify(input)} -> ${JSON.stringify(want)}`, async function () { + // @ts-ignore + const got = attributes.attribsToString(input, pool); + expect(got).to.equal(want); + }); + } + }); + + describe('inserts new attributes into the pool', function () { + const testCases = [ + [[['k', 'v']], `*${attribs.length}`], + [[attribs[0], ['k', 'v']], `*0*${attribs.length}`], + [[['k', 'v'], attribs[0]], `*${attribs.length}*0`], + ]; + for (const [input, want] of testCases) { + it(`${JSON.stringify(input)} -> ${JSON.stringify(want)}`, async function () { + // @ts-ignore + const got = attributes.attribsToString(input, pool); + expect(got).to.equal(want); + expect(JSON.stringify(pool.getAttrib(attribs.length))) + .to.equal(JSON.stringify(['k', 'v'])); + }); + } + }); + }); +}); diff --git a/src/tests/backend-new/specs/easysync-assembler.ts b/src/tests/backend-new/specs/easysync-assembler.ts new file mode 100644 index 000000000..28cb2eb46 --- /dev/null +++ b/src/tests/backend-new/specs/easysync-assembler.ts @@ -0,0 +1,224 @@ +'use strict'; + +import {deserializeOps, opsFromAText} from '../../../static/js/Changeset'; +import padutils from '../../../static/js/pad_utils'; +import {poolOrArray} from '../easysync-helper.js'; + +import {describe, it, expect} from 'vitest' +import {OpAssembler} from "../../../static/js/OpAssembler"; +import {SmartOpAssembler} from "../../../static/js/SmartOpAssembler"; +import Op from "../../../static/js/Op"; + + +describe('easysync-assembler', function () { + it('opAssembler', async function () { + const x = '-c*3*4+6|3=az*asdf0*1*2*3+1=1-1+1*0+1=1-1+1|c=c-1'; + const assem = new OpAssembler(); + var opLength = 0 + for (const op of deserializeOps(x)){ + console.log(op) + assem.append(op); + opLength++ + } + expect(assem.toString()).to.equal(x); + }); + + it('smartOpAssembler', async function () { + const x = '-c*3*4+6|3=az*asdf0*1*2*3+1=1-1+1*0+1=1-1+1|c=c-1'; + const assem = new SmartOpAssembler(); + for (const op of deserializeOps(x)) assem.append(op); + assem.endDocument(); + expect(assem.toString()).to.equal(x); + }); + + it('smartOpAssembler ignore additional pure keeps (no attributes)', async function () { + const x = '-c*3*4+6|1+1=5'; + const assem = new SmartOpAssembler(); + for (const op of deserializeOps(x)) assem.append(op); + assem.endDocument(); + expect(assem.toString()).to.equal('-c*3*4+6|1+1'); + }); + + it('smartOpAssembler merge consecutive + ops without multiline', async function () { + const x = '-c*3*4+6*3*4+1*3*4+9=5'; + const assem = new SmartOpAssembler(); + for (const op of deserializeOps(x)) assem.append(op); + assem.endDocument(); + expect(assem.toString()).to.equal('-c*3*4+g'); + }); + + it('smartOpAssembler merge consecutive + ops with multiline', async function () { + const x = '-c*3*4+6*3*4|1+1*3*4|9+f*3*4+k=5'; + const assem = new SmartOpAssembler(); + for (const op of deserializeOps(x)) assem.append(op); + assem.endDocument(); + expect(assem.toString()).to.equal('-c*3*4|a+m*3*4+k'); + }); + + it('smartOpAssembler merge consecutive - ops without multiline', async function () { + const x = '-c-6-1-9=5'; + const assem = new SmartOpAssembler(); + for (const op of deserializeOps(x)) assem.append(op); + assem.endDocument(); + expect(assem.toString()).to.equal('-s'); + }); + + it('smartOpAssembler merge consecutive - ops with multiline', async function () { + const x = '-c-6|1-1|9-f-k=5'; + const assem = new SmartOpAssembler(); + for (const op of deserializeOps(x)) assem.append(op); + assem.endDocument(); + expect(assem.toString()).to.equal('|a-y-k'); + }); + + it('smartOpAssembler merge consecutive = ops without multiline', async function () { + const x = '-c*3*4=6*2*4=1*3*4=f*3*4=2*3*4=a=k=5'; + const assem = new SmartOpAssembler(); + for (const op of deserializeOps(x)) assem.append(op); + assem.endDocument(); + expect(assem.toString()).to.equal('-c*3*4=6*2*4=1*3*4=r'); + }); + + it('smartOpAssembler merge consecutive = ops with multiline', async function () { + const x = '-c*3*4=6*2*4|1=1*3*4|9=f*3*4|2=2*3*4=a*3*4=1=k=5'; + const assem = new SmartOpAssembler(); + for (const op of deserializeOps(x)) assem.append(op); + assem.endDocument(); + expect(assem.toString()).to.equal('-c*3*4=6*2*4|1=1*3*4|b=h*3*4=b'); + }); + + it('smartOpAssembler ignore + ops with ops.chars === 0', async function () { + const x = '-c*3*4+6*3*4+0*3*4+1+0*3*4+1'; + const assem = new SmartOpAssembler(); + for (const op of deserializeOps(x)) assem.append(op); + assem.endDocument(); + expect(assem.toString()).to.equal('-c*3*4+8'); + }); + + it('smartOpAssembler ignore - ops with ops.chars === 0', async function () { + const x = '-c-6-0-1-0-1'; + const assem = new SmartOpAssembler(); + for (const op of deserializeOps(x)) assem.append(op); + assem.endDocument(); + expect(assem.toString()).to.equal('-k'); + }); + + it('smartOpAssembler append + op with text', async function () { + const assem = new SmartOpAssembler(); + const pool = poolOrArray([ + 'attr1,1', + 'attr2,2', + 'attr3,3', + 'attr4,4', + 'attr5,5', + ]); + + padutils.warnDeprecatedFlags.disabledForTestingOnly = true; + try { + assem.appendOpWithText('+', 'test', '*3*4*5', pool); + assem.appendOpWithText('+', 'test', '*3*4*5', pool); + assem.appendOpWithText('+', 'test', '*1*4*5', pool); + } finally { + // @ts-ignore + delete padutils.warnDeprecatedFlags.disabledForTestingOnly; + } + assem.endDocument(); + expect(assem.toString()).to.equal('*3*4*5+8*1*4*5+4'); + }); + + it('smartOpAssembler append + op with multiline text', async function () { + const assem = new SmartOpAssembler(); + const pool = poolOrArray([ + 'attr1,1', + 'attr2,2', + 'attr3,3', + 'attr4,4', + 'attr5,5', + ]); + + padutils.warnDeprecatedFlags.disabledForTestingOnly = true; + try { + assem.appendOpWithText('+', 'test\ntest', '*3*4*5', pool); + assem.appendOpWithText('+', '\ntest\n', '*3*4*5', pool); + assem.appendOpWithText('+', '\ntest', '*1*4*5', pool); + } finally { + // @ts-ignore + delete padutils.warnDeprecatedFlags.disabledForTestingOnly; + } + assem.endDocument(); + expect(assem.toString()).to.equal('*3*4*5|3+f*1*4*5|1+1*1*4*5+4'); + }); + + it('smartOpAssembler clear should empty internal assemblers', async function () { + const x = '-c*3*4+6|3=az*asdf0*1*2*3+1=1-1+1*0+1=1-1+1|c=c-1'; + const ops = deserializeOps(x); + const iter = { + _n: ops.next(), + hasNext() { return !this._n.done; }, + next() { const v = this._n.value; this._n = ops.next(); return v as Op; }, + }; + const assem = new SmartOpAssembler(); + var iter1 = iter.next() + assem.append(iter1); + var iter2 = iter.next() + assem.append(iter2); + var iter3 = iter.next() + assem.append(iter3); + console.log(assem.toString()); + assem.clear(); + assem.append(iter.next()); + assem.append(iter.next()); + console.log(assem.toString()); + assem.clear(); + let counter = 0; + while (iter.hasNext()) { + console.log(counter++) + assem.append(iter.next()); + } + assem.endDocument(); + expect(assem.toString()).to.equal('-1+1*0+1=1-1+1|c=c-1'); + }); + + describe('append atext to assembler', function () { + const testAppendATextToAssembler = (testId: number, atext: { text: string; attribs: string; }, correctOps: string) => { + it(`testAppendATextToAssembler#${testId}`, async function () { + const assem = new SmartOpAssembler(); + for (const op of opsFromAText(atext)) assem.append(op); + expect(assem.toString()).to.equal(correctOps); + }); + }; + + testAppendATextToAssembler(1, { + text: '\n', + attribs: '|1+1', + }, ''); + testAppendATextToAssembler(2, { + text: '\n\n', + attribs: '|2+2', + }, '|1+1'); + testAppendATextToAssembler(3, { + text: '\n\n', + attribs: '*x|2+2', + }, '*x|1+1'); + testAppendATextToAssembler(4, { + text: '\n\n', + attribs: '*x|1+1|1+1', + }, '*x|1+1'); + testAppendATextToAssembler(5, { + text: 'foo\n', + attribs: '|1+4', + }, '+3'); + testAppendATextToAssembler(6, { + text: '\nfoo\n', + attribs: '|2+5', + }, '|1+1+3'); + testAppendATextToAssembler(7, { + text: '\nfoo\n', + attribs: '*x|2+5', + }, '*x|1+1*x+3'); + testAppendATextToAssembler(8, { + text: '\n\n\nfoo\n', + attribs: '|2+2*x|2+5', + }, '|2+2*x|1+1*x+3'); + }); +}); diff --git a/src/tests/backend-new/specs/easysync-compose.ts b/src/tests/backend-new/specs/easysync-compose.ts new file mode 100644 index 000000000..79369caad --- /dev/null +++ b/src/tests/backend-new/specs/easysync-compose.ts @@ -0,0 +1,54 @@ +'use strict'; + +import {applyToText, checkRep, compose} from '../../../static/js/Changeset'; +import AttributePool from '../../../static/js/AttributePool'; +import {randomMultiline, randomTestChangeset} from '../easysync-helper'; +import {expect, describe, it} from 'vitest'; + +describe('easysync-compose', function () { + describe('compose', function () { + const testCompose = (randomSeed: number) => { + it(`testCompose#${randomSeed}`, async function () { + const p = new AttributePool(); + + const startText = `${randomMultiline(10, 20)}\n`; + + const x1 = randomTestChangeset(startText); + const change1 = x1[0]; + const text1 = x1[1]; + + const x2 = randomTestChangeset(text1); + const change2 = x2[0]; + const text2 = x2[1]; + + const x3 = randomTestChangeset(text2); + const change3 = x3[0]; + const text3 = x3[1]; + + const change12 = checkRep(compose(change1, change2, p)); + const change23 = checkRep(compose(change2, change3, p)); + const change123 = checkRep(compose(change12, change3, p)); + const change123a = checkRep(compose(change1, change23, p)); + expect(change123a).to.equal(change123); + + expect(applyToText(change12, startText)).to.equal(text2); + expect(applyToText(change23, text1)).to.equal(text3); + expect(applyToText(change123, startText)).to.equal(text3); + }); + }; + + for (let i = 0; i < 30; i++) testCompose(i); + }); + + describe('compose attributes', function () { + it('simpleComposeAttributesTest', async function () { + const p = new AttributePool(); + p.putAttrib(['bold', '']); + p.putAttrib(['bold', 'true']); + const cs1 = checkRep('Z:2>1*1+1*1=1$x'); + const cs2 = checkRep('Z:3>0*0|1=3$'); + const cs12 = checkRep(compose(cs1, cs2, p)); + expect(cs12).to.equal('Z:2>1+1*0|1=2$x'); + }); + }); +}); diff --git a/src/tests/backend-new/specs/easysync-inverseRandom.ts b/src/tests/backend-new/specs/easysync-inverseRandom.ts new file mode 100644 index 000000000..a9b743c76 --- /dev/null +++ b/src/tests/backend-new/specs/easysync-inverseRandom.ts @@ -0,0 +1,55 @@ +'use strict'; + +import AttributePool from '../../../static/js/AttributePool'; +import {checkRep, inverse, makeAttribution, mutateAttributionLines, mutateTextLines, splitAttributionLines} from '../../../static/js/Changeset'; +import {randomMultiline, randomTestChangeset, poolOrArray} from '../easysync-helper.js'; +import {expect, describe, it} from 'vitest' + +describe('easysync-inverseRandom', function () { + describe('inverse random', function () { + const testInverseRandom = (randomSeed: number) => { + it(`testInverseRandom#${randomSeed}`, async function () { + const p = poolOrArray(['apple,', 'apple,true', 'banana,', 'banana,true']); + + const startText = `${randomMultiline(10, 20)}\n`; + const alines = + splitAttributionLines(makeAttribution(startText), startText); + const lines = startText.slice(0, -1).split('\n').map((s) => `${s}\n`); + + const stylifier = randomTestChangeset(startText, true)[0]; + + mutateAttributionLines(stylifier, alines, p); + mutateTextLines(stylifier, lines); + + const changeset = randomTestChangeset(lines.join(''), true)[0]; + const inverseChangeset = inverse(changeset, lines, alines, p); + + const origLines = lines.slice(); + const origALines = alines.slice(); + + mutateTextLines(changeset, lines); + mutateAttributionLines(changeset, alines, p); + mutateTextLines(inverseChangeset, lines); + mutateAttributionLines(inverseChangeset, alines, p); + expect(lines).to.eql(origLines); + expect(alines).to.eql(origALines); + }); + }; + + for (let i = 0; i < 30; i++) testInverseRandom(i); + }); + + describe('inverse', function () { + const testInverse = (testId: number, cs: string, lines: string | RegExpMatchArray | null, alines: string[] | { get: (idx: number) => string; }, pool: string[] | AttributePool, correctOutput: string) => { + it(`testInverse#${testId}`, async function () { + pool = poolOrArray(pool); + const str = inverse(checkRep(cs), lines, alines, pool as AttributePool); + expect(str).to.equal(correctOutput); + }); + }; + + // take "FFFFTTTTT" and apply "-FT--FFTT", the inverse of which is "--F--TT--" + testInverse(1, 'Z:9>0=1*0=1*1=1=2*0=2*1|1=2$', null, + ['+4*1+5'], ['bold,', 'bold,true'], 'Z:9>0=2*0=1=2*1=2$'); + }); +}); diff --git a/src/tests/backend-new/specs/easysync-mutations.ts b/src/tests/backend-new/specs/easysync-mutations.ts new file mode 100644 index 000000000..1cf2ec276 --- /dev/null +++ b/src/tests/backend-new/specs/easysync-mutations.ts @@ -0,0 +1,320 @@ +'use strict'; + +import {applyToAttribution, applyToText, checkRep, joinAttributionLines, mutateAttributionLines, mutateTextLines, pack} from '../../../static/js/Changeset'; +import AttributePool from '../../../static/js/AttributePool'; +import {poolOrArray} from '../easysync-helper'; +import {expect, describe,it } from "vitest"; +import {SmartOpAssembler} from "../../../static/js/SmartOpAssembler"; +import Op from "../../../static/js/Op"; +import {StringAssembler} from "../../../static/js/StringAssembler"; +import TextLinesMutator from "../../../static/js/TextLinesMutator"; +import {numToString} from "../../../static/js/ChangesetUtils"; + +describe('easysync-mutations', function () { + const applyMutations = (mu: TextLinesMutator, arrayOfArrays: any[]) => { + arrayOfArrays.forEach((a) => { + // @ts-ignore + const result = mu[a[0]](...a.slice(1)); + if (a[0] === 'remove' && a[3]) { + expect(result).to.equal(a[3]); + } + }); + }; + + const mutationsToChangeset = (oldLen: number, arrayOfArrays: string[][]) => { + const assem = new SmartOpAssembler(); + const op = new Op(); + const bank = new StringAssembler(); + let oldPos = 0; + let newLen = 0; + arrayOfArrays.forEach((a: any[]) => { + if (a[0] === 'skip') { + op.opcode = '='; + op.chars = a[1]; + op.lines = (a[2] || 0); + assem.append(op); + oldPos += op.chars; + newLen += op.chars; + } else if (a[0] === 'remove') { + op.opcode = '-'; + op.chars = a[1]; + op.lines = (a[2] || 0); + assem.append(op); + oldPos += op.chars; + } else if (a[0] === 'insert') { + op.opcode = '+'; + bank.append(a[1]); + op.chars = a[1].length; + op.lines = (a[2] || 0); + assem.append(op); + newLen += op.chars; + } + }); + newLen += oldLen - oldPos; + assem.endDocument(); + return pack(oldLen, newLen, assem.toString(), bank.toString()); + }; + + const runMutationTest = (testId: number, origLines: string[], muts:any, correct: string[]) => { + it(`runMutationTest#${testId}`, async function () { + let lines = origLines.slice(); + const mu = new TextLinesMutator(lines); + applyMutations(mu, muts); + mu.close(); + expect(lines).to.eql(correct); + + const inText = origLines.join(''); + const cs = mutationsToChangeset(inText.length, muts); + lines = origLines.slice(); + mutateTextLines(cs, lines); + expect(lines).to.eql(correct); + + const correctText = correct.join(''); + const outText = applyToText(cs, inText); + expect(outText).to.equal(correctText); + }); + }; + + runMutationTest(1, ['apple\n', 'banana\n', 'cabbage\n', 'duffle\n', 'eggplant\n'], [ + ['remove', 1, 0, 'a'], + ['insert', 'tu'], + ['remove', 1, 0, 'p'], + ['skip', 4, 1], + ['skip', 7, 1], + ['insert', 'cream\npie\n', 2], + ['skip', 2], + ['insert', 'bot'], + ['insert', '\n', 1], + ['insert', 'bu'], + ['skip', 3], + ['remove', 3, 1, 'ge\n'], + ['remove', 6, 0, 'duffle'], + ], ['tuple\n', 'banana\n', 'cream\n', 'pie\n', 'cabot\n', 'bubba\n', 'eggplant\n']); + + runMutationTest(2, ['apple\n', 'banana\n', 'cabbage\n', 'duffle\n', 'eggplant\n'], [ + ['remove', 1, 0, 'a'], + ['remove', 1, 0, 'p'], + ['insert', 'tu'], + ['skip', 11, 2], + ['insert', 'cream\npie\n', 2], + ['skip', 2], + ['insert', 'bot'], + ['insert', '\n', 1], + ['insert', 'bu'], + ['skip', 3], + ['remove', 3, 1, 'ge\n'], + ['remove', 6, 0, 'duffle'], + ], ['tuple\n', 'banana\n', 'cream\n', 'pie\n', 'cabot\n', 'bubba\n', 'eggplant\n']); + + runMutationTest(3, ['apple\n', 'banana\n', 'cabbage\n', 'duffle\n', 'eggplant\n'], [ + ['remove', 6, 1, 'apple\n'], + ['skip', 15, 2], + ['skip', 6], + ['remove', 1, 1, '\n'], + ['remove', 8, 0, 'eggplant'], + ['skip', 1, 1], + ], ['banana\n', 'cabbage\n', 'duffle\n']); + + runMutationTest(4, ['15\n'], [ + ['skip', 1], + ['insert', '\n2\n3\n4\n', 4], + ['skip', 2, 1], + ], ['1\n', '2\n', '3\n', '4\n', '5\n']); + + runMutationTest(5, ['1\n', '2\n', '3\n', '4\n', '5\n'], [ + ['skip', 1], + ['remove', 7, 4, '\n2\n3\n4\n'], + ['skip', 2, 1], + ], ['15\n']); + + runMutationTest(6, ['123\n', 'abc\n', 'def\n', 'ghi\n', 'xyz\n'], [ + ['insert', '0'], + ['skip', 4, 1], + ['skip', 4, 1], + ['remove', 8, 2, 'def\nghi\n'], + ['skip', 4, 1], + ], ['0123\n', 'abc\n', 'xyz\n']); + + runMutationTest(7, ['apple\n', 'banana\n', 'cabbage\n', 'duffle\n', 'eggplant\n'], [ + ['remove', 6, 1, 'apple\n'], + ['skip', 15, 2, true], + ['skip', 6, 0, true], + ['remove', 1, 1, '\n'], + ['remove', 8, 0, 'eggplant'], + ['skip', 1, 1, true], + ], ['banana\n', 'cabbage\n', 'duffle\n']); + + it('mutatorHasMore', async function () { + const lines = ['1\n', '2\n', '3\n', '4\n']; + let mu; + + mu = new TextLinesMutator(lines); + expect(mu.hasMore()).toBeTruthy(); + mu.skip(8, 4); + expect(mu.hasMore()).toBeFalsy(); + mu.close(); + expect(mu.hasMore()).toBeFalsy(); + + // still 1,2,3,4 + mu = new TextLinesMutator(lines); + expect(mu.hasMore()).toBeTruthy(); + mu.remove(2, 1); + expect(mu.hasMore()).toBeTruthy(); + mu.skip(2, 1); + expect(mu.hasMore()).toBeTruthy(); + mu.skip(2, 1); + expect(mu.hasMore()).toBeTruthy(); + mu.skip(2, 1); + expect(mu.hasMore()).toBeFalsy(); + mu.insert('5\n', 1); + expect(mu.hasMore()).toBeFalsy(); + mu.close(); + expect(mu.hasMore()).toBeFalsy(); + + // 2,3,4,5 now + mu = new TextLinesMutator(lines); + expect(mu.hasMore()).toBeTruthy(); + mu.remove(6, 3); + expect(mu.hasMore()).toBeTruthy(); + mu.remove(2, 1); + expect(mu.hasMore()).toBeFalsy(); + mu.insert('hello\n', 1); + expect(mu.hasMore()).toBeFalsy(); + mu.close(); + expect(mu.hasMore()).toBeFalsy(); + }); + + describe('mutateTextLines', function () { + const testMutateTextLines = (testId: number, cs: string, lines: string[], correctLines: string[]) => { + it(`testMutateTextLines#${testId}`, async function () { + const a = lines.slice(); + mutateTextLines(cs, a); + expect(a).to.eql(correctLines); + }); + }; + + testMutateTextLines(1, 'Z:4<1|1-2-1|1+1+1$\nc', ['a\n', 'b\n'], ['\n', 'c\n']); + testMutateTextLines(2, 'Z:4>0|1-2-1|2+3$\nc\n', ['a\n', 'b\n'], ['\n', 'c\n', '\n']); + + it('mutate keep only lines', async function () { + const lines = ['1\n', '2\n', '3\n', '4\n']; + const result = lines.slice(); + const cs = 'Z:8>0*0|1=2|2=2'; + + mutateTextLines(cs, lines); + expect(result).to.eql(lines); + }); + }); + + describe('mutate attributions', function () { + const testPoolWithChars = (() => { + const p = new AttributePool(); + p.putAttrib(['char', 'newline']); + for (let i = 1; i < 36; i++) { + p.putAttrib(['char', numToString(i)]); + } + p.putAttrib(['char', '']); + return p; + })(); + + const runMutateAttributionTest = (testId: number, attribs: string[] | AttributePool, cs: string, alines: string[], outCorrect: string[]) => { + it(`runMutateAttributionTest#${testId}`, async function () { + const p = poolOrArray(attribs); + const alines2 = Array.prototype.slice.call(alines); + mutateAttributionLines(checkRep(cs), alines2, p); + expect(alines2).to.eql(outCorrect); + + const removeQuestionMarks = (a: string) => a.replace(/\?/g, ''); + const inMerged = joinAttributionLines(alines.map(removeQuestionMarks)); + const correctMerged = joinAttributionLines(outCorrect.map(removeQuestionMarks)); + const mergedResult = applyToAttribution(cs, inMerged, p); + expect(mergedResult).to.equal(correctMerged); + }); + }; + + // turn 123\n 456\n 789\n into 123\n 456\n 789\n + runMutateAttributionTest(1, + ['bold,true'], 'Z:c>0|1=4=1*0=1$', ['|1+4', '|1+4', '|1+4'], + ['|1+4', '+1*0+1|1+2', '|1+4']); + + // make a document bold + runMutateAttributionTest(2, + ['bold,true'], 'Z:c>0*0|3=c$', ['|1+4', '|1+4', '|1+4'], ['*0|1+4', '*0|1+4', '*0|1+4']); + + // clear bold on document + runMutateAttributionTest(3, + ['bold,', 'bold,true'], 'Z:c>0*0|3=c$', + ['*1+1+1*1+1|1+1', '+1*1+1|1+2', '*1+1+1*1+1|1+1'], ['|1+4', '|1+4', '|1+4']); + + // add a character on line 3 of a document with 5 blank lines, and make sure + // the optimization that skips purely-kept lines is working; if any attribution string + // with a '?' is parsed it will cause an error. + runMutateAttributionTest(4, + ['foo,bar', 'line,1', 'line,2', 'line,3', 'line,4', 'line,5'], + 'Z:5>1|2=2+1$x', ['?*1|1+1', '?*2|1+1', '*3|1+1', '?*4|1+1', '?*5|1+1'], + ['?*1|1+1', '?*2|1+1', '+1*3|1+1', '?*4|1+1', '?*5|1+1']); + + // based on runMutationTest#1 + runMutateAttributionTest(5, testPoolWithChars, + 'Z:11>7-2*t+1*u+1|2=b|2+a=2*b+1*o+1*t+1*0|1+1*b+1*u+1=3|1-3-6$tucream\npie\nbot\nbu', + [ + '*a+1*p+2*l+1*e+1*0|1+1', + '*b+1*a+1*n+1*a+1*n+1*a+1*0|1+1', + '*c+1*a+1*b+2*a+1*g+1*e+1*0|1+1', + '*d+1*u+1*f+2*l+1*e+1*0|1+1', + '*e+1*g+2*p+1*l+1*a+1*n+1*t+1*0|1+1', + ], + [ + '*t+1*u+1*p+1*l+1*e+1*0|1+1', + '*b+1*a+1*n+1*a+1*n+1*a+1*0|1+1', + '|1+6', + '|1+4', + '*c+1*a+1*b+1*o+1*t+1*0|1+1', + '*b+1*u+1*b+2*a+1*0|1+1', + '*e+1*g+2*p+1*l+1*a+1*n+1*t+1*0|1+1', + ]); + + // based on runMutationTest#3 + runMutateAttributionTest(6, testPoolWithChars, + 'Z:117=1|4+7$\n2\n3\n4\n', + ['*1+1*5|1+2'], ['*1+1|1+1', '|1+2', '|1+2', '|1+2', '*5|1+2']); + + // based on runMutationTest#5 + runMutateAttributionTest(8, testPoolWithChars, 'Z:a<7=1|4-7$', + ['*1|1+2', '*2|1+2', '*3|1+2', '*4|1+2', '*5|1+2'], ['*1+1*5|1+2']); + + // based on runMutationTest#6 + runMutateAttributionTest(9, testPoolWithChars, 'Z:k<7*0+1*10|2=8|2-8$0', + [ + '*1+1*2+1*3+1|1+1', + '*a+1*b+1*c+1|1+1', + '*d+1*e+1*f+1|1+1', + '*g+1*h+1*i+1|1+1', + '?*x+1*y+1*z+1|1+1', + ], + ['*0+1|1+4', '|1+4', '?*x+1*y+1*z+1|1+1']); + + runMutateAttributionTest(10, testPoolWithChars, 'Z:6>4=1+1=1+1|1=1+1=1*0+1$abcd', + ['|1+3', '|1+3'], ['|1+5', '+2*0+1|1+2']); + + + runMutateAttributionTest(11, testPoolWithChars, 'Z:s>1|1=4=6|1+1$\n', + ['*0|1+4', '*0|1+8', '*0+5|1+1', '*0|1+1', '*0|1+5', '*0|1+1', '*0|1+1', '*0|1+1', '|1+1'], + [ + '*0|1+4', + '*0+6|1+1', + '*0|1+2', + '*0+5|1+1', + '*0|1+1', + '*0|1+5', + '*0|1+1', + '*0|1+1', + '*0|1+1', + '|1+1', + ]); + }); +}); diff --git a/src/tests/backend-new/specs/easysync-other.test.ts b/src/tests/backend-new/specs/easysync-other.test.ts new file mode 100644 index 000000000..9a24dee6f --- /dev/null +++ b/src/tests/backend-new/specs/easysync-other.test.ts @@ -0,0 +1,166 @@ +'use strict'; + +import {applyToAttribution, applyToText, checkRep, deserializeOps, exportedForTestingOnly, filterAttribNumbers, joinAttributionLines, makeAttribsString, makeSplice, moveOpsToNewPool, opAttributeValue, splitAttributionLines} from '../../../static/js/Changeset'; +import AttributePool from '../../../static/js/AttributePool'; +import {randomMultiline, poolOrArray} from '../easysync-helper'; +import padutils from '../../../static/js/pad_utils'; +import {describe, it, expect} from 'vitest' +import Op from "../../../static/js/Op"; +import {MergingOpAssembler} from "../../../static/js/MergingOpAssembler"; +import {Attribute} from "../../../static/js/types/Attribute"; + + +describe('easysync-other', function () { + describe('filter attribute numbers', function () { + const testFilterAttribNumbers = (testId: number, cs: string, filter: Function, correctOutput: string) => { + it(`testFilterAttribNumbers#${testId}`, async function () { + const str = filterAttribNumbers(cs, filter); + expect(str).to.equal(correctOutput); + }); + }; + + testFilterAttribNumbers(1, '*0*1+1+2+3*1+4*2+5*0*2*1*b*c+6', + (n: number) => (n % 2) === 0, '*0+1+2+3+4*2+5*0*2*c+6'); + testFilterAttribNumbers(2, '*0*1+1+2+3*1+4*2+5*0*2*1*b*c+6', + (n: number) => (n % 2) === 1, '*1+1+2+3*1+4+5*1*b+6'); + }); + + describe('make attribs string', function () { + const testMakeAttribsString = (testId: number, pool: string[], opcode: string, attribs: string | Attribute[], correctString: string) => { + it(`testMakeAttribsString#${testId}`, async function () { + const p = poolOrArray(pool); + padutils.warnDeprecatedFlags.disabledForTestingOnly = true; + try { + expect(makeAttribsString(opcode, attribs, p)).to.equal(correctString); + } finally { + // @ts-ignore + delete padutils.warnDeprecatedFlags.disabledForTestingOnly; + } + }); + }; + + testMakeAttribsString(1, ['bold,'], '+', [ + ['bold', ''], + ], ''); + testMakeAttribsString(2, ['abc,def', 'bold,'], '=', [ + ['bold', ''], + ], '*1'); + testMakeAttribsString(3, ['abc,def', 'bold,true'], '+', [ + ['abc', 'def'], + ['bold', 'true'], + ], '*0*1'); + testMakeAttribsString(4, ['abc,def', 'bold,true'], '+', [ + ['bold', 'true'], + ['abc', 'def'], + ], '*0*1'); + }); + + describe('other', function () { + it('testMoveOpsToNewPool', async function () { + const pool1 = new AttributePool(); + const pool2 = new AttributePool(); + + pool1.putAttrib(['baz', 'qux']); + pool1.putAttrib(['foo', 'bar']); + + pool2.putAttrib(['foo', 'bar']); + + expect(moveOpsToNewPool('Z:1>2*1+1*0+1$ab', pool1, pool2)) + .to.equal('Z:1>2*0+1*1+1$ab'); + expect(moveOpsToNewPool('*1+1*0+1', pool1, pool2)).to.equal('*0+1*1+1'); + }); + + it('testMakeSplice', async function () { + const t = 'a\nb\nc\n'; + let splice = makeSplice(t, 5, 0, 'def') + const t2 = applyToText(splice, t); + expect(t2).to.equal('a\nb\ncdef\n'); + }); + + it('makeSplice at the end', async function () { + const orig = '123'; + const ins = '456'; + expect(applyToText(makeSplice(orig, orig.length, 0, ins), orig)) + .to.equal(`${orig}${ins}`); + }); + + it('testToSplices', async function () { + const cs = checkRep('Z:z>9*0=1=4-3+9=1|1-4-4+1*0+a$123456789abcdefghijk'); + const correctSplices = [ + [5, 8, '123456789'], + [9, 17, 'abcdefghijk'], + ]; + expect(exportedForTestingOnly.toSplices(cs)).to.eql(correctSplices); + }); + + it('opAttributeValue', async function () { + const p = new AttributePool(); + p.putAttrib(['name', 'david']); + p.putAttrib(['color', 'green']); + + const stringOp = (str: string) => deserializeOps(str).next().value as Op; + + padutils.warnDeprecatedFlags.disabledForTestingOnly = true; + try { + expect(opAttributeValue(stringOp('*0*1+1'), 'name', p)).to.equal('david'); + expect(opAttributeValue(stringOp('*0+1'), 'name', p)).to.equal('david'); + expect(opAttributeValue(stringOp('*1+1'), 'name', p)).to.equal(''); + expect(opAttributeValue(stringOp('+1'), 'name', p)).to.equal(''); + expect(opAttributeValue(stringOp('*0*1+1'), 'color', p)).to.equal('green'); + expect(opAttributeValue(stringOp('*1+1'), 'color', p)).to.equal('green'); + expect(opAttributeValue(stringOp('*0+1'), 'color', p)).to.equal(''); + expect(opAttributeValue(stringOp('+1'), 'color', p)).to.equal(''); + } finally { + // @ts-ignore + delete padutils.warnDeprecatedFlags.disabledForTestingOnly; + } + }); + + describe('applyToAttribution', function () { + const runApplyToAttributionTest = (testId: number, attribs: string[], cs: string, inAttr: string, outCorrect: string) => { + it(`applyToAttribution#${testId}`, async function () { + const p = poolOrArray(attribs); + const result = applyToAttribution(checkRep(cs), inAttr, p); + expect(result).to.equal(outCorrect); + }); + }; + + // turn cactus\n into actusabcd\n + runApplyToAttributionTest(1, + ['bold,', 'bold,true'], 'Z:7>3-1*0=1*1=1=3+4$abcd', '+1*1+1|1+5', '+1*1+1|1+8'); + + // turn "david\ngreenspan\n" into "david\ngreen\n" + runApplyToAttributionTest(2, + ['bold,', 'bold,true'], 'Z:g<4*1|1=6*1=5-4$', '|2+g', '*1|1+6*1+5|1+1'); + }); + + describe('split/join attribution lines', function () { + const testSplitJoinAttributionLines = (randomSeed: number) => { + const stringToOps = (str: string) => { + const assem = new MergingOpAssembler(); + const o = new Op('+'); + o.chars = 1; + for (let i = 0; i < str.length; i++) { + const c = str.charAt(i); + o.lines = (c === '\n' ? 1 : 0); + o.attribs = (c === 'a' || c === 'b' ? `*${c}` : ''); + assem.append(o); + } + return assem.toString(); + }; + + it(`testSplitJoinAttributionLines#${randomSeed}`, async function () { + const doc = `${randomMultiline(10, 20)}\n`; + + const theJoined = stringToOps(doc); + const theSplit = doc.match(/[^\n]*\n/g)!.map(stringToOps); + + expect(splitAttributionLines(theJoined, doc)).to.eql(theSplit); + expect(joinAttributionLines(theSplit)).to.equal(theJoined); + }); + }; + + for (let i = 0; i < 10; i++) testSplitJoinAttributionLines(i); + }); + }); +}); diff --git a/src/tests/backend-new/specs/easysync-subAttribution.ts b/src/tests/backend-new/specs/easysync-subAttribution.ts new file mode 100644 index 000000000..90760d9be --- /dev/null +++ b/src/tests/backend-new/specs/easysync-subAttribution.ts @@ -0,0 +1,55 @@ +'use strict'; + +import {subattribution} from '../../../static/js/Changeset'; +import {expect, describe, it} from 'vitest'; +describe('easysync-subAttribution', function () { + const testSubattribution = (testId: number, astr: string, start: number, end: number | undefined, correctOutput: string) => { + it(`subattribution#${testId}`, async function () { + const str = subattribution(astr, start, end); + expect(str).to.equal(correctOutput); + }); + }; + + testSubattribution(1, '+1', 0, 0, ''); + testSubattribution(2, '+1', 0, 1, '+1'); + testSubattribution(3, '+1', 0, undefined, '+1'); + testSubattribution(4, '|1+1', 0, 0, ''); + testSubattribution(5, '|1+1', 0, 1, '|1+1'); + testSubattribution(6, '|1+1', 0, undefined, '|1+1'); + testSubattribution(7, '*0+1', 0, 0, ''); + testSubattribution(8, '*0+1', 0, 1, '*0+1'); + testSubattribution(9, '*0+1', 0, undefined, '*0+1'); + testSubattribution(10, '*0|1+1', 0, 0, ''); + testSubattribution(11, '*0|1+1', 0, 1, '*0|1+1'); + testSubattribution(12, '*0|1+1', 0, undefined, '*0|1+1'); + testSubattribution(13, '*0+2+1*1+3', 0, 1, '*0+1'); + testSubattribution(14, '*0+2+1*1+3', 0, 2, '*0+2'); + testSubattribution(15, '*0+2+1*1+3', 0, 3, '*0+2+1'); + testSubattribution(16, '*0+2+1*1+3', 0, 4, '*0+2+1*1+1'); + testSubattribution(17, '*0+2+1*1+3', 0, 5, '*0+2+1*1+2'); + testSubattribution(18, '*0+2+1*1+3', 0, 6, '*0+2+1*1+3'); + testSubattribution(19, '*0+2+1*1+3', 0, 7, '*0+2+1*1+3'); + testSubattribution(20, '*0+2+1*1+3', 0, undefined, '*0+2+1*1+3'); + testSubattribution(21, '*0+2+1*1+3', 1, undefined, '*0+1+1*1+3'); + testSubattribution(22, '*0+2+1*1+3', 2, undefined, '+1*1+3'); + testSubattribution(23, '*0+2+1*1+3', 3, undefined, '*1+3'); + testSubattribution(24, '*0+2+1*1+3', 4, undefined, '*1+2'); + testSubattribution(25, '*0+2+1*1+3', 5, undefined, '*1+1'); + testSubattribution(26, '*0+2+1*1+3', 6, undefined, ''); + testSubattribution(27, '*0+2+1*1|1+3', 0, 1, '*0+1'); + testSubattribution(28, '*0+2+1*1|1+3', 0, 2, '*0+2'); + testSubattribution(29, '*0+2+1*1|1+3', 0, 3, '*0+2+1'); + testSubattribution(30, '*0+2+1*1|1+3', 0, 4, '*0+2+1*1+1'); + testSubattribution(31, '*0+2+1*1|1+3', 0, 5, '*0+2+1*1+2'); + testSubattribution(32, '*0+2+1*1|1+3', 0, 6, '*0+2+1*1|1+3'); + testSubattribution(33, '*0+2+1*1|1+3', 0, 7, '*0+2+1*1|1+3'); + testSubattribution(34, '*0+2+1*1|1+3', 0, undefined, '*0+2+1*1|1+3'); + testSubattribution(35, '*0+2+1*1|1+3', 1, undefined, '*0+1+1*1|1+3'); + testSubattribution(36, '*0+2+1*1|1+3', 2, undefined, '+1*1|1+3'); + testSubattribution(37, '*0+2+1*1|1+3', 3, undefined, '*1|1+3'); + testSubattribution(38, '*0+2+1*1|1+3', 4, undefined, '*1|1+2'); + testSubattribution(39, '*0+2+1*1|1+3', 5, undefined, '*1|1+1'); + testSubattribution(40, '*0+2+1*1|1+3', 1, 5, '*0+1+1*1+2'); + testSubattribution(41, '*0+2+1*1|1+3', 2, 6, '+1*1|1+3'); + testSubattribution(42, '*0+2+1*1+3', 2, 6, '+1*1+3'); +}); diff --git a/src/tests/backend-new/specs/pad_utils.ts b/src/tests/backend-new/specs/pad_utils.ts new file mode 100644 index 000000000..569f49d04 --- /dev/null +++ b/src/tests/backend-new/specs/pad_utils.ts @@ -0,0 +1,42 @@ +import {MapArrayType} from "../../../node/types/MapType"; +import padutils from '../../../static/js/pad_utils'; +import {describe, it, expect, afterEach, beforeAll} from "vitest"; + +describe(__filename, function () { + describe('warnDeprecated', function () { + const {warnDeprecatedFlags, warnDeprecated} = padutils; + const backups:MapArrayType = {}; + + beforeAll(async function () { + backups.logger = warnDeprecatedFlags.logger; + }); + + afterEach(async function () { + warnDeprecatedFlags.logger = backups.logger; + delete warnDeprecatedFlags._rl; // Reset internal rate limiter state. + }); + + /*it('includes the stack', async function () { + let got; + warnDeprecated.logger = {warn: (stack: any) => got = stack}; + warnDeprecated(); + assert(got!.includes(__filename)); + });*/ + + it('rate limited', async function () { + let got = 0; + warnDeprecatedFlags.logger = {warn: () => ++got}; + warnDeprecated(); // Initialize internal rate limiter state. + const {period} = warnDeprecatedFlags._rl!; + got = 0; + const testCases = [[0, 1], [0, 1], [period - 1, 1], [period, 2]]; + for (const [now, want] of testCases) { // In a loop so that the stack trace is the same. + warnDeprecatedFlags._rl!.now = () => now; + warnDeprecated(); + expect(got).toEqual(want); + } + warnDeprecated(); // Should have a different stack trace. + expect(got).toEqual(testCases[testCases.length - 1][1] + 1); + }); + }); +}); diff --git a/src/tests/backend-new/specs/path_exists.ts b/src/tests/backend-new/specs/path_exists.ts new file mode 100644 index 000000000..5c719d05e --- /dev/null +++ b/src/tests/backend-new/specs/path_exists.ts @@ -0,0 +1,22 @@ +import check from "../../../node/utils/path_exists"; +import {expect, describe, it} from "vitest"; + +describe('Test path exists', function () { + it('should return true if the path exists - directory', function () { + const path = './locales'; + const result = check(path); + expect(result).toBeTruthy(); + }); + + it('should return true if the path exists - file', function () { + const path = './locales/en.json'; + const result = check(path); + expect(result).toBeTruthy(); + }) + + it('should return false if the path does not exist', function () { + const path = './path_not_exists.ts'; + const result = check(path); + expect(result).toEqual(false); + }); +}) diff --git a/src/tests/backend-new/specs/promises.ts b/src/tests/backend-new/specs/promises.ts new file mode 100644 index 000000000..2ce6aed27 --- /dev/null +++ b/src/tests/backend-new/specs/promises.ts @@ -0,0 +1,92 @@ +import {MapArrayType} from "../../../node/types/MapType"; + +import {timesLimit} from '../../../node/utils/promises'; +import {describe, it, expect} from "vitest"; + +describe(__filename, function () { + describe('promises.timesLimit', function () { + let wantIndex = 0; + + type TestPromise = { + promise?: Promise, + resolve?: () => void, + } + + const testPromises: TestPromise[] = []; + const makePromise = (index: number) => { + // Make sure index increases by one each time. + expect(index).toEqual(wantIndex++); + // Save the resolve callback (so the test can trigger resolution) + // and the promise itself (to wait for resolve to take effect). + const p:TestPromise = {}; + p.promise = new Promise((resolve) => { + p.resolve = resolve; + }); + testPromises.push(p); + return p.promise; + }; + + const total = 11; + const concurrency = 7; + const timesLimitPromise = timesLimit(total, concurrency, makePromise); + + it('honors concurrency', async function () { + expect(wantIndex).toEqual(concurrency); + }); + + it('creates another when one completes', async function () { + const {promise, resolve} = testPromises.shift()!; + resolve!(); + await promise; + expect(wantIndex).toEqual(concurrency + 1); + }); + + it('creates the expected total number of promises', async function () { + while (testPromises.length > 0) { + // Resolve them in random order to ensure that the resolution order doesn't matter. + const i = Math.floor(Math.random() * Math.floor(testPromises.length)); + const {promise, resolve} = testPromises.splice(i, 1)[0]; + resolve!(); + await promise; + } + expect(wantIndex).toEqual(total); + }); + + it('resolves', async function () { + await timesLimitPromise; + }); + + it('does not create too many promises if total < concurrency', async function () { + wantIndex = 0; + expect(testPromises.length).toEqual(0); + const total = 7; + const concurrency = 11; + const timesLimitPromise = timesLimit(total, concurrency, makePromise); + while (testPromises.length > 0) { + const {promise, resolve} = testPromises.pop()!; + resolve!(); + await promise; + } + await timesLimitPromise; + expect(wantIndex).toEqual(total); + }); + + it('accepts total === 0, concurrency > 0', async function () { + wantIndex = 0; + expect(testPromises.length).toEqual(0); + await timesLimit(0, concurrency, makePromise); + expect(wantIndex).toEqual(0); + }); + + it('accepts total === 0, concurrency === 0', async function () { + wantIndex = 0; + expect(testPromises.length).toEqual(0); + await timesLimit(0, 0, makePromise); + expect(wantIndex).toEqual(0); + }); + + it('rejects total > 0, concurrency === 0', async function () { + expect(timesLimit(total, 0, makePromise)).rejects.toThrow(RangeError); + }); + }); +}); diff --git a/src/tests/backend-new/specs/sanitizePathname.ts b/src/tests/backend-new/specs/sanitizePathname.ts new file mode 100644 index 000000000..e841ae155 --- /dev/null +++ b/src/tests/backend-new/specs/sanitizePathname.ts @@ -0,0 +1,98 @@ +import {strict as assert} from "assert"; +import path from 'path'; +import sanitizePathname from '../../../node/utils/sanitizePathname'; +import {describe, it, expect} from 'vitest'; + +describe(__filename, function () { + describe('absolute paths rejected', function () { + const testCases = [ + ['posix', '/'], + ['posix', '/foo'], + ['win32', '/'], + ['win32', '\\'], + ['win32', 'C:/foo'], + ['win32', 'C:\\foo'], + ['win32', 'c:/foo'], + ['win32', 'c:\\foo'], + ['win32', '/foo'], + ['win32', '\\foo'], + ]; + for (const [platform, p] of testCases) { + it(`${platform} ${p}`, async function () { + // @ts-ignore + expect(() => sanitizePathname(p, path[platform] as any)).toThrowError(/absolute path/); + }); + } + }); + describe('directory traversal rejected', function () { + const testCases = [ + ['posix', '..'], + ['posix', '../'], + ['posix', '../foo'], + ['posix', 'foo/../..'], + ['win32', '..'], + ['win32', '../'], + ['win32', '..\\'], + ['win32', '../foo'], + ['win32', '..\\foo'], + ['win32', 'foo/../..'], + ['win32', 'foo\\..\\..'], + ]; + for (const [platform, p] of testCases) { + it(`${platform} ${p}`, async function () { + // @ts-ignore + assert.throws(() => sanitizePathname(p, path[platform]), {message: /travers/}); + }); + } + }); + + describe('accepted paths', function () { + const testCases = [ + ['posix', '', '.'], + ['posix', '.'], + ['posix', './'], + ['posix', 'foo'], + ['posix', 'foo/'], + ['posix', 'foo/bar/..', 'foo'], + ['posix', 'foo/bar/../', 'foo/'], + ['posix', './foo', 'foo'], + ['posix', 'foo/bar'], + ['posix', 'foo\\bar'], + ['posix', '\\foo'], + ['posix', '..\\foo'], + ['posix', 'foo/../bar', 'bar'], + ['posix', 'C:/foo'], + ['posix', 'C:\\foo'], + ['win32', '', '.'], + ['win32', '.'], + ['win32', './'], + ['win32', '.\\', './'], + ['win32', 'foo'], + ['win32', 'foo/'], + ['win32', 'foo\\', 'foo/'], + ['win32', 'foo/bar/..', 'foo'], + ['win32', 'foo\\bar\\..', 'foo'], + ['win32', 'foo/bar/../', 'foo/'], + ['win32', 'foo\\bar\\..\\', 'foo/'], + ['win32', './foo', 'foo'], + ['win32', '.\\foo', 'foo'], + ['win32', 'foo/bar'], + ['win32', 'foo\\bar', 'foo/bar'], + ['win32', 'foo/../bar', 'bar'], + ['win32', 'foo\\..\\bar', 'bar'], + ['win32', 'foo/..\\bar', 'bar'], + ['win32', 'foo\\../bar', 'bar'], + ]; + for (const [platform, p, tcWant] of testCases) { + const want = tcWant == null ? p : tcWant; + it(`${platform} ${p || ''} -> ${want}`, async function () { + // @ts-ignore + assert.equal(sanitizePathname(p, path[platform]), want); + }); + } + }); + + it('default path API', async function () { + assert.equal(sanitizePathname('foo'), 'foo'); + }); +}); diff --git a/src/tests/backend-new/specs/skiplist.ts b/src/tests/backend-new/specs/skiplist.ts new file mode 100644 index 000000000..23ad46ae6 --- /dev/null +++ b/src/tests/backend-new/specs/skiplist.ts @@ -0,0 +1,56 @@ +'use strict'; + +import SkipList from 'ep_etherpad-lite/static/js/skiplist'; +import {expect, describe, it} from 'vitest'; + +describe('skiplist.js', function () { + it('rejects null keys', async function () { + const skiplist = new SkipList(); + for (const key of [undefined, null]) { + // @ts-ignore + expect(() => skiplist.push({key})).toThrowError(); + } + }); + + it('rejects duplicate keys', async function () { + const skiplist = new SkipList(); + skiplist.push({key: 'foo'}); + expect(() => skiplist.push({key: 'foo'})).toThrowError(); + }); + + it('atOffset() returns last entry that touches offset', async function () { + const skiplist = new SkipList(); + const entries: { key: string; width: number; }[] = []; + let nextId = 0; + const makeEntry = (width: number) => { + const entry = {key: `id${nextId++}`, width}; + entries.push(entry); + return entry; + }; + + skiplist.push(makeEntry(5)); + expect(skiplist.atOffset(4)).toBe(entries[0]); + expect(skiplist.atOffset(5)).toBe(entries[0]); + expect(() => skiplist.atOffset(6)).toThrowError(); + + skiplist.push(makeEntry(0)); + expect(skiplist.atOffset(4)).toBe(entries[0]); + expect(skiplist.atOffset(5)).toBe(entries[1]); + expect(() => skiplist.atOffset(6)).toThrowError(); + + skiplist.push(makeEntry(0)); + expect(skiplist.atOffset(4)).toBe(entries[0]); + expect(skiplist.atOffset(5)).toBe(entries[2]); + expect(() => skiplist.atOffset(6)).toThrowError(); + + skiplist.splice(2, 0, [makeEntry(0)]); + expect(skiplist.atOffset(4)).toBe(entries[0]); + expect(skiplist.atOffset(5)).toBe(entries[2]); + expect(() => skiplist.atOffset(6)).toThrowError(); + + skiplist.push(makeEntry(3)); + expect(skiplist.atOffset(4)).toBe(entries[0]); + expect(skiplist.atOffset(5)).toBe(entries[4]); + expect(skiplist.atOffset(6)).toBe(entries[4]); + }); +}); diff --git a/src/tests/backend/common.ts b/src/tests/backend/common.ts new file mode 100644 index 000000000..271fb43d4 --- /dev/null +++ b/src/tests/backend/common.ts @@ -0,0 +1,302 @@ +'use strict'; + +import {MapArrayType} from "../../node/types/MapType"; + +import AttributePool from '../../static/js/AttributePool'; +const assert = require('assert').strict; +const io = require('socket.io-client'); +const log4js = require('log4js'); +import padutils from '../../static/js/pad_utils'; +const process = require('process'); +const server = require('../../node/server'); +const setCookieParser = require('set-cookie-parser'); +const settings = require('../../node/utils/Settings'); +import supertest from 'supertest'; +import TestAgent from "supertest/lib/agent"; +import {Http2Server} from "node:http2"; +import {SignJWT} from "jose"; +import {privateKeyExported} from "../../node/security/OAuth2Provider"; +const webaccess = require('../../node/hooks/express/webaccess'); + +const backups:MapArrayType = {}; +let agentPromise:Promise|null = null; + +export let agent: TestAgent|null = null; +export let baseUrl:string|null = null; +export let httpServer: Http2Server|null = null; +export const logger = log4js.getLogger('test'); + +const logLevel = logger.level; + +// Mocha doesn't monitor unhandled Promise rejections, so convert them to uncaught exceptions. +// https://github.com/mochajs/mocha/issues/2640 +process.on('unhandledRejection', (reason: string) => { throw reason; }); + +before(async function () { + this.timeout(60000); + await init(); +}); + + +export const generateJWTToken = () => { + const jwt = new SignJWT({ + sub: 'admin', + jti: '123', + exp: Math.floor(Date.now() / 1000) + 60 * 60, + aud: 'account', + iss: 'http://localhost:9001', + admin: true + }) + jwt.setProtectedHeader({alg: 'RS256'}) + return jwt.sign(privateKeyExported!) +} + + +export const generateJWTTokenUser = () => { + const jwt = new SignJWT({ + sub: 'admin', + jti: '123', + exp: Math.floor(Date.now() / 1000) + 60 * 60, + aud: 'account', + iss: 'http://localhost:9001', + }) + jwt.setProtectedHeader({alg: 'RS256'}) + return jwt.sign(privateKeyExported!) +} + +export const init = async function () { + if (agentPromise != null) return await agentPromise; + let agentResolve; + agentPromise = new Promise((resolve) => { agentResolve = resolve; }); + + if (!logLevel.isLessThanOrEqualTo(log4js.levels.DEBUG)) { + logger.warn('Disabling non-test logging for the duration of the test. ' + + 'To enable non-test logging, change the loglevel setting to DEBUG.'); + } + + // Note: This is only a shallow backup. + backups.settings = Object.assign({}, settings); + // Start the Etherpad server on a random unused port. + settings.port = 0; + settings.ip = 'localhost'; + settings.importExportRateLimiting = {max: 999999}; + settings.commitRateLimiting = {duration: 0.001, points: 1e6}; + httpServer = await server.start(); + // @ts-ignore + baseUrl = `http://localhost:${httpServer!.address()!.port}`; + logger.debug(`HTTP server at ${baseUrl}`); + // Create a supertest user agent for the HTTP server. + agent = supertest(baseUrl) + //.set('Authorization', `Bearer ${await generateJWTToken()}`); + // Speed up authn tests. + backups.authnFailureDelayMs = webaccess.authnFailureDelayMs; + webaccess.authnFailureDelayMs = 0; + + after(async function () { + webaccess.authnFailureDelayMs = backups.authnFailureDelayMs; + // Note: This does not unset settings that were added. + Object.assign(settings, backups.settings); + await server.exit(); + }); + + agentResolve!(agent); + return agent; +}; + +/** + * Waits for the next named socket.io event. Rejects if there is an error event while waiting + * (unless waiting for that error event). + * + * @param {io.Socket} socket - The socket.io Socket object to listen on. + * @param {string} event - The socket.io Socket event to listen for. + * @returns The argument(s) passed to the event handler. + */ +export const waitForSocketEvent = async (socket: any, event:string) => { + const errorEvents = [ + 'error', + 'connect_error', + 'connect_timeout', + 'reconnect_error', + 'reconnect_failed', + ]; + const handlers = new Map(); + let cancelTimeout; + try { + const timeoutP = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + reject(new Error(`timed out waiting for ${event} event`)); + cancelTimeout = () => {}; + }, 1000); + cancelTimeout = () => { + clearTimeout(timeout); + resolve(); + cancelTimeout = () => {}; + }; + }); + const errorEventP = Promise.race(errorEvents.map((event) => new Promise((resolve, reject) => { + handlers.set(event, (errorString:string) => { + logger.debug(`socket.io ${event} event: ${errorString}`); + reject(new Error(errorString)); + }); + }))); + const eventP = new Promise((resolve) => { + // This will overwrite one of the above handlers if the user is waiting for an error event. + handlers.set(event, (...args:string[]) => { + logger.debug(`socket.io ${event} event`); + if (args.length > 1) return resolve(args); + resolve(args[0]); + }); + }); + for (const [event, handler] of handlers) socket.on(event, handler); + // timeoutP and errorEventP are guaranteed to never resolve here (they can only reject), so the + // Promise returned by Promise.race() is guaranteed to resolve to the eventP value (if + // the event arrives). + return await Promise.race([timeoutP, errorEventP, eventP]); + } finally { + cancelTimeout!(); + for (const [event, handler] of handlers) socket.off(event, handler); + } +}; + +/** + * Establishes a new socket.io connection. + * + * @param {object} [res] - Optional HTTP response object. The cookies from this response's + * `set-cookie` header(s) are passed to the server when opening the socket.io connection. If + * nullish, no cookies are passed to the server. + * @returns {io.Socket} A socket.io client Socket object. + */ +export const connect = async (res:any = null) => { + // Convert the `set-cookie` header(s) into a `cookie` header. + const resCookies = (res == null) ? {} : setCookieParser.parse(res, {map: true}); + const reqCookieHdr = Object.entries(resCookies).map( + // @ts-ignore + ([name, cookie]) => `${name}=${encodeURIComponent(cookie.value)}`).join('; '); + + logger.debug('socket.io connecting...'); + let padId = null; + if (res) { + padId = res.req.path.split('/p/')[1]; + } + const socket = io(`${baseUrl}/`, { + forceNew: true, // Different tests will have different query parameters. + // socketio.js-client on node.js doesn't support cookies (see https://git.io/JU8u9), so the + // express_sid cookie must be passed as a query parameter. + query: {cookie: reqCookieHdr, padId}, + }); + try { + await waitForSocketEvent(socket, 'connect'); + } catch (e) { + socket.close(); + throw e; + } + logger.debug('socket.io connected'); + + return socket; +}; + +/** + * Helper function to exchange CLIENT_READY+CLIENT_VARS messages for the named pad. + * + * @param {io.Socket} socket - Connected socket.io Socket object. + * @param {string} padId - Which pad to join. + * @param token + * @returns The CLIENT_VARS message from the server. + */ +export const handshake = async (socket: any, padId:string, token = padutils.generateAuthorToken()) => { + logger.debug('sending CLIENT_READY...'); + socket.emit('message', { + component: 'pad', + type: 'CLIENT_READY', + padId, + sessionID: null, + token, + }); + logger.debug('waiting for CLIENT_VARS response...'); + const msg = await waitForSocketEvent(socket, 'message'); + logger.debug('received CLIENT_VARS message'); + return msg; +}; + +/** + * Convenience wrapper around `socket.send()` that waits for acknowledgement. + */ +export const sendMessage = async (socket: any, message:any) => await new Promise((resolve, reject) => { + socket.emit('message', message, (errInfo:{ + name: string, + message: string, + }) => { + if (errInfo != null) { + const {name, message} = errInfo; + const err = new Error(message); + err.name = name; + reject(err); + return; + } + resolve(); + }); +}); + +/** + * Convenience function to send a USER_CHANGES message. Waits for acknowledgement. + */ +export const sendUserChanges = async (socket:any, data:any) => await sendMessage(socket, { + type: 'COLLABROOM', + component: 'pad', + data: { + type: 'USER_CHANGES', + apool: new AttributePool(), + ...data, + }, +}); + + +/* + * Convenience function to send a delete pad request. + */ +export const sendPadDelete = async (socket:any, data:any) => await sendMessage(socket, { + type: 'PAD_DELETE', + component: 'pad', + data: { + padId: data.padId + }, +}); + + +/** + * Convenience function that waits for an ACCEPT_COMMIT message. Asserts that the new revision + * matches the expected revision. + * + * Note: To avoid a race condition, this should be called before the USER_CHANGES message is sent. + * For example: + * + * await Promise.all([ + * common.waitForAcceptCommit(socket, rev + 1), + * common.sendUserChanges(socket, {baseRev: rev, changeset}), + * ]); + */ +export const waitForAcceptCommit = async (socket:any, wantRev: number) => { + const msg = await waitForSocketEvent(socket, 'message'); + assert.deepEqual(msg, { + type: 'COLLABROOM', + data: { + type: 'ACCEPT_COMMIT', + newRev: wantRev, + }, + }); +}; + +const alphabet = 'abcdefghijklmnopqrstuvwxyz'; + +/** + * Generates a random string. + * + * @param {number} [len] - The desired length of the generated string. + * @param {string} [charset] - Characters to pick from. + * @returns {string} + */ +export const randomString = (len: number = 10, charset: string = `${alphabet}${alphabet.toUpperCase()}0123456789`): string => { + let ret = ''; + while (ret.length < len) ret += charset[Math.floor(Math.random() * charset.length)]; + return ret; +}; diff --git a/src/tests/backend/fuzzImportTest.ts b/src/tests/backend/fuzzImportTest.ts new file mode 100644 index 000000000..5b959bbc2 --- /dev/null +++ b/src/tests/backend/fuzzImportTest.ts @@ -0,0 +1,72 @@ +/* + * Fuzz testing the import endpoint + * Usage: node fuzzImportTest.js + */ +const settings = require('../container/loadSettings').loadSettings(); +const common = require('./common'); +const host = `http://${settings.ip}:${settings.port}`; +const froth = require('mocha-froth'); +const axios = require('axios'); +const apiVersion = 1; +const testPadId = `TEST_fuzz${makeid()}`; + +const endPoint = function (point: string, version?:number) { + version = version || apiVersion; + return `/api/${version}/${point}}`; +}; + +console.log('Testing against padID', testPadId); +console.log(`To watch the test live visit ${host}/p/${testPadId}`); +console.log('Tests will start in 5 seconds, click the URL now!'); + +setTimeout(() => { + for (let i = 1; i < 1000000; i++) { // 1M runs + setTimeout(async () => { + await runTest(i); + }, i * 100); // 100 ms + } +}, 5000); // wait 5 seconds + +async function runTest(number: number) { + await axios + .get(`${host + endPoint('createPad')}?padID=${testPadId}`, { + headers: { + Authorization: await common.generateJWTToken(), + } + }) + .then(() => { + const req = axios.post(`${host}/p/${testPadId}/import`) + .then(() => { + console.log('Success'); + let fN = '/test.txt'; + let cT = 'text/plain'; + + // To be more aggressive every other test we mess with Etherpad + // We provide a weird file name and also set a weird contentType + if (number % 2 == 0) { + fN = froth().toString(); + cT = froth().toString(); + } + + const form = req.form(); + form.append('file', froth().toString(), { + filename: fN, + contentType: cT, + }); + }); + }) + .catch((err:any) => { + // @ts-ignore + throw new Error('FAILURE', err); + }) +} + +function makeid() { + let text = ''; + const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + + for (let i = 0; i < 5; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; +} diff --git a/src/tests/backend/specs/ExportEtherpad.ts b/src/tests/backend/specs/ExportEtherpad.ts new file mode 100644 index 000000000..677890cbb --- /dev/null +++ b/src/tests/backend/specs/ExportEtherpad.ts @@ -0,0 +1,67 @@ +'use strict'; + +const assert = require('assert').strict; +const common = require('../common'); +const exportEtherpad = require('../../../node/utils/ExportEtherpad'); +const padManager = require('../../../node/db/PadManager'); +const plugins = require('../../../static/js/pluginfw/plugin_defs'); +const readOnlyManager = require('../../../node/db/ReadOnlyManager'); + +describe(__filename, function () { + let padId:string; + + beforeEach(async function () { + padId = common.randomString(); + assert(!await padManager.doesPadExist(padId)); + }); + + describe('exportEtherpadAdditionalContent', function () { + let hookBackup: ()=>void; + + before(async function () { + hookBackup = plugins.hooks.exportEtherpadAdditionalContent || []; + plugins.hooks.exportEtherpadAdditionalContent = [{hook_fn: () => ['custom']}]; + }); + + after(async function () { + plugins.hooks.exportEtherpadAdditionalContent = hookBackup; + }); + + it('exports custom records', async function () { + const pad = await padManager.getPad(padId); + await pad.db.set(`custom:${padId}`, 'a'); + await pad.db.set(`custom:${padId}:`, 'b'); + await pad.db.set(`custom:${padId}:foo`, 'c'); + const data = await exportEtherpad.getPadRaw(pad.id, null); + assert.equal(data[`custom:${padId}`], 'a'); + assert.equal(data[`custom:${padId}:`], 'b'); + assert.equal(data[`custom:${padId}:foo`], 'c'); + }); + + it('export from read-only pad uses read-only ID', async function () { + const pad = await padManager.getPad(padId); + const readOnlyId = await readOnlyManager.getReadOnlyId(padId); + await pad.db.set(`custom:${padId}`, 'a'); + await pad.db.set(`custom:${padId}:`, 'b'); + await pad.db.set(`custom:${padId}:foo`, 'c'); + const data = await exportEtherpad.getPadRaw(padId, readOnlyId); + assert.equal(data[`custom:${readOnlyId}`], 'a'); + assert.equal(data[`custom:${readOnlyId}:`], 'b'); + assert.equal(data[`custom:${readOnlyId}:foo`], 'c'); + assert(!(`custom:${padId}` in data)); + assert(!(`custom:${padId}:` in data)); + assert(!(`custom:${padId}:foo` in data)); + }); + + it('does not export records from pad with similar ID', async function () { + const pad = await padManager.getPad(padId); + await pad.db.set(`custom:${padId}x`, 'a'); + await pad.db.set(`custom:${padId}x:`, 'b'); + await pad.db.set(`custom:${padId}x:foo`, 'c'); + const data = await exportEtherpad.getPadRaw(pad.id, null); + assert(!(`custom:${padId}x` in data)); + assert(!(`custom:${padId}x:` in data)); + assert(!(`custom:${padId}x:foo` in data)); + }); + }); +}); diff --git a/src/tests/backend/specs/ImportEtherpad.ts b/src/tests/backend/specs/ImportEtherpad.ts new file mode 100644 index 000000000..b9ac9baaf --- /dev/null +++ b/src/tests/backend/specs/ImportEtherpad.ts @@ -0,0 +1,210 @@ +'use strict'; + +import {MapArrayType} from "../../../node/types/MapType"; + +const assert = require('assert').strict; +const authorManager = require('../../../node/db/AuthorManager'); +const db = require('../../../node/db/DB'); +const importEtherpad = require('../../../node/utils/ImportEtherpad'); +const padManager = require('../../../node/db/PadManager'); +const plugins = require('../../../static/js/pluginfw/plugin_defs'); +import {randomString} from '../../../static/js/pad_utils'; + +describe(__filename, function () { + let padId: string; + + const makeAuthorId = () => `a.${randomString(16)}`; + + const makeExport = (authorId: string) => ({ + 'pad:testing': { + atext: { + text: 'foo\n', + attribs: '|1+4', + }, + pool: { + numToAttrib: {}, + nextNum: 0, + }, + head: 0, + savedRevisions: [], + }, + [`globalAuthor:${authorId}`]: { + colorId: '#000000', + name: 'new', + timestamp: 1598747784631, + padIDs: 'testing', + }, + 'pad:testing:revs:0': { + changeset: 'Z:1>3+3$foo', + meta: { + author: '', + timestamp: 1597632398288, + pool: { + numToAttrib: {}, + nextNum: 0, + }, + atext: { + text: 'foo\n', + attribs: '|1+4', + }, + }, + }, + }); + + beforeEach(async function () { + padId = randomString(10); + assert(!await padManager.doesPadExist(padId)); + }); + + it('unknown db records are ignored', async function () { + const badKey = `maliciousDbKey${randomString(10)}`; + await importEtherpad.setPadRaw(padId, JSON.stringify({ + [badKey]: 'value', + ...makeExport(makeAuthorId()), + })); + assert(await db.get(badKey) == null); + }); + + it('changes are all or nothing', async function () { + const authorId = makeAuthorId(); + const data:MapArrayType = makeExport(authorId); + data['pad:differentPadId:revs:0'] = data['pad:testing:revs:0']; + delete data['pad:testing:revs:0']; + assert.rejects(importEtherpad.setPadRaw(padId, JSON.stringify(data)), /unexpected pad ID/); + assert(!await authorManager.doesAuthorExist(authorId)); + assert(!await padManager.doesPadExist(padId)); + }); + + describe('author pad IDs', function () { + let existingAuthorId: string; + let newAuthorId:string; + + beforeEach(async function () { + existingAuthorId = (await authorManager.createAuthor('existing')).authorID; + assert(await authorManager.doesAuthorExist(existingAuthorId)); + assert.deepEqual((await authorManager.listPadsOfAuthor(existingAuthorId)).padIDs, []); + newAuthorId = makeAuthorId(); + assert.notEqual(newAuthorId, existingAuthorId); + assert(!await authorManager.doesAuthorExist(newAuthorId)); + }); + + it('author does not yet exist', async function () { + await importEtherpad.setPadRaw(padId, JSON.stringify(makeExport(newAuthorId))); + assert(await authorManager.doesAuthorExist(newAuthorId)); + const author = await authorManager.getAuthor(newAuthorId); + assert.equal(author.name, 'new'); + assert.equal(author.colorId, '#000000'); + assert.deepEqual((await authorManager.listPadsOfAuthor(newAuthorId)).padIDs, [padId]); + }); + + it('author already exists, no pads', async function () { + newAuthorId = existingAuthorId; + await importEtherpad.setPadRaw(padId, JSON.stringify(makeExport(newAuthorId))); + assert(await authorManager.doesAuthorExist(newAuthorId)); + const author = await authorManager.getAuthor(newAuthorId); + assert.equal(author.name, 'existing'); + assert.notEqual(author.colorId, '#000000'); + assert.deepEqual((await authorManager.listPadsOfAuthor(newAuthorId)).padIDs, [padId]); + }); + + it('author already exists, on different pad', async function () { + const otherPadId = randomString(10); + await authorManager.addPad(existingAuthorId, otherPadId); + newAuthorId = existingAuthorId; + await importEtherpad.setPadRaw(padId, JSON.stringify(makeExport(newAuthorId))); + assert(await authorManager.doesAuthorExist(newAuthorId)); + const author = await authorManager.getAuthor(newAuthorId); + assert.equal(author.name, 'existing'); + assert.notEqual(author.colorId, '#000000'); + assert.deepEqual( + (await authorManager.listPadsOfAuthor(newAuthorId)).padIDs.sort(), + [otherPadId, padId].sort()); + }); + + it('author already exists, on same pad', async function () { + await authorManager.addPad(existingAuthorId, padId); + newAuthorId = existingAuthorId; + await importEtherpad.setPadRaw(padId, JSON.stringify(makeExport(newAuthorId))); + assert(await authorManager.doesAuthorExist(newAuthorId)); + const author = await authorManager.getAuthor(newAuthorId); + assert.equal(author.name, 'existing'); + assert.notEqual(author.colorId, '#000000'); + assert.deepEqual((await authorManager.listPadsOfAuthor(newAuthorId)).padIDs, [padId]); + }); + }); + + describe('enforces consistent pad ID', function () { + it('pad record has different pad ID', async function () { + const data:MapArrayType = makeExport(makeAuthorId()); + data['pad:differentPadId'] = data['pad:testing']; + delete data['pad:testing']; + assert.rejects(importEtherpad.setPadRaw(padId, JSON.stringify(data)), /unexpected pad ID/); + }); + + it('globalAuthor record has different pad ID', async function () { + const authorId = makeAuthorId(); + const data = makeExport(authorId); + data[`globalAuthor:${authorId}`].padIDs = 'differentPadId'; + assert.rejects(importEtherpad.setPadRaw(padId, JSON.stringify(data)), /unexpected pad ID/); + }); + + it('pad rev record has different pad ID', async function () { + const data:MapArrayType = makeExport(makeAuthorId()); + data['pad:differentPadId:revs:0'] = data['pad:testing:revs:0']; + delete data['pad:testing:revs:0']; + assert.rejects(importEtherpad.setPadRaw(padId, JSON.stringify(data)), /unexpected pad ID/); + }); + }); + + describe('order of records does not matter', function () { + for (const perm of [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]) { + it(JSON.stringify(perm), async function () { + const authorId = makeAuthorId(); + const records = Object.entries(makeExport(authorId)); + assert.equal(records.length, 3); + await importEtherpad.setPadRaw( + padId, JSON.stringify(Object.fromEntries(perm.map((i) => records[i])))); + assert.deepEqual((await authorManager.listPadsOfAuthor(authorId)).padIDs, [padId]); + const pad = await padManager.getPad(padId); + assert.equal(pad.text(), 'foo\n'); + }); + } + }); + + describe('exportEtherpadAdditionalContent', function () { + let hookBackup: Function; + + before(async function () { + hookBackup = plugins.hooks.exportEtherpadAdditionalContent || []; + plugins.hooks.exportEtherpadAdditionalContent = [{hook_fn: () => ['custom']}]; + }); + + after(async function () { + plugins.hooks.exportEtherpadAdditionalContent = hookBackup; + }); + + it('imports from custom prefix', async function () { + await importEtherpad.setPadRaw(padId, JSON.stringify({ + ...makeExport(makeAuthorId()), + 'custom:testing': 'a', + 'custom:testing:foo': 'b', + })); + const pad = await padManager.getPad(padId); + assert.equal(await pad.db.get(`custom:${padId}`), 'a'); + assert.equal(await pad.db.get(`custom:${padId}:foo`), 'b'); + }); + + it('rejects records for pad with similar ID', async function () { + await assert.rejects(importEtherpad.setPadRaw(padId, JSON.stringify({ + ...makeExport(makeAuthorId()), + 'custom:testingx': 'x', + })), /unexpected pad ID/); + assert(await db.get(`custom:${padId}x`) == null); + await assert.rejects(importEtherpad.setPadRaw(padId, JSON.stringify({ + ...makeExport(makeAuthorId()), + 'custom:testingx:foo': 'x', + })), /unexpected pad ID/); + assert(await db.get(`custom:${padId}x:foo`) == null); + }); + }); +}); diff --git a/src/tests/backend/specs/Pad.ts b/src/tests/backend/specs/Pad.ts new file mode 100644 index 000000000..b77bdf672 --- /dev/null +++ b/src/tests/backend/specs/Pad.ts @@ -0,0 +1,143 @@ +'use strict'; + +import {PadType} from "../../../node/types/PadType"; + +const Pad = require('../../../node/db/Pad'); +import { strict as assert } from 'assert'; +import {MapArrayType} from "../../../node/types/MapType"; +const authorManager = require('../../../node/db/AuthorManager'); +const common = require('../common'); +const padManager = require('../../../node/db/PadManager'); +const plugins = require('../../../static/js/pluginfw/plugin_defs'); +const settings = require('../../../node/utils/Settings'); + +describe(__filename, function () { + const backups:MapArrayType = {}; + let pad: PadType|null; + let padId: string; + + before(async function () { + backups.hooks = { + padDefaultContent: plugins.hooks.padDefaultContent, + }; + backups.defaultPadText = settings.defaultPadText; + }); + + beforeEach(async function () { + backups.hooks.padDefaultContent = []; + padId = common.randomString(); + assert(!(await padManager.doesPadExist(padId))); + }); + + afterEach(async function () { + Object.assign(plugins.hooks, backups.hooks); + if (pad != null) await pad.remove(); + pad = null; + }); + + describe('cleanText', function () { + const testCases = [ + ['', ''], + ['\n', '\n'], + ['x', 'x'], + ['x\n', 'x\n'], + ['x\ny\n', 'x\ny\n'], + ['x\ry\n', 'x\ny\n'], + ['x\r\ny\n', 'x\ny\n'], + ['x\r\r\ny\n', 'x\n\ny\n'], + ]; + for (const [input, want] of testCases) { + it(`${JSON.stringify(input)} -> ${JSON.stringify(want)}`, async function () { + assert.equal(Pad.cleanText(input), want); + }); + } + }); + + describe('padDefaultContent hook', function () { + it('runs when a pad is created without specific text', async function () { + const p = new Promise((resolve) => { + plugins.hooks.padDefaultContent.push({hook_fn: () => resolve()}); + }); + pad = await padManager.getPad(padId); + await p; + }); + + it('not run if pad is created with specific text', async function () { + plugins.hooks.padDefaultContent.push( + {hook_fn: () => { throw new Error('should not be called'); }}); + pad = await padManager.getPad(padId, ''); + }); + + it('defaults to settings.defaultPadText', async function () { + const p = new Promise((resolve, reject) => { + plugins.hooks.padDefaultContent.push({hook_fn: async (hookName:string, ctx:any) => { + try { + assert.equal(ctx.type, 'text'); + assert.equal(ctx.content, settings.defaultPadText); + } catch (err) { + return reject(err); + } + resolve(); + }}); + }); + pad = await padManager.getPad(padId); + await p; + }); + + it('passes the pad object', async function () { + const gotP = new Promise((resolve) => { + plugins.hooks.padDefaultContent.push({hook_fn: async (hookName:string, {pad}:{ + pad: PadType, + }) => resolve(pad)}); + }); + pad = await padManager.getPad(padId); + assert.equal(await gotP, pad); + }); + + it('passes empty authorId if not provided', async function () { + const gotP = new Promise((resolve) => { + plugins.hooks.padDefaultContent.push( + {hook_fn: async (hookName:string, {authorId}:{ + authorId: string, + }) => resolve(authorId)}); + }); + pad = await padManager.getPad(padId); + assert.equal(await gotP, ''); + }); + + it('passes provided authorId', async function () { + const want = await authorManager.getAuthor4Token(`t.${padId}`); + const gotP = new Promise((resolve) => { + plugins.hooks.padDefaultContent.push( + {hook_fn: async (hookName: string, {authorId}:{ + authorId: string, + }) => resolve(authorId)}); + }); + pad = await padManager.getPad(padId, null, want); + assert.equal(await gotP, want); + }); + + it('uses provided content', async function () { + const want = 'hello world'; + assert.notEqual(want, settings.defaultPadText); + plugins.hooks.padDefaultContent.push({hook_fn: async (hookName:string, ctx:any) => { + ctx.type = 'text'; + ctx.content = want; + }}); + pad = await padManager.getPad(padId); + assert.equal(pad!.text(), `${want}\n`); + }); + + it('cleans provided content', async function () { + const input = 'foo\r\nbar\r\tbaz'; + const want = 'foo\nbar\n baz'; + assert.notEqual(want, settings.defaultPadText); + plugins.hooks.padDefaultContent.push({hook_fn: async (hookName:string, ctx:any) => { + ctx.type = 'text'; + ctx.content = input; + }}); + pad = await padManager.getPad(padId); + assert.equal(pad!.text(), `${want}\n`); + }); + }); +}); diff --git a/src/tests/backend/specs/SecretRotator.ts b/src/tests/backend/specs/SecretRotator.ts new file mode 100644 index 000000000..d95b6dba1 --- /dev/null +++ b/src/tests/backend/specs/SecretRotator.ts @@ -0,0 +1,561 @@ +'use strict'; + +import {strict} from "assert"; +const common = require('../common'); +const crypto = require('../../../node/security/crypto'); +const db = require('../../../node/db/DB'); +const SecretRotator = require("../../../node/security/SecretRotator").SecretRotator; + +const logger = common.logger; + +// Greatest common divisor. +const gcd: Function = (...args:number[]) => ( + args.length === 1 ? args[0] + : args.length === 2 ? ((args[1]) ? gcd(args[1], args[0] % args[1]) : Math.abs(args[0])) + : gcd(args[0], gcd(...args.slice(1)))); + +// Least common multiple. +const lcm:Function = (...args: number[]) => ( + args.length === 1 ? args[0] + : args.length === 2 ? Math.abs(args[0] * args[1]) / gcd(...args) + : lcm(args[0], lcm(...args.slice(1)))); + +class FakeClock { + _now: number; + _nextId: number; + _idle: Promise; + timeouts: Map; + + constructor() { + logger.debug('new fake clock'); + this._now = 0; + this._nextId = 1; + this._idle = Promise.resolve(); + this.timeouts = new Map(); + } + + _next() { return Math.min(...[...this.timeouts.values()].map((x) => x.when)); } + async setNow(t: number) { + logger.debug(`setting fake time to ${t}`); + strict(t >= this._now); + strict(t < Infinity); + let n; + while ((n = this._next()) <= t) { + this._now = Math.max(this._now, Math.min(n, t)); + logger.debug(`fake time set to ${this._now}; firing timeouts...`); + await this._fire(); + } + this._now = t; + logger.debug(`fake time set to ${this._now}`); + } + async advance(t: number) { await this.setNow(this._now + t); } + async advanceToNext() { + const n = this._next(); + if (n < this._now) await this._fire(); + else if (n < Infinity) await this.setNow(n); + } + async _fire() { + // This method MUST NOT execute any of the setTimeout callbacks synchronously, otherwise + // fc.setTimeout(fn, 0) would execute fn before fc.setTimeout() returns. Fortunately, the + // ECMAScript standard guarantees that a function passed to Promise.prototype.then() will run + // asynchronously. + this._idle = this._idle.then(() => Promise.all( + [...this.timeouts.values()] + .filter(({when}) => when <= this._now) + .sort((a, b) => a.when - b.when) + .map(async ({id, fn}) => { + this.clearTimeout(id); + // With the standard setTimeout(), the callback function's return value is ignored. + // Here we await the return value so that test code can block until timeout work is + // done. + await fn(); + }))); + await this._idle; + } + + get now() { return this._now; } + setTimeout(fn:Function, wait = 0) { + const when = this._now + wait; + const id = this._nextId++; + this.timeouts.set(id, {id, fn, when}); + this._fire(); + return id; + } + clearTimeout(id:number) { this.timeouts.delete(id); } +} + +// In JavaScript, the % operator is remainder, not modulus. +const mod = (a: number, n:number) => ((a % n) + n) % n; + +describe(__filename, function () { + let dbPrefix: string; + let sr: any; + let interval = 1e3; + const lifetime = 1e4; + const intervalStart = (t: number) => t - mod(t, interval); + const hkdf = async (secret: string, salt:string, tN:number) => Buffer.from( + await crypto.hkdf('sha256', secret, salt, `${tN}`, 32)).toString('hex'); + + const newRotator = (s:string|null = null) => new SecretRotator(dbPrefix, interval, lifetime, s); + + const setFakeClock = (sr: { _t: { now: () => number; setTimeout: (fn: Function, wait?: number) => number; clearTimeout: (id: number) => void; }; }, fc:FakeClock|null = null) => { + if (fc == null) fc = new FakeClock(); + sr._t = { + now: () => fc!.now, + setTimeout: fc.setTimeout.bind(fc), + clearTimeout: fc.clearTimeout.bind(fc), + }; + return fc; + }; + + before(async function () { + await common.init(); + }); + + beforeEach(async function () { + dbPrefix = `test-SecretRotator-${common.randomString()}`; + interval = 1e3; + }); + + afterEach(async function () { + if (sr != null) sr.stop(); + sr = null; + await Promise.all( + (await db.findKeys(`${dbPrefix}:*`, null)).map(async (dbKey: string) => await db.remove(dbKey))); + }); + + describe('constructor', function () { + it('creates empty secrets array', async function () { + sr = newRotator(); + strict.deepEqual(sr.secrets, []); + }); + + for (const invalidChar of '*:%') { + it(`rejects database prefixes containing ${invalidChar}`, async function () { + dbPrefix += invalidChar; + strict.throws(newRotator, /invalid char/); + }); + } + }); + + describe('start', function () { + it('does not replace secrets array', async function () { + sr = newRotator(); + setFakeClock(sr); + const {secrets} = sr; + await sr.start(); + strict.equal(sr.secrets, secrets); + }); + + it('derives secrets', async function () { + sr = newRotator(); + setFakeClock(sr); + await sr.start(); + strict.equal(sr.secrets.length, 3); // Current (active), previous, and next. + for (const s of sr.secrets) { + strict.equal(typeof s, 'string'); + strict(s); + } + strict.equal(new Set(sr.secrets).size, sr.secrets.length); // The secrets should all differ. + }); + + it('publishes params', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + const dbKeys = await db.findKeys(`${dbPrefix}:*`, null); + strict.equal(dbKeys.length, 1); + const [id] = dbKeys; + strict(id.startsWith(`${dbPrefix}:`)); + strict.notEqual(id.slice(dbPrefix.length + 1), ''); + const p = await db.get(id); + const {secret, salt} = p.algParams; + strict.deepEqual(p, { + algId: 1, + algParams: { + digest: 'sha256', + keyLen: 32, + salt, + secret, + }, + start: fc.now, + end: fc.now + (2 * interval), + interval, + lifetime, + }); + strict.equal(typeof salt, 'string'); + strict.match(salt, /^[0-9a-f]{64}$/); + strict.equal(typeof secret, 'string'); + strict.match(secret, /^[0-9a-f]{64}$/); + strict.deepEqual(sr.secrets, await Promise.all( + [0, -interval, interval].map(async (tN) => await hkdf(secret, salt, tN)))); + }); + + it('reuses matching publication if unexpired', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + const {secrets} = sr; + const dbKeys = await db.findKeys(`${dbPrefix}:*`, null); + sr.stop(); + sr = newRotator(); + setFakeClock(sr, fc); + await sr.start(); + strict.deepEqual(sr.secrets, secrets); + strict.deepEqual(await db.findKeys(`${dbPrefix}:*`, null), dbKeys); + }); + + it('deletes expired publications', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + const [oldId] = await db.findKeys(`${dbPrefix}:*`, null); + strict(oldId != null); + sr.stop(); + const p = await db.get(oldId); + await fc.setNow(p.end + p.lifetime + p.interval); + sr = newRotator(); + setFakeClock(sr, fc); + await sr.start(); + const ids = await db.findKeys(`${dbPrefix}:*`, null); + strict.equal(ids.length, 1); + const [newId] = ids; + strict.notEqual(newId, oldId); + }); + + it('keeps expired publications until interval past expiration', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + const [, , future] = sr.secrets; + sr.stop(); + const [origId] = await db.findKeys(`${dbPrefix}:*`, null); + const p = await db.get(origId); + await fc.advance(p.end + p.lifetime + p.interval - 1); + sr = newRotator(); + setFakeClock(sr, fc); + await sr.start(); + strict(sr.secrets.slice(1).includes(future)); + // It should have created a new publication, not extended the life of the old publication. + strict.equal((await db.findKeys(`${dbPrefix}:*`, null)).length, 2); + strict.deepEqual(await db.get(origId), p); + }); + + it('idempotent', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + strict.equal(fc.timeouts.size, 1); + const secrets = [...sr.secrets]; + const dbKeys = await db.findKeys(`${dbPrefix}:*`, null); + await sr.start(); + strict.equal(fc.timeouts.size, 1); + strict.deepEqual(sr.secrets, secrets); + strict.deepEqual(await db.findKeys(`${dbPrefix}:*`, null), dbKeys); + }); + + describe(`schedules update at next interval (= ${interval})`, function () { + const testCases = [ + {now: 0, want: interval}, + {now: 1, want: interval}, + {now: interval - 1, want: interval}, + {now: interval, want: 2 * interval}, + {now: interval + 1, want: 2 * interval}, + ]; + for (const {now, want} of testCases) { + it(`${now} -> ${want}`, async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await fc.setNow(now); + await sr.start(); + strict.equal(fc.timeouts.size, 1); + const [{when}] = fc.timeouts.values(); + strict.equal(when, want); + }); + } + + it('multiple active params with different intervals', async function () { + const intervals = [400, 600, 1000]; + const lcmi = lcm(...intervals); + const wants:Set = new Set(); + for (const i of intervals) for (let t = i; t <= lcmi; t += i) wants.add(t); + const fcs = new FakeClock(); + const srs = intervals.map((i) => { + interval = i; + const sr = newRotator(); + setFakeClock(sr, fcs); + return sr; + }); + try { + for (const sr of srs) await sr.start(); // Don't use Promise.all() otherwise they race. + interval = intervals[intervals.length - 1]; + sr = newRotator(); + const fc = setFakeClock(sr); // Independent clock to test a single instance's behavior. + await sr.start(); + for (const want of [...wants].sort((a, b) => a - b)) { + logger.debug(`next timeout should be at ${want}`); + await fc.advanceToNext(); + await fcs.setNow(fc.now); // Keep all of the publications alive. + strict.equal(fc.now, want); + } + } finally { + for (const sr of srs) sr.stop(); + } + }); + }); + }); + + describe('stop', function () { + it('clears timeout', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + strict.notEqual(fc.timeouts.size, 0); + sr.stop(); + strict.equal(fc.timeouts.size, 0); + }); + + it('safe to call multiple times', async function () { + sr = newRotator(); + setFakeClock(sr); + await sr.start(); + sr.stop(); + sr.stop(); + }); + }); + + describe('legacy secret', function () { + it('ends at now if there are no previously published secrets', async function () { + sr = newRotator('legacy'); + const fc = setFakeClock(sr); + // Use a time that isn't a multiple of interval in case there is a modular arithmetic bug that + // would otherwise go undetected. + await fc.setNow(1); + strict(mod(fc.now, interval) !== 0); + await sr.start(); + strict.equal(sr.secrets.length, 4); // 1 for the legacy secret, 3 for past, current, future + strict(sr.secrets.slice(1).includes('legacy')); // Should not be the current secret. + const ids = await db.findKeys(`${dbPrefix}:*`, null); + const params = (await Promise.all(ids.map(async (id:string) => await db.get(id)))) + .sort((a, b) => a.algId - b.algId); + strict.deepEqual(params, [ + { + algId: 0, + algParams: 'legacy', + // The start time must equal the end time so that legacy secrets do not affect the end + // times of legacy secrets published by other instances. + start: fc.now, + end: fc.now, + lifetime, + interval: null, + }, + { + algId: 1, + algParams: params[1].algParams, + start: fc.now, + end: intervalStart(fc.now) + (2 * interval), + interval, + lifetime, + }, + ]); + }); + + it('ends at the start of the oldest previously published secret', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await fc.setNow(1); + strict(mod(fc.now, interval) !== 0); + const wantTime = fc.now; + await sr.start(); + strict.equal(sr.secrets.length, 3); + const [s1, s0, s2] = sr.secrets; // s1=current, s0=previous, s2=next + sr.stop(); + // Use a time that is not a multiple of interval off of epoch or wantTime just in case there + // is a modular arithmetic bug that would otherwise go undetected. + await fc.advance(interval + 1); + strict(mod(fc.now, interval) !== 0); + strict(mod(fc.now - wantTime, interval) !== 0); + sr = newRotator('legacy'); + setFakeClock(sr, fc); + await sr.start(); + strict.equal(sr.secrets.length, 5); // s0 through s3 and the legacy secret. + strict.deepEqual(sr.secrets, [s2, s1, s0, sr.secrets[3], 'legacy']); + const ids = await db.findKeys(`${dbPrefix}:*`, null); + const params = (await Promise.all(ids.map(async (id:string) => await db.get(id)))) + .sort((a, b) => a.algId - b.algId); + strict.deepEqual(params, [ + { + algId: 0, + algParams: 'legacy', + start: wantTime, + end: wantTime, + interval: null, + lifetime, + }, + { + algId: 1, + algParams: params[1].algParams, + start: wantTime, + end: intervalStart(fc.now) + (2 * interval), + interval, + lifetime, + }, + ]); + }); + + it('multiple instances with different legacy secrets', async function () { + sr = newRotator('legacy1'); + const fc = setFakeClock(sr); + await sr.start(); + sr.stop(); + sr = newRotator('legacy2'); + setFakeClock(sr, fc); + await sr.start(); + strict(sr.secrets.slice(1).includes('legacy1')); + strict(sr.secrets.slice(1).includes('legacy2')); + }); + + it('multiple instances with the same legacy secret', async function () { + sr = newRotator('legacy'); + const fc = setFakeClock(sr); + await sr.start(); + sr.stop(); + sr = newRotator('legacy'); + setFakeClock(sr, fc); + await sr.start(); + strict.deepEqual(sr.secrets, [...new Set(sr.secrets)]); + // There shouldn't be multiple publications for the same legacy secret. + strict.equal((await db.findKeys(`${dbPrefix}:*`, null)).length, 2); + }); + + it('legacy secret is included for interval after expiration', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + sr.stop(); + await fc.advance(lifetime + interval - 1); + sr = newRotator('legacy'); + setFakeClock(sr, fc); + await sr.start(); + strict(sr.secrets.slice(1).includes('legacy')); + }); + + it('legacy secret is not included if the oldest secret is old enough', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + sr.stop(); + await fc.advance(lifetime + interval); + sr = newRotator('legacy'); + setFakeClock(sr, fc); + await sr.start(); + strict(!sr.secrets.includes('legacy')); + }); + + it('dead secrets still affect legacy secret end time', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + const secrets = new Set(sr.secrets); + sr.stop(); + await fc.advance(lifetime + (3 * interval)); + sr = newRotator('legacy'); + setFakeClock(sr, fc); + await sr.start(); + strict(!sr.secrets.includes('legacy')); + strict(!sr.secrets.some((s:string) => secrets.has(s))); + }); + }); + + describe('rotation', function () { + it('no rotation before start of interval', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + strict.equal(fc.now, 0); + await sr.start(); + const secrets = [...sr.secrets]; + await fc.advance(interval - 1); + strict.deepEqual(sr.secrets, secrets); + }); + + it('does not replace secrets array', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + const [current] = sr.secrets; + const secrets = sr.secrets; + await fc.advance(interval); + strict.notEqual(sr.secrets[0], current); + strict.equal(sr.secrets, secrets); + }); + + it('future secret becomes current, new future is generated', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + const secrets = new Set(sr.secrets); + strict.equal(secrets.size, 3); + const [s1, s0, s2] = sr.secrets; + await fc.advance(interval); + strict.deepEqual(sr.secrets, [s2, s1, s0, sr.secrets[3]]); + strict(!secrets.has(sr.secrets[3])); + }); + + it('expired publications are deleted', async function () { + const origInterval = interval; + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + sr.stop(); + ++interval; // Force new params so that the old params can expire. + sr = newRotator(); + setFakeClock(sr, fc); + await sr.start(); + strict.equal((await db.findKeys(`${dbPrefix}:*`, null)).length, 2); + await fc.advance(lifetime + (3 * origInterval)); + strict.equal((await db.findKeys(`${dbPrefix}:*`, null)).length, 1); + }); + + it('old secrets are eventually removed', async function () { + sr = newRotator(); + const fc = setFakeClock(sr); + await sr.start(); + const [, s0] = sr.secrets; + await fc.advance(lifetime + interval - 1); + strict(sr.secrets.slice(1).includes(s0)); + await fc.advance(1); + strict(!sr.secrets.includes(s0)); + }); + }); + + describe('clock skew', function () { + it('out of sync works if in adjacent interval', async function () { + const srs = [newRotator(), newRotator()]; + const fcs = srs.map((sr) => setFakeClock(sr)); + for (const sr of srs) await sr.start(); // Don't use Promise.all() otherwise they race. + strict.deepEqual(srs[0].secrets, srs[1].secrets); + // Advance fcs[0] to the end of the interval after fcs[1]. + await fcs[0].advance((2 * interval) - 1); + strict(srs[0].secrets.includes(srs[1].secrets[0])); + strict(srs[1].secrets.includes(srs[0].secrets[0])); + // Advance both by an interval. + await Promise.all([fcs[1].advance(interval), fcs[0].advance(interval)]); + strict(srs[0].secrets.includes(srs[1].secrets[0])); + strict(srs[1].secrets.includes(srs[0].secrets[0])); + // Advance fcs[1] to the end of the interval after fcs[0]. + await Promise.all([fcs[1].advance((3 * interval) - 1), fcs[0].advance(1)]); + strict(srs[0].secrets.includes(srs[1].secrets[0])); + strict(srs[1].secrets.includes(srs[0].secrets[0])); + }); + + it('start up out of sync', async function () { + const srs = [newRotator(), newRotator()]; + const fcs = srs.map((sr) => setFakeClock(sr)); + await fcs[0].advance((2 * interval) - 1); + await srs[0].start(); // Must start before srs[1] so that srs[1] starts in srs[0]'s past. + await srs[1].start(); + strict(srs[0].secrets.includes(srs[1].secrets[0])); + strict(srs[1].secrets.includes(srs[0].secrets[0])); + }); + }); +}); diff --git a/src/tests/backend/specs/SessionStore.ts b/src/tests/backend/specs/SessionStore.ts new file mode 100644 index 000000000..5dfc44ff2 --- /dev/null +++ b/src/tests/backend/specs/SessionStore.ts @@ -0,0 +1,246 @@ +'use strict'; + +const SessionStore = require('../../../node/db/SessionStore'); +import {strict as assert} from 'assert'; +const common = require('../common'); +const db = require('../../../node/db/DB'); +import util from 'util'; + +type Session = { + set: (sid: string|null,sess:any, sess2:any) => void; + get: (sid:string|null) => any; + destroy: (sid:string|null) => void; + touch: (sid:string|null, sess:any, sess2:any) => void; + shutdown: () => void; +} + +describe(__filename, function () { + let ss: Session|null; + let sid: string|null; + + const set = async (sess: string|null) => await util.promisify(ss!.set).call(ss, sid, sess); + const get = async () => await util.promisify(ss!.get).call(ss, sid); + const destroy = async () => await util.promisify(ss!.destroy).call(ss, sid); + const touch = async (sess: Session) => await util.promisify(ss!.touch).call(ss, sid, sess); + + before(async function () { + await common.init(); + }); + + beforeEach(async function () { + ss = new SessionStore(); + sid = common.randomString(); + }); + + afterEach(async function () { + if (ss != null) { + if (sid != null) await destroy(); + ss.shutdown(); + } + sid = null; + ss = null; + }); + + describe('set', function () { + it('set of null is a no-op', async function () { + await set(null); + assert(await db.get(`sessionstorage:${sid}`) == null); + }); + + it('set of non-expiring session', async function () { + const sess:any = {foo: 'bar', baz: {asdf: 'jkl;'}}; + await set(sess); + assert.equal(JSON.stringify(await db.get(`sessionstorage:${sid}`)), JSON.stringify(sess)); + }); + + it('set of session that expires', async function () { + const sess:any = {foo: 'bar', cookie: {expires: new Date(Date.now() + 100)}}; + await set(sess); + assert.equal(JSON.stringify(await db.get(`sessionstorage:${sid}`)), JSON.stringify(sess)); + await new Promise((resolve) => setTimeout(resolve, 110)); + // Writing should start a timeout. + assert(await db.get(`sessionstorage:${sid}`) == null); + }); + + it('set of already expired session', async function () { + const sess:any = {foo: 'bar', cookie: {expires: new Date(1)}}; + await set(sess); + // No record should have been created. + assert(await db.get(`sessionstorage:${sid}`) == null); + }); + + it('switch from non-expiring to expiring', async function () { + const sess:any = {foo: 'bar'}; + await set(sess); + const sess2:any = {foo: 'bar', cookie: {expires: new Date(Date.now() + 100)}}; + await set(sess2); + await new Promise((resolve) => setTimeout(resolve, 110)); + assert(await db.get(`sessionstorage:${sid}`) == null); + }); + + it('switch from expiring to non-expiring', async function () { + const sess:any = {foo: 'bar', cookie: {expires: new Date(Date.now() + 100)}}; + await set(sess); + const sess2:any = {foo: 'bar'}; + await set(sess2); + await new Promise((resolve) => setTimeout(resolve, 110)); + assert.equal(JSON.stringify(await db.get(`sessionstorage:${sid}`)), JSON.stringify(sess2)); + }); + }); + + describe('get', function () { + it('get of non-existent entry', async function () { + assert(await get() == null); + }); + + it('set+get round trip', async function () { + const sess:any = {foo: 'bar', baz: {asdf: 'jkl;'}}; + await set(sess); + assert.equal(JSON.stringify(await get()), JSON.stringify(sess)); + }); + + it('get of record from previous run (no expiration)', async function () { + const sess = {foo: 'bar', baz: {asdf: 'jkl;'}}; + await db.set(`sessionstorage:${sid}`, sess); + assert.equal(JSON.stringify(await get()), JSON.stringify(sess)); + }); + + it('get of record from previous run (not yet expired)', async function () { + const sess = {foo: 'bar', cookie: {expires: new Date(Date.now() + 100)}}; + await db.set(`sessionstorage:${sid}`, sess); + assert.equal(JSON.stringify(await get()), JSON.stringify(sess)); + await new Promise((resolve) => setTimeout(resolve, 110)); + // Reading should start a timeout. + assert(await db.get(`sessionstorage:${sid}`) == null); + }); + + it('get of record from previous run (already expired)', async function () { + const sess = {foo: 'bar', cookie: {expires: new Date(1)}}; + await db.set(`sessionstorage:${sid}`, sess); + assert(await get() == null); + assert(await db.get(`sessionstorage:${sid}`) == null); + }); + + it('external expiration update is picked up', async function () { + const sess:any = {foo: 'bar', cookie: {expires: new Date(Date.now() + 100)}}; + await set(sess); + assert.equal(JSON.stringify(await get()), JSON.stringify(sess)); + const sess2 = {...sess, cookie: {expires: new Date(Date.now() + 200)}}; + await db.set(`sessionstorage:${sid}`, sess2); + assert.equal(JSON.stringify(await get()), JSON.stringify(sess2)); + await new Promise((resolve) => setTimeout(resolve, 110)); + // The original timeout should not have fired. + assert.equal(JSON.stringify(await get()), JSON.stringify(sess2)); + }); + }); + + describe('shutdown', function () { + it('shutdown cancels timeouts', async function () { + const sess:any = {foo: 'bar', cookie: {expires: new Date(Date.now() + 100)}}; + await set(sess); + assert.equal(JSON.stringify(await get()), JSON.stringify(sess)); + ss!.shutdown(); + await new Promise((resolve) => setTimeout(resolve, 110)); + // The record should not have been automatically purged. + assert.equal(JSON.stringify(await db.get(`sessionstorage:${sid}`)), JSON.stringify(sess)); + }); + }); + + describe('destroy', function () { + it('destroy deletes the database record', async function () { + const sess:any = {cookie: {expires: new Date(Date.now() + 100)}}; + await set(sess); + await destroy(); + assert(await db.get(`sessionstorage:${sid}`) == null); + }); + + it('destroy cancels the timeout', async function () { + const sess:any = {cookie: {expires: new Date(Date.now() + 100)}}; + await set(sess); + await destroy(); + await db.set(`sessionstorage:${sid}`, sess); + await new Promise((resolve) => setTimeout(resolve, 110)); + assert.equal(JSON.stringify(await db.get(`sessionstorage:${sid}`)), JSON.stringify(sess)); + }); + + it('destroy session that does not exist', async function () { + await destroy(); + }); + }); + + describe('touch without refresh', function () { + it('touch before set is equivalent to set if session expires', async function () { + const sess:any = {cookie: {expires: new Date(Date.now() + 1000)}}; + await touch(sess); + assert.equal(JSON.stringify(await get()), JSON.stringify(sess)); + }); + + it('touch updates observed expiration but not database', async function () { + const start = Date.now(); + const sess:any = {cookie: {expires: new Date(start + 200)}}; + await set(sess); + const sess2:any = {cookie: {expires: new Date(start + 12000)}}; + await touch(sess2); + assert.equal(JSON.stringify(await db.get(`sessionstorage:${sid}`)), JSON.stringify(sess)); + assert.equal(JSON.stringify(await get()), JSON.stringify(sess2)); + }); + }); + + describe('touch with refresh', function () { + beforeEach(async function () { + ss = new SessionStore(200); + }); + + it('touch before set is equivalent to set if session expires', async function () { + const sess:any = {cookie: {expires: new Date(Date.now() + 1000)}}; + await touch(sess); + assert.equal(JSON.stringify(await get()), JSON.stringify(sess)); + }); + + it('touch before eligible for refresh updates expiration but not DB', async function () { + const now = Date.now(); + const sess:any = {foo: 'bar', cookie: {expires: new Date(now + 1000)}}; + await set(sess); + const sess2:any = {foo: 'bar', cookie: {expires: new Date(now + 1001)}}; + await touch(sess2); + assert.equal(JSON.stringify(await db.get(`sessionstorage:${sid}`)), JSON.stringify(sess)); + assert.equal(JSON.stringify(await get()), JSON.stringify(sess2)); + }); + + it('touch before eligible for refresh updates timeout', async function () { + const start = Date.now(); + const sess:any = {foo: 'bar', cookie: {expires: new Date(start + 200)}}; + await set(sess); + await new Promise((resolve) => setTimeout(resolve, 100)); + const sess2:any = {foo: 'bar', cookie: {expires: new Date(start + 399)}}; + await touch(sess2); + await new Promise((resolve) => setTimeout(resolve, 110)); + assert.equal(JSON.stringify(await db.get(`sessionstorage:${sid}`)), JSON.stringify(sess)); + assert.equal(JSON.stringify(await get()), JSON.stringify(sess2)); + }); + + it('touch after eligible for refresh updates db', async function () { + const start = Date.now(); + const sess:any = {foo: 'bar', cookie: {expires: new Date(start + 200)}}; + await set(sess); + await new Promise((resolve) => setTimeout(resolve, 100)); + const sess2:any = {foo: 'bar', cookie: {expires: new Date(start + 400)}}; + await touch(sess2); + await new Promise((resolve) => setTimeout(resolve, 110)); + assert.equal(JSON.stringify(await db.get(`sessionstorage:${sid}`)), JSON.stringify(sess2)); + assert.equal(JSON.stringify(await get()), JSON.stringify(sess2)); + }); + + it('refresh=0 updates db every time', async function () { + ss = new SessionStore(0); + const sess:any = {foo: 'bar', cookie: {expires: new Date(Date.now() + 1000)}}; + await set(sess); + await db.remove(`sessionstorage:${sid}`); + await touch(sess); // No change in expiration time. + assert.equal(JSON.stringify(await db.get(`sessionstorage:${sid}`)), JSON.stringify(sess)); + await db.remove(`sessionstorage:${sid}`); + await touch(sess); // No change in expiration time. + assert.equal(JSON.stringify(await db.get(`sessionstorage:${sid}`)), JSON.stringify(sess)); + }); + }); +}); diff --git a/src/tests/backend/specs/Stream.ts b/src/tests/backend/specs/Stream.ts new file mode 100644 index 000000000..c8a5a3e36 --- /dev/null +++ b/src/tests/backend/specs/Stream.ts @@ -0,0 +1,365 @@ +'use strict'; + +const Stream = require('../../../node/utils/Stream'); +import {strict} from "assert"; + +class DemoIterable { + private value: number; + errs: Error[]; + rets: any[]; + constructor() { + this.value = 0; + this.errs = []; + this.rets = []; + } + + completed() { return this.errs.length > 0 || this.rets.length > 0; } + + next() { + if (this.completed()) return {value: undefined, done: true}; // Mimic standard generators. + return {value: this.value++, done: false}; + } + + throw(err: any) { + const alreadyCompleted = this.completed(); + this.errs.push(err); + if (alreadyCompleted) throw err; // Mimic standard generator objects. + throw err; + } + + return(ret: number) { + const alreadyCompleted = this.completed(); + this.rets.push(ret); + if (alreadyCompleted) return {value: ret, done: true}; // Mimic standard generator objects. + return {value: ret, done: true}; + } + + [Symbol.iterator]() { return this; } +} + +const assertUnhandledRejection = async (action: any, want: any) => { + // Temporarily remove unhandled Promise rejection listeners so that the unhandled rejections we + // expect to see don't trigger a test failure (or terminate node). + const event = 'unhandledRejection'; + const listenersBackup = process.rawListeners(event); + process.removeAllListeners(event); + let tempListener: Function; + let asyncErr:any; + try { + const seenErrPromise = new Promise((resolve) => { + tempListener = (err:any) => { + strict.equal(asyncErr, undefined); + asyncErr = err; + resolve(); + }; + }); + // @ts-ignore + process.on(event, tempListener); + await action(); + await seenErrPromise; + } finally { + // Restore the original listeners. + // @ts-ignore + process.off(event, tempListener); + for (const listener of listenersBackup) { // @ts-ignore + process.on(event, listener); + } + } + await strict.rejects(Promise.reject(asyncErr), want); +}; + +describe(__filename, function () { + describe('basic behavior', function () { + it('takes a generator', async function () { + strict.deepEqual([...new Stream((function* () { yield 0; yield 1; yield 2; })())], [0, 1, 2]); + }); + + it('takes an array', async function () { + strict.deepEqual([...new Stream([0, 1, 2])], [0, 1, 2]); + }); + + it('takes an iterator', async function () { + strict.deepEqual([...new Stream([0, 1, 2][Symbol.iterator]())], [0, 1, 2]); + }); + + it('supports empty iterators', async function () { + strict.deepEqual([...new Stream([])], []); + }); + + it('is resumable', async function () { + const s = new Stream((function* () { yield 0; yield 1; yield 2; })()); + let iter = s[Symbol.iterator](); + strict.deepEqual(iter.next(), {value: 0, done: false}); + iter = s[Symbol.iterator](); + strict.deepEqual(iter.next(), {value: 1, done: false}); + strict.deepEqual([...s], [2]); + }); + + it('supports return value', async function () { + const s = new Stream((function* () { yield 0; return 1; })()); + const iter = s[Symbol.iterator](); + strict.deepEqual(iter.next(), {value: 0, done: false}); + strict.deepEqual(iter.next(), {value: 1, done: true}); + }); + + it('does not start until needed', async function () { + let lastYield = null; + new Stream((function* () { yield lastYield = 0; })()); + // Fetching from the underlying iterator should not start until the first value is fetched + // from the stream. + strict.equal(lastYield, null); + }); + + it('throw is propagated', async function () { + const underlying = new DemoIterable(); + const s = new Stream(underlying); + const iter = s[Symbol.iterator](); + strict.deepEqual(iter.next(), {value: 0, done: false}); + const err = new Error('injected'); + strict.throws(() => iter.throw(err), err); + strict.equal(underlying.errs[0], err); + }); + + it('return is propagated', async function () { + const underlying = new DemoIterable(); + const s = new Stream(underlying); + const iter = s[Symbol.iterator](); + strict.deepEqual(iter.next(), {value: 0, done: false}); + strict.deepEqual(iter.return(42), {value: 42, done: true}); + strict.equal(underlying.rets[0], 42); + }); + }); + + describe('range', function () { + it('basic', async function () { + strict.deepEqual([...Stream.range(0, 3)], [0, 1, 2]); + }); + + it('empty', async function () { + strict.deepEqual([...Stream.range(0, 0)], []); + }); + + it('positive start', async function () { + strict.deepEqual([...Stream.range(3, 5)], [3, 4]); + }); + + it('negative start', async function () { + strict.deepEqual([...Stream.range(-3, 0)], [-3, -2, -1]); + }); + + it('end before start', async function () { + strict.deepEqual([...Stream.range(3, 0)], []); + }); + }); + + describe('batch', function () { + it('empty', async function () { + strict.deepEqual([...new Stream([]).batch(10)], []); + }); + + it('does not start until needed', async function () { + let lastYield = null; + new Stream((function* () { yield lastYield = 0; })()).batch(10); + strict.equal(lastYield, null); + }); + + it('fewer than batch size', async function () { + let lastYield = null; + const values = (function* () { + for (let i = 0; i < 5; i++) yield lastYield = i; + })(); + const s = new Stream(values).batch(10); + strict.equal(lastYield, null); + strict.deepEqual(s[Symbol.iterator]().next(), {value: 0, done: false}); + strict.equal(lastYield, 4); + strict.deepEqual([...s], [1, 2, 3, 4]); + strict.equal(lastYield, 4); + }); + + it('exactly batch size', async function () { + let lastYield = null; + const values = (function* () { + for (let i = 0; i < 5; i++) yield lastYield = i; + })(); + const s = new Stream(values).batch(5); + strict.equal(lastYield, null); + strict.deepEqual(s[Symbol.iterator]().next(), {value: 0, done: false}); + strict.equal(lastYield, 4); + strict.deepEqual([...s], [1, 2, 3, 4]); + strict.equal(lastYield, 4); + }); + + it('multiple batches, last batch is not full', async function () { + let lastYield = null; + const values = (function* () { + for (let i = 0; i < 10; i++) yield lastYield = i; + })(); + const s = new Stream(values).batch(3); + strict.equal(lastYield, null); + const iter = s[Symbol.iterator](); + strict.deepEqual(iter.next(), {value: 0, done: false}); + strict.equal(lastYield, 2); + strict.deepEqual(iter.next(), {value: 1, done: false}); + strict.deepEqual(iter.next(), {value: 2, done: false}); + strict.equal(lastYield, 2); + strict.deepEqual(iter.next(), {value: 3, done: false}); + strict.equal(lastYield, 5); + strict.deepEqual([...s], [4, 5, 6, 7, 8, 9]); + strict.equal(lastYield, 9); + }); + + it('batched Promise rejections are suppressed while iterating', async function () { + let lastYield = null; + const err = new Error('injected'); + const values = (function* () { + lastYield = 'promise of 0'; + yield new Promise((resolve) => setTimeout(() => resolve(0), 100)); + lastYield = 'rejected Promise'; + yield Promise.reject(err); + lastYield = 'promise of 2'; + yield Promise.resolve(2); + })(); + const s = new Stream(values).batch(3); + const iter = s[Symbol.iterator](); + const nextp = iter.next().value; + strict.equal(lastYield, 'promise of 2'); + strict.equal(await nextp, 0); + await strict.rejects(iter.next().value, err); + iter.return(); + }); + + it('batched Promise rejections are unsuppressed when iteration completes', async function () { + let lastYield = null; + const err = new Error('injected'); + const values = (function* () { + lastYield = 'promise of 0'; + yield new Promise((resolve) => setTimeout(() => resolve(0), 100)); + lastYield = 'rejected Promise'; + yield Promise.reject(err); + lastYield = 'promise of 2'; + yield Promise.resolve(2); + })(); + const s = new Stream(values).batch(3); + const iter = s[Symbol.iterator](); + strict.equal(await iter.next().value, 0); + strict.equal(lastYield, 'promise of 2'); + await assertUnhandledRejection(() => iter.return(), err); + }); + }); + + describe('buffer', function () { + it('empty', async function () { + strict.deepEqual([...new Stream([]).buffer(10)], []); + }); + + it('does not start until needed', async function () { + let lastYield = null; + new Stream((function* () { yield lastYield = 0; })()).buffer(10); + strict.equal(lastYield, null); + }); + + it('fewer than buffer size', async function () { + let lastYield = null; + const values = (function* () { + for (let i = 0; i < 5; i++) yield lastYield = i; + })(); + const s = new Stream(values).buffer(10); + strict.equal(lastYield, null); + strict.deepEqual(s[Symbol.iterator]().next(), {value: 0, done: false}); + strict.equal(lastYield, 4); + strict.deepEqual([...s], [1, 2, 3, 4]); + strict.equal(lastYield, 4); + }); + + it('exactly buffer size', async function () { + let lastYield = null; + const values = (function* () { + for (let i = 0; i < 5; i++) yield lastYield = i; + })(); + const s = new Stream(values).buffer(5); + strict.equal(lastYield, null); + strict.deepEqual(s[Symbol.iterator]().next(), {value: 0, done: false}); + strict.equal(lastYield, 4); + strict.deepEqual([...s], [1, 2, 3, 4]); + strict.equal(lastYield, 4); + }); + + it('more than buffer size', async function () { + let lastYield = null; + const values = (function* () { + for (let i = 0; i < 10; i++) yield lastYield = i; + })(); + const s = new Stream(values).buffer(3); + strict.equal(lastYield, null); + const iter = s[Symbol.iterator](); + strict.deepEqual(iter.next(), {value: 0, done: false}); + strict.equal(lastYield, 3); + strict.deepEqual(iter.next(), {value: 1, done: false}); + strict.equal(lastYield, 4); + strict.deepEqual(iter.next(), {value: 2, done: false}); + strict.equal(lastYield, 5); + strict.deepEqual([...s], [3, 4, 5, 6, 7, 8, 9]); + strict.equal(lastYield, 9); + }); + + it('buffered Promise rejections are suppressed while iterating', async function () { + let lastYield = null; + const err = new Error('injected'); + const values = (function* () { + lastYield = 'promise of 0'; + yield new Promise((resolve) => setTimeout(() => resolve(0), 100)); + lastYield = 'rejected Promise'; + yield Promise.reject(err); + lastYield = 'promise of 2'; + yield Promise.resolve(2); + })(); + const s = new Stream(values).buffer(3); + const iter = s[Symbol.iterator](); + const nextp = iter.next().value; + strict.equal(lastYield, 'promise of 2'); + strict.equal(await nextp, 0); + await strict.rejects(iter.next().value, err); + iter.return(); + }); + + it('buffered Promise rejections are unsuppressed when iteration completes', async function () { + let lastYield = null; + const err = new Error('injected'); + const values = (function* () { + lastYield = 'promise of 0'; + yield new Promise((resolve) => setTimeout(() => resolve(0), 100)); + lastYield = 'rejected Promise'; + yield Promise.reject(err); + lastYield = 'promise of 2'; + yield Promise.resolve(2); + })(); + const s = new Stream(values).buffer(3); + const iter = s[Symbol.iterator](); + strict.equal(await iter.next().value, 0); + strict.equal(lastYield, 'promise of 2'); + await assertUnhandledRejection(() => iter.return(), err); + }); + }); + + describe('map', function () { + it('empty', async function () { + let called = false; + strict.deepEqual([...new Stream([]).map(() => called = true)], []); + strict.equal(called, false); + }); + + it('does not start until needed', async function () { + let called = false; + strict.deepEqual([...new Stream([]).map(() => called = true)], []); + new Stream((function* () { yield 0; })()).map(() => called = true); + strict.equal(called, false); + }); + + it('works', async function () { + const calls:any[] = []; + strict.deepEqual( + [...new Stream([0, 1, 2]).map((v:any) => { calls.push(v); return 2 * v; })], [0, 2, 4]); + strict.deepEqual(calls, [0, 1, 2]); + }); + }); +}); diff --git a/src/tests/backend/specs/api/api.ts b/src/tests/backend/specs/api/api.ts new file mode 100644 index 000000000..bab70b47c --- /dev/null +++ b/src/tests/backend/specs/api/api.ts @@ -0,0 +1,57 @@ +'use strict'; + +/** + * API specs + * + * Tests for generic overarching HTTP API related features not related to any + * specific part of the data model or domain. For example: tests for versioning + * and openapi definitions. + */ + +const common = require('../../common'); +const validateOpenAPI = require('openapi-schema-validation').validate; + +let agent: any; +let apiVersion = 1; + +const makeid = () => { + let text = ''; + const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + + for (let i = 0; i < 5; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; +}; + +const testPadId = makeid(); + +const endPoint = (point:string) => `/api/${apiVersion}/${point}`; + +describe(__filename, function () { + before(async function () { agent = await common.init(); }); + + it('can obtain API version', async function () { + await agent.get('/api/') + .expect(200) + .expect((res:any) => { + apiVersion = res.body.currentVersion; + if (!res.body.currentVersion) throw new Error('No version set in API'); + return; + }); + }); + + it('can obtain valid openapi definition document', async function () { + this.timeout(15000); + await agent.get('/api/openapi.json') + .expect(200) + .expect((res:any) => { + const {valid, errors} = validateOpenAPI(res.body, 3); + if (!valid) { + const prettyErrors = JSON.stringify(errors, null, 2); + throw new Error(`Document is not valid OpenAPI. ${errors.length} ` + + `validation errors:\n${prettyErrors}`); + } + }); + }); +}); diff --git a/src/tests/backend/specs/api/characterEncoding.ts b/src/tests/backend/specs/api/characterEncoding.ts new file mode 100644 index 000000000..80093437b --- /dev/null +++ b/src/tests/backend/specs/api/characterEncoding.ts @@ -0,0 +1,101 @@ +'use strict'; + +/* + * This file is copied & modified from /src/tests/backend/specs/api/pad.js + * + * TODO: maybe unify those two files and merge in a single one. + */ + +import {generateJWTToken, generateJWTTokenUser} from "../../common"; + +const assert = require('assert').strict; +const common = require('../../common'); +const fs = require('fs'); +const fsp = fs.promises; + +let agent:any; +let apiVersion = 1; +const testPadId = makeid(); + +const endPoint = (point:string, version?:number) => `/api/${version || apiVersion}/${point}`; + +describe(__filename, function () { + before(async function () { agent = await common.init(); }); + + describe('Sanity checks', function () { + it('can connect', async function () { + await agent.get('/api/') + .set("Authorization", await generateJWTToken()) + .expect(200) + .expect('Content-Type', /json/); + }); + + it('finds the version tag', async function () { + const res = await agent.get('/api/') + .set("Authorization", await generateJWTToken()) + .expect(200); + apiVersion = res.body.currentVersion; + assert(apiVersion); + }); + + it('errors with invalid OAuth token', async function () { + // This is broken because Etherpad doesn't handle HTTP codes properly see #2343 + await agent.get(`/api/${apiVersion}/createPad?padID=test`) + .set("Authorization", (await generateJWTToken()).substring(0,10)) + .expect(401); + }); + + it('errors with unprivileged OAuth token', async function () { + // This is broken because Etherpad doesn't handle HTTP codes properly see #2343 + await agent.get(`/api/${apiVersion}/createPad?padID=test`) + .set("Authorization", (await generateJWTTokenUser()).substring(0,10)) + .expect(401); + }); + }); + + describe('Tests', function () { + it('creates a new Pad', async function () { + const res = await agent.get(`${endPoint('createPad')}?padID=${testPadId}`) + .set("Authorization", await generateJWTToken()) + .expect(200) + .expect('Content-Type', /json/); + assert.equal(res.body.code, 0); + }); + + it('Sets the HTML of a Pad attempting to weird utf8 encoded content', async function () { + const res = await agent.post(endPoint('setHTML')) + .set("Authorization", await generateJWTToken()) + .send({ + padID: testPadId, + html: await fsp.readFile('tests/backend/specs/api/emojis.html', 'utf8'), + }) + .expect(200) + .expect('Content-Type', /json/); + assert.equal(res.body.code, 0); + }); + + it('get the HTML of Pad with emojis', async function () { + const res = await agent.get(`${endPoint('getHTML')}?padID=${testPadId}`) + .set("Authorization", await generateJWTToken()) + .expect(200) + .expect('Content-Type', /json/); + assert.match(res.body.data.html, /🇼/); + }); + }); +}); + +/* + + End of test + +*/ + +function makeid() { + let text = ''; + const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + + for (let i = 0; i < 10; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; +} diff --git a/src/tests/backend/specs/api/chat.ts b/src/tests/backend/specs/api/chat.ts new file mode 100644 index 000000000..d2c0ba8a8 --- /dev/null +++ b/src/tests/backend/specs/api/chat.ts @@ -0,0 +1,126 @@ +'use strict'; + +import {generateJWTToken} from "../../common"; + +const common = require('../../common'); + +import {strict as assert} from "assert"; + +let agent:any; +let apiVersion = 1; +let authorID = ''; +const padID = makeid(); +const timestamp = Date.now(); + +const endPoint = (point:string) => `/api/${apiVersion}/${point}`; + +describe(__filename, function () { + before(async function () { agent = await common.init(); }); + + describe('API Versioning', function () { + it('errors if can not connect', async function () { + await agent.get('/api/') + .expect((res:any) => { + apiVersion = res.body.currentVersion; + if (!res.body.currentVersion) throw new Error('No version set in API'); + return; + }) + .expect(200); + }); + }); + + // BEGIN GROUP AND AUTHOR TESTS + // /////////////////////////////////// + // /////////////////////////////////// + + /* Tests performed + -> createPad(padID) + -> createAuthor([name]) -- should return an authorID + -> appendChatMessage(padID, text, authorID, time) + -> getChatHead(padID) + -> getChatHistory(padID) + */ + + describe('Chat functionality', function () { + it('creates a new Pad', async function () { + await agent.get(`${endPoint('createPad')}?padID=${padID}`) + .set("authorization", await generateJWTToken()) + .expect(200) + .expect((res:any) => { + if (res.body.code !== 0) throw new Error('Unable to create new Pad'); + }) + .expect('Content-Type', /json/); + }); + + it('Creates an author with a name set', async function () { + await agent.get(endPoint('createAuthor')) + .set("authorization", await generateJWTToken()) + .expect((res:any) => { + if (res.body.code !== 0 || !res.body.data.authorID) { + throw new Error('Unable to create author'); + } + authorID = res.body.data.authorID; // we will be this author for the rest of the tests + }) + .expect('Content-Type', /json/) + .expect(200); + }); + + it('Gets the head of chat before the first chat msg', async function () { + await agent.get(`${endPoint('getChatHead')}?padID=${padID}`) + .set("authorization", await generateJWTToken()) + .expect((res:any) => { + if (res.body.data.chatHead !== -1) throw new Error('Chat Head Length is wrong'); + if (res.body.code !== 0) throw new Error('Unable to get chat head'); + }) + .expect('Content-Type', /json/) + .expect(200); + }); + + it('Adds a chat message to the pad', async function () { + await agent.get(`${endPoint('appendChatMessage')}?padID=${padID}&text=blalblalbha` + + `&authorID=${authorID}&time=${timestamp}`) + .set("authorization", await generateJWTToken()) + .expect((res:any) => { + if (res.body.code !== 0) throw new Error('Unable to create chat message'); + }) + .expect('Content-Type', /json/) + .expect(200); + }); + + it('Gets the head of chat', async function () { + await agent.get(`${endPoint('getChatHead')}?padID=${padID}`) + .set("authorization", await generateJWTToken()) + .expect((res:any) => { + if (res.body.data.chatHead !== 0) throw new Error('Chat Head Length is wrong'); + + if (res.body.code !== 0) throw new Error('Unable to get chat head'); + }) + .expect('Content-Type', /json/) + .expect(200); + }); + + it('Gets Chat History of a Pad', async function () { + await agent.get(`${endPoint('getChatHistory')}?padID=${padID}`) + .set("authorization", await generateJWTToken()) + .expect('Content-Type', /json/) + .expect(200) + .expect((res:any) => { + assert.equal(res.body.code, 0, 'Unable to get chat history'); + assert.equal(res.body.data.messages.length, 1, 'Chat History Length is wrong'); + assert.equal(res.body.data.messages[0].text, 'blalblalbha', 'Chat text does not match'); + assert.equal(res.body.data.messages[0].userId, authorID, 'Message author does not match'); + assert.equal(res.body.data.messages[0].time, timestamp.toString(), 'Message time does not match'); + }); + }); + }); +}); + +function makeid() { + let text = ''; + const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + + for (let i = 0; i < 5; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; +} diff --git a/src/tests/backend/specs/api/emojis.html b/src/tests/backend/specs/api/emojis.html new file mode 100644 index 000000000..4becaea00 --- /dev/null +++ b/src/tests/backend/specs/api/emojis.html @@ -0,0 +1,10 @@ + + + + foo + + + +😀 😁 😂 🤣 😃 😄 😅 😆 😉 😊 😋 😎 😍 😘 🥰 😗 😙 😚 ☺️ 🙂 🤗 🤩 🤔 🤨 😐 😑 😶 🙄 😏 😣 😥 😮 🤐 😯 😪 😫 😴 😌 😛 😜 😝 🤤 😒 😓 😔 😕 🙃 🤑 😲 ☹️ 🙁 😖 😞 😟 😤 😢 😭 😦 😧 😨 😩 🤯 😬 😰 😱 🥵 🥶 😳 🤪 😵 😡 😠 🤬 😷 🤒 🤕 🤢 🤮 🤧 😇 🤠 🤡 🥳 🥴 🥺 🤥 🤫 🤭 🧐 🤓 😈 👿 👹 👺 💀 👻 👽 🤖 💩 😺 😸 😹 😻 😼 😽 🙀 😿 😾 👶 👧 🧒 👦 👩 🧑 👨 👵 🧓 👴 👲 👳‍♀️ 👳‍♂️ 🧕 🧔 👱‍♂️ 👱‍♀️ 👨‍🦰 👩‍🦰 👨‍🦱 👩‍🦱 👨‍🦲 👩‍🦲 👨‍🦳 👩‍🦳 🦸‍♀️ 🦸‍♂️ 🦹‍♀️ 🦹‍♂️ 👮‍♀️ 👮‍♂️ 👷‍♀️ 👷‍♂️ 💂‍♀️ 💂‍♂️ 🕵️‍♀️ 🕵️‍♂️ 👩‍⚕️ 👨‍⚕️ 👩‍🌾 👨‍🌾 👩‍🍳 👨‍🍳 👩‍🎓 👨‍🎓 👩‍🎤 👨‍🎤 👩‍🏫 👨‍🏫 👩‍🏭 👨‍🏭 👩‍💻 👨‍💻 👩‍💼 👨‍💼 👩‍🔧 👨‍🔧 👩‍🔬 👨‍🔬 👩‍🎨 👨‍🎨 👩‍🚒 👨‍🚒 👩‍✈️ 👨‍✈️ 👩‍🚀 👨‍🚀 👩‍⚖️ 👨‍⚖️ 👰 🤵 👸 🤴 🤶 🎅 🧙‍♀️ 🧙‍♂️ 🧝‍♀️ 🧝‍♂️ 🧛‍♀️ 🧛‍♂️ 🧟‍♀️ 🧟‍♂️ 🧞‍♀️ 🧞‍♂️ 🧜‍♀️ 🧜‍♂️ 🧚‍♀️ 🧚‍♂️ 👼 🤰 🤱 🙇‍♀️ 🙇‍♂️ 💁‍♀️ 💁‍♂️ 🙅‍♀️ 🙅‍♂️ 🙆‍♀️ 🙆‍♂️ 🙋‍♀️ 🙋‍♂️ 🤦‍♀️ 🤦‍♂️ 🤷‍♀️ 🤷‍♂️ 🙎‍♀️ 🙎‍♂️ 🙍‍♀️ 🙍‍♂️ 💇‍♀️ 💇‍♂️ 💆‍♀️ 💆‍♂️ 🧖‍♀️ 🧖‍♂️ 💅 🤳 💃 🕺 👯‍♀️ 👯‍♂️ 🕴 🚶‍♀️ 🚶‍♂️ 🏃‍♀️ 🏃‍♂️ 👫 👭 👬 💑 👩‍❤️‍👩 👨‍❤️‍👨 💏 👩‍❤️‍💋‍👩 👨‍❤️‍💋‍👨 👪 👨‍👩‍👧 👨‍👩‍👧‍👦 👨‍👩‍👦‍👦 👨‍👩‍👧‍👧 👩‍👩‍👦 👩‍👩‍👧 👩‍👩‍👧‍👦 👩‍👩‍👦‍👦 👩‍👩‍👧‍👧 👨‍👨‍👦 👨‍👨‍👧 👨‍👨‍👧‍👦 👨‍👨‍👦‍👦 👨‍👨‍👧‍👧 👩‍👦 👩‍👧 👩‍👧‍👦 👩‍👦‍👦 👩‍👧‍👧 👨‍👦 👨‍👧 👨‍👧‍👦 👨‍👦‍👦 👨‍👧‍👧 🤲 👐 🙌 👏 🤝 👍 👎 👊 ✊ 🤛 🤜 🤞 ✌️ 🤟 🤘 👌 👈 👉 👆 👇 ☝️ ✋ 🤚 🖐 🖖 👋 🤙 💪 🦵 🦶 🖕 ✍️ 🙏 💍 💄 💋 👄 👅 👂 👃 👣 👁 👀 🧠 🦴 🦷 🗣 👤 👥🧥 👚 👕 👖 👔 👗 👙 👘 👠 👡 👢 👞 👟 🥾 🥿 🧦 🧤 🧣 🎩 🧢 👒 🎓 ⛑ 👑 👝 👛 👜 💼 🎒 👓 🕶 🥽 🥼 🌂 🧵 🧶👶🏻 👦🏻 👧🏻 👨🏻 👩🏻 👱🏻‍♀️ 👱🏻 👴🏻 👵🏻 👲🏻 👳🏻‍♀️ 👳🏻 👮🏻‍♀️ 👮🏻 👷🏻‍♀️ 👷🏻 💂🏻‍♀️ 💂🏻 🕵🏻‍♀️ 🕵🏻 👩🏻‍⚕️ 👨🏻‍⚕️ 👩🏻‍🌾 👨🏻‍🌾 👩🏻‍🍳 👨🏻‍🍳 👩🏻‍🎓 👨🏻‍🎓 👩🏻‍🎤 👨🏻‍🎤 👩🏻‍🏫 👨🏻‍🏫 👩🏻‍🏭 👨🏻‍🏭 👩🏻‍💻 👨🏻‍💻 👩🏻‍💼 👨🏻‍💼 👩🏻‍🔧 👨🏻‍🔧 👩🏻‍🔬 👨🏻‍🔬 👩🏻‍🎨 👨🏻‍🎨 👩🏻‍🚒 👨🏻‍🚒 👩🏻‍✈️ 👨🏻‍✈️ 👩🏻‍🚀 👨🏻‍🚀 👩🏻‍⚖️ 👨🏻‍⚖️ 🤶🏻 🎅🏻 👸🏻 🤴🏻 👰🏻 🤵🏻 👼🏻 🤰🏻 🙇🏻‍♀️ 🙇🏻 💁🏻 💁🏻‍♂️ 🙅🏻 🙅🏻‍♂️ 🙆🏻 🙆🏻‍♂️ 🙋🏻 🙋🏻‍♂️ 🤦🏻‍♀️ 🤦🏻‍♂️ 🤷🏻‍♀️ 🤷🏻‍♂️ 🙎🏻 🙎🏻‍♂️ 🙍🏻 🙍🏻‍♂️ 💇🏻 💇🏻‍♂️ 💆🏻 💆🏻‍♂️ 🕴🏻 💃🏻 🕺🏻 🚶🏻‍♀️ 🚶🏻 🏃🏻‍♀️ 🏃🏻 🤲🏻 👐🏻 🙌🏻 👏🏻 🙏🏻 👍🏻 👎🏻 👊🏻 ✊🏻 🤛🏻 🤜🏻 🤞🏻 ✌🏻 🤟🏻 🤘🏻 👌🏻 👈🏻 👉🏻 👆🏻 👇🏻 ☝🏻 ✋🏻 🤚🏻 🖐🏻 🖖🏻 👋🏻 🤙🏻 💪🏻 🖕🏻 ✍🏻 🤳🏻 💅🏻 👂🏻 👃🏻👶🏼 👦🏼 👧🏼 👨🏼 👩🏼 👱🏼‍♀️ 👱🏼 👴🏼 👵🏼 👲🏼 👳🏼‍♀️ 👳🏼 👮🏼‍♀️ 👮🏼 👷🏼‍♀️ 👷🏼 💂🏼‍♀️ 💂🏼 🕵🏼‍♀️ 🕵🏼 👩🏼‍⚕️ 👨🏼‍⚕️ 👩🏼‍🌾 👨🏼‍🌾 👩🏼‍🍳 👨🏼‍🍳 👩🏼‍🎓 👨🏼‍🎓 👩🏼‍🎤 👨🏼‍🎤 👩🏼‍🏫 👨🏼‍🏫 👩🏼‍🏭 👨🏼‍🏭 👩🏼‍💻 👨🏼‍💻 👩🏼‍💼 👨🏼‍💼 👩🏼‍🔧 👨🏼‍🔧 👩🏼‍🔬 👨🏼‍🔬 👩🏼‍🎨 👨🏼‍🎨 👩🏼‍🚒 👨🏼‍🚒 👩🏼‍✈️ 👨🏼‍✈️ 👩🏼‍🚀 👨🏼‍🚀 👩🏼‍⚖️ 👨🏼‍⚖️ 🤶🏼 🎅🏼 👸🏼 🤴🏼 👰🏼 🤵🏼 👼🏼 🤰🏼 🙇🏼‍♀️ 🙇🏼 💁🏼 💁🏼‍♂️ 🙅🏼 🙅🏼‍♂️ 🙆🏼 🙆🏼‍♂️ 🙋🏼 🙋🏼‍♂️ 🤦🏼‍♀️ 🤦🏼‍♂️ 🤷🏼‍♀️ 🤷🏼‍♂️ 🙎🏼 🙎🏼‍♂️ 🙍🏼 🙍🏼‍♂️ 💇🏼 💇🏼‍♂️ 💆🏼 💆🏼‍♂️ 🕴🏼 💃🏼 🕺🏼 🚶🏼‍♀️ 🚶🏼 🏃🏼‍♀️ 🏃🏼 🤲🏼 👐🏼 🙌🏼 👏🏼 🙏🏼 👍🏼 👎🏼 👊🏼 ✊🏼 🤛🏼 🤜🏼 🤞🏼 ✌🏼 🤟🏼 🤘🏼 👌🏼 👈🏼 👉🏼 👆🏼 👇🏼 ☝🏼 ✋🏼 🤚🏼 🖐🏼 🖖🏼 👋🏼 🤙🏼 💪🏼 🖕🏼 ✍🏼 🤳🏼 💅🏼 👂🏼 👃🏼👶🏽 👦🏽 👧🏽 👨🏽 👩🏽 👱🏽‍♀️ 👱🏽 👴🏽 👵🏽 👲🏽 👳🏽‍♀️ 👳🏽 👮🏽‍♀️ 👮🏽 👷🏽‍♀️ 👷🏽 💂🏽‍♀️ 💂🏽 🕵🏽‍♀️ 🕵🏽 👩🏽‍⚕️ 👨🏽‍⚕️ 👩🏽‍🌾 👨🏽‍🌾 👩🏽‍🍳 👨🏽‍🍳 👩🏽‍🎓 👨🏽‍🎓 👩🏽‍🎤 👨🏽‍🎤 👩🏽‍🏫 👨🏽‍🏫 👩🏽‍🏭 👨🏽‍🏭 👩🏽‍💻 👨🏽‍💻 👩🏽‍💼 👨🏽‍💼 👩🏽‍🔧 👨🏽‍🔧 👩🏽‍🔬 👨🏽‍🔬 👩🏽‍🎨 👨🏽‍🎨 👩🏽‍🚒 👨🏽‍🚒 👩🏽‍✈️ 👨🏽‍✈️ 👩🏽‍🚀 👨🏽‍🚀 👩🏽‍⚖️ 👨🏽‍⚖️ 🤶🏽 🎅🏽 👸🏽 🤴🏽 👰🏽 🤵🏽 👼🏽 🤰🏽 🙇🏽‍♀️ 🙇🏽 💁🏽 💁🏽‍♂️ 🙅🏽 🙅🏽‍♂️ 🙆🏽 🙆🏽‍♂️ 🙋🏽 🙋🏽‍♂️ 🤦🏽‍♀️ 🤦🏽‍♂️ 🤷🏽‍♀️ 🤷🏽‍♂️ 🙎🏽 🙎🏽‍♂️ 🙍🏽 🙍🏽‍♂️ 💇🏽 💇🏽‍♂️ 💆🏽 💆🏽‍♂️ 🕴🏼 💃🏽 🕺🏽 🚶🏽‍♀️ 🚶🏽 🏃🏽‍♀️ 🏃🏽 🤲🏽 👐🏽 🙌🏽 👏🏽 🙏🏽 👍🏽 👎🏽 👊🏽 ✊🏽 🤛🏽 🤜🏽 🤞🏽 ✌🏽 🤟🏽 🤘🏽 👌🏽 👈🏽 👉🏽 👆🏽 👇🏽 ☝🏽 ✋🏽 🤚🏽 🖐🏽 🖖🏽 👋🏽 🤙🏽 💪🏽 🖕🏽 ✍🏽 🤳🏽 💅🏽 👂🏽 👃🏽👶🏾 👦🏾 👧🏾 👨🏾 👩🏾 👱🏾‍♀️ 👱🏾 👴🏾 👵🏾 👲🏾 👳🏾‍♀️ 👳🏾 👮🏾‍♀️ 👮🏾 👷🏾‍♀️ 👷🏾 💂🏾‍♀️ 💂🏾 🕵🏾‍♀️ 🕵🏾 👩🏾‍⚕️ 👨🏾‍⚕️ 👩🏾‍🌾 👨🏾‍🌾 👩🏾‍🍳 👨🏾‍🍳 👩🏾‍🎓 👨🏾‍🎓 👩🏾‍🎤 👨🏾‍🎤 👩🏾‍🏫 👨🏾‍🏫 👩🏾‍🏭 👨🏾‍🏭 👩🏾‍💻 👨🏾‍💻 👩🏾‍💼 👨🏾‍💼 👩🏾‍🔧 👨🏾‍🔧 👩🏾‍🔬 👨🏾‍🔬 👩🏾‍🎨 👨🏾‍🎨 👩🏾‍🚒 👨🏾‍🚒 👩🏾‍✈️ 👨🏾‍✈️ 👩🏾‍🚀 👨🏾‍🚀 👩🏾‍⚖️ 👨🏾‍⚖️ 🤶🏾 🎅🏾 👸🏾 🤴🏾 👰🏾 🤵🏾 👼🏾 🤰🏾 🙇🏾‍♀️ 🙇🏾 💁🏾 💁🏾‍♂️ 🙅🏾 🙅🏾‍♂️ 🙆🏾 🙆🏾‍♂️ 🙋🏾 🙋🏾‍♂️ 🤦🏾‍♀️ 🤦🏾‍♂️ 🤷🏾‍♀️ 🤷🏾‍♂️ 🙎🏾 🙎🏾‍♂️ 🙍🏾 🙍🏾‍♂️ 💇🏾 💇🏾‍♂️ 💆🏾 💆🏾‍♂️ 🕴🏾 💃🏾 🕺🏾 🚶🏾‍♀️ 🚶🏾 🏃🏾‍♀️ 🏃🏾 🤲🏾 👐🏾 🙌🏾 👏🏾 🙏🏾 👍🏾 👎🏾 👊🏾 ✊🏾 🤛🏾 🤜🏾 🤞🏾 ✌🏾 🤟🏾 🤘🏾 👌🏾 👈🏾 👉🏾 👆🏾 👇🏾 ☝🏾 ✋🏾 🤚🏾 🖐🏾 🖖🏾 👋🏾 🤙🏾 💪🏾 🖕🏾 ✍🏾 🤳🏾 💅🏾 👂🏾 👃🏾👶🏿 👦🏿 👧🏿 👨🏿 👩🏿 👱🏿‍♀️ 👱🏿 👴🏿 👵🏿 👲🏿 👳🏿‍♀️ 👳🏿 👮🏿‍♀️ 👮🏿 👷🏿‍♀️ 👷🏿 💂🏿‍♀️ 💂🏿 🕵🏿‍♀️ 🕵🏿 👩🏿‍⚕️ 👨🏿‍⚕️ 👩🏿‍🌾 👨🏿‍🌾 👩🏿‍🍳 👨🏿‍🍳 👩🏿‍🎓 👨🏿‍🎓 👩🏿‍🎤 👨🏿‍🎤 👩🏿‍🏫 👨🏿‍🏫 👩🏿‍🏭 👨🏿‍🏭 👩🏿‍💻 👨🏿‍💻 👩🏿‍💼 👨🏿‍💼 👩🏿‍🔧 👨🏿‍🔧 👩🏿‍🔬 👨🏿‍🔬 👩🏿‍🎨 👨🏿‍🎨 👩🏿‍🚒 👨🏿‍🚒 👩🏿‍✈️ 👨🏿‍✈️ 👩🏿‍🚀 👨🏿‍🚀 👩🏿‍⚖️ 👨🏿‍⚖️ 🤶🏿 🎅🏿 👸🏿 🤴🏿 👰🏿 🤵🏿 👼🏿 🤰🏿 🙇🏿‍♀️ 🙇🏿 💁🏿 💁🏿‍♂️ 🙅🏿 🙅🏿‍♂️ 🙆🏿 🙆🏿‍♂️ 🙋🏿 🙋🏿‍♂️ 🤦🏿‍♀️ 🤦🏿‍♂️ 🤷🏿‍♀️ 🤷🏿‍♂️ 🙎🏿 🙎🏿‍♂️ 🙍🏿 🙍🏿‍♂️ 💇🏿 💇🏿‍♂️ 💆🏿 💆🏿‍♂️ 🕴🏿 💃🏿 🕺🏿 🚶🏿‍♀️ 🚶🏿 🏃🏿‍♀️ 🏃🏿 🤲🏿 👐🏿 🙌🏿 👏🏿 🙏🏿 👍🏿 👎🏿 👊🏿 ✊🏿 🤛🏿 🤜🏿 🤞🏿 ✌🏿 🤟🏿 🤘🏿 👌🏿 👈🏿 👉🏿 👆🏿 👇🏿 ☝🏿 ✋🏿 🤚🏿 🖐🏿 🖖🏿 👋🏿 🤙🏿 💪🏿 🖕🏿 ✍🏿 🤳🏿 💅🏿 👂🏿 👃🏿🐶 🐱 🐭 🐹 🐰 🦊 🦝 🐻 🐼 🦘 🦡 🐨 🐯 🦁 🐮 🐷 🐽 🐸 🐵 🙈 🙉 🙊 🐒 🐔 🐧 🐦 🐤 🐣 🐥 🦆 🦢 🦅 🦉 🦚 🦜 🦇 🐺 🐗 🐴 🦄 🐝 🐛 🦋 🐌 🐚 🐞 🐜 🦗 🕷 🕸 🦂 🦟 🦠 🐢 🐍 🦎 🦖 🦕 🐙 🦑 🦐 🦀 🐡 🐠 🐟 🐬 🐳 🐋 🦈 🐊 🐅 🐆 🦓 🦍 🐘 🦏 🦛 🐪 🐫 🦙 🦒 🐃 🐂 🐄 🐎 🐖 🐏 🐑 🐐 🦌 🐕 🐩 🐈 🐓 🦃 🕊 🐇 🐁 🐀 🐿 🦔 🐾 🐉 🐲 🌵 🎄 🌲 🌳 🌴 🌱 🌿 ☘️ 🍀 🎍 🎋 🍃 🍂 🍁 🍄 🌾 💐 🌷 🌹 🥀 🌺 🌸 🌼 🌻 🌞 🌝 🌛 🌜 🌚 🌕 🌖 🌗 🌘 🌑 🌒 🌓 🌔 🌙 🌎 🌍 🌏 💫 ⭐️ 🌟 ✨ ⚡️ ☄️ 💥 🔥 🌪 🌈 ☀️ 🌤 ⛅️ 🌥 ☁️ 🌦 🌧 ⛈ 🌩 🌨 ❄️ ☃️ ⛄️ 🌬 💨 💧 💦 ☔️ ☂️ 🌊 🌫🍏 🍎 🍐 🍊 🍋 🍌 🍉 🍇 🍓 🍈 🍒 🍑 🍍 🥭 🥥 🥝 🍅 🍆 🥑 🥦 🥒 🥬 🌶 🌽 🥕 🥔 🍠 🥐 🍞 🥖 🥨 🥯 🧀 🥚 🍳 🥞 🥓 🥩 🍗 🍖 🌭 🍔 🍟 🍕 🥪 🥙 🌮 🌯 🥗 🥘 🥫 🍝 🍜 🍲 🍛 🍣 🍱 🥟 🍤 🍙 🍚 🍘 🍥 🥮 🥠 🍢 🍡 🍧 🍨 🍦 🥧 🍰 🎂 🍮 🍭 🍬 🍫 🍿 🧂 🍩 🍪 🌰 🥜 🍯 🥛 🍼 ☕️ 🍵 🥤 🍶 🍺 🍻 🥂 🍷 🥃 🍸 🍹 🍾 🥄 🍴 🍽 🥣 🥡 🥢⚽️ 🏀 🏈 ⚾️ 🥎 🏐 🏉 🎾 🥏 🎱 🏓 🏸 🥅 🏒 🏑 🥍 🏏 ⛳️ 🏹 🎣 🥊 🥋 🎽 ⛸ 🥌 🛷 🛹 🎿 ⛷ 🏂 🏋️‍♀️ 🏋🏻‍♀️ 🏋🏼‍♀️ 🏋🏽‍♀️ 🏋🏾‍♀️ 🏋🏿‍♀️ 🏋️‍♂️ 🏋🏻‍♂️ 🏋🏼‍♂️ 🏋🏽‍♂️ 🏋🏾‍♂️ 🏋🏿‍♂️ 🤼‍♀️ 🤼‍♂️ 🤸‍♀️ 🤸🏻‍♀️ 🤸🏼‍♀️ 🤸🏽‍♀️ 🤸🏾‍♀️ 🤸🏿‍♀️ 🤸‍♂️ 🤸🏻‍♂️ 🤸🏼‍♂️ 🤸🏽‍♂️ 🤸🏾‍♂️ 🤸🏿‍♂️ ⛹️‍♀️ ⛹🏻‍♀️ ⛹🏼‍♀️ ⛹🏽‍♀️ ⛹🏾‍♀️ ⛹🏿‍♀️ ⛹️‍♂️ ⛹🏻‍♂️ ⛹🏼‍♂️ ⛹🏽‍♂️ ⛹🏾‍♂️ ⛹🏿‍♂️ 🤺 🤾‍♀️ 🤾🏻‍♀️ 🤾🏼‍♀️ 🤾🏾‍♀️ 🤾🏾‍♀️ 🤾🏿‍♀️ 🤾‍♂️ 🤾🏻‍♂️ 🤾🏼‍♂️ 🤾🏽‍♂️ 🤾🏾‍♂️ 🤾🏿‍♂️ 🏌️‍♀️ 🏌🏻‍♀️ 🏌🏼‍♀️ 🏌🏽‍♀️ 🏌🏾‍♀️ 🏌🏿‍♀️ 🏌️‍♂️ 🏌🏻‍♂️ 🏌🏼‍♂️ 🏌🏽‍♂️ 🏌🏾‍♂️ 🏌🏿‍♂️ 🏇 🏇🏻 🏇🏼 🏇🏽 🏇🏾 🏇🏿 🧘‍♀️ 🧘🏻‍♀️ 🧘🏼‍♀️ 🧘🏽‍♀️ 🧘🏾‍♀️ 🧘🏿‍♀️ 🧘‍♂️ 🧘🏻‍♂️ 🧘🏼‍♂️ 🧘🏽‍♂️ 🧘🏾‍♂️ 🧘🏿‍♂️ 🏄‍♀️ 🏄🏻‍♀️ 🏄🏼‍♀️ 🏄🏽‍♀️ 🏄🏾‍♀️ 🏄🏿‍♀️ 🏄‍♂️ 🏄🏻‍♂️ 🏄🏼‍♂️ 🏄🏽‍♂️ 🏄🏾‍♂️ 🏄🏿‍♂️ 🏊‍♀️ 🏊🏻‍♀️ 🏊🏼‍♀️ 🏊🏽‍♀️ 🏊🏾‍♀️ 🏊🏿‍♀️ 🏊‍♂️ 🏊🏻‍♂️ 🏊🏼‍♂️ 🏊🏽‍♂️ 🏊🏾‍♂️ 🏊🏿‍♂️ 🤽‍♀️ 🤽🏻‍♀️ 🤽🏼‍♀️ 🤽🏽‍♀️ 🤽🏾‍♀️ 🤽🏿‍♀️ 🤽‍♂️ 🤽🏻‍♂️ 🤽🏼‍♂️ 🤽🏽‍♂️ 🤽🏾‍♂️ 🤽🏿‍♂️ 🚣‍♀️ 🚣🏻‍♀️ 🚣🏼‍♀️ 🚣🏽‍♀️ 🚣🏾‍♀️ 🚣🏿‍♀️ 🚣‍♂️ 🚣🏻‍♂️ 🚣🏼‍♂️ 🚣🏽‍♂️ 🚣🏾‍♂️ 🚣🏿‍♂️ 🧗‍♀️ 🧗🏻‍♀️ 🧗🏼‍♀️ 🧗🏽‍♀️ 🧗🏾‍♀️ 🧗🏿‍♀️ 🧗‍♂️ 🧗🏻‍♂️ 🧗🏼‍♂️ 🧗🏽‍♂️ 🧗🏾‍♂️ 🧗🏿‍♂️ 🚵‍♀️ 🚵🏻‍♀️ 🚵🏼‍♀️ 🚵🏽‍♀️ 🚵🏾‍♀️ 🚵🏿‍♀️ 🚵‍♂️ 🚵🏻‍♂️ 🚵🏼‍♂️ 🚵🏽‍♂️ 🚵🏾‍♂️ 🚵🏿‍♂️ 🚴‍♀️ 🚴🏻‍♀️ 🚴🏼‍♀️ 🚴🏽‍♀️ 🚴🏾‍♀️ 🚴🏿‍♀️ 🚴‍♂️ 🚴🏻‍♂️ 🚴🏼‍♂️ 🚴🏽‍♂️ 🚴🏾‍♂️ 🚴🏿‍♂️ 🏆 🥇 🥈 🥉 🏅 🎖 🏵 🎗 🎫 🎟 🎪 🤹‍♀️ 🤹🏻‍♀️ 🤹🏼‍♀️ 🤹🏽‍♀️ 🤹🏾‍♀️ 🤹🏿‍♀️ 🤹‍♂️ 🤹🏻‍♂️ 🤹🏼‍♂️ 🤹🏽‍♂️ 🤹🏾‍♂️ 🤹🏿‍♂️ 🎭 🎨 🎬 🎤 🎧 🎼 🎹 🥁 🎷 🎺 🎸 🎻 🎲 🧩 ♟ 🎯 🎳 🎮 🎰🚗 🚕 🚙 🚌 🚎 🏎 🚓 🚑 🚒 🚐 🚚 🚛 🚜 🛴 🚲 🛵 🏍 🚨 🚔 🚍 🚘 🚖 🚡 🚠 🚟 🚃 🚋 🚞 🚝 🚄 🚅 🚈 🚂 🚆 🚇 🚊 🚉 ✈️ 🛫 🛬 🛩 💺 🛰 🚀 🛸 🚁 🛶 ⛵️ 🚤 🛥 🛳 ⛴ 🚢 ⚓️ ⛽️ 🚧 🚦 🚥 🚏 🗺 🗿 🗽 🗼 🏰 🏯 🏟 🎡 🎢 🎠 ⛲️ ⛱ 🏖 🏝 🏜 🌋 ⛰ 🏔 🗻 🏕 ⛺️ 🏠 🏡 🏘 🏚 🏗 🏭 🏢 🏬 🏣 🏤 🏥 🏦 🏨 🏪 🏫 🏩 💒 🏛 ⛪️ 🕌 🕍 🕋 ⛩ 🛤 🛣 🗾 🎑 🏞 🌅 🌄 🌠 🎇 🎆 🌇 🌆 🏙 🌃 🌌 🌉 🌁⌚️ 📱 📲 💻 ⌨️ 🖥 🖨 🖱 🖲 🕹 🗜 💽 💾 💿 📀 📼 📷 📸 📹 🎥 📽 🎞 📞 ☎️ 📟 📠 📺 📻 🎙 🎚 🎛 ⏱ ⏲ ⏰ 🕰 ⌛️ ⏳ 📡 🔋 🔌 💡 🔦 🕯 🗑 🛢 💸 💵 💴 💶 💷 💰 💳 🧾 💎 ⚖️ 🔧 🔨 ⚒ 🛠 ⛏ 🔩 ⚙️ ⛓ 🔫 💣 🔪 🗡 ⚔️ 🛡 🚬 ⚰️ ⚱️ 🏺 🧭 🧱 🔮 🧿 🧸 📿 💈 ⚗️ 🔭 🧰 🧲 🧪 🧫 🧬 🧯 🔬 🕳 💊 💉 🌡 🚽 🚰 🚿 🛁 🛀 🛀🏻 🛀🏼 🛀🏽 🛀🏾 🛀🏿 🧴 🧵 🧶 🧷 🧹 🧺 🧻 🧼 🧽 🛎 🔑 🗝 🚪 🛋 🛏 🛌 🖼 🛍 🧳 🛒 🎁 🎈 🎏 🎀 🎊 🎉 🧨 🎎 🏮 🎐 🧧 ✉️ 📩 📨 📧 💌 📥 📤 📦 🏷 📪 📫 📬 📭 📮 📯 📜 📃 📄 📑 📊 📈 📉 🗒 🗓 📆 📅 📇 🗃 🗳 🗄 📋 📁 📂 🗂 🗞 📰 📓 📔 📒 📕 📗 📘 📙 📚 📖 🔖 🔗 📎 🖇 📐 📏 📌 📍 ✂️ 🖊 🖋 ✒️ 🖌 🖍 📝 ✏️ 🔍 🔎 🔏 🔐 🔒 🔓❤️ 🧡 💛 💚 💙 💜 🖤 💔 ❣️ 💕 💞 💓 💗 💖 💘 💝 💟 ☮️ ✝️ ☪️ 🕉 ☸️ ✡️ 🔯 🕎 ☯️ ☦️ 🛐 ⛎ ♈️ ♉️ ♊️ ♋️ ♌️ ♍️ ♎️ ♏️ ♐️ ♑️ ♒️ ♓️ 🆔 ⚛️ 🉑 ☢️ ☣️ 📴 📳 🈶 🈚️ 🈸 🈺 🈷️ ✴️ 🆚 💮 🉐 ㊙️ ㊗️ 🈴 🈵 🈹 🈲 🅰️ 🅱️ 🆎 🆑 🅾️ 🆘 ❌ ⭕️ 🛑 ⛔️ 📛 🚫 💯 💢 ♨️ 🚷 🚯 🚳 🚱 🔞 📵 🚭 ❗️ ❕ ❓ ❔ ‼️ ⁉️ 🔅 🔆 〽️ ⚠️ 🚸 🔱 ⚜️ 🔰 ♻️ ✅ 🈯️ 💹 ❇️ ✳️ ❎ 🌐 💠 Ⓜ️ 🌀 💤 🏧 🚾 ♿️ 🅿️ 🈳 🈂️ 🛂 🛃 🛄 🛅 🚹 🚺 🚼 🚻 🚮 🎦 📶 🈁 🔣 ℹ️ 🔤 🔡 🔠 🆖 🆗 🆙 🆒 🆕 🆓 0️⃣ 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣ 8️⃣ 9️⃣ 🔟 🔢 #️⃣ *️⃣ ⏏️ ▶️ ⏸ ⏯ ⏹ ⏺ ⏭ ⏮ ⏩ ⏪ ⏫ ⏬ ◀️ 🔼 🔽 ➡️ ⬅️ ⬆️ ⬇️ ↗️ ↘️ ↙️ ↖️ ↕️ ↔️ ↪️ ↩️ ⤴️ ⤵️ 🔀 🔁 🔂 🔄 🔃 🎵 🎶 ➕ ➖ ➗ ✖️ ♾ 💲 💱 ™️ ©️ ®️ 〰️ ➰ ➿ 🔚 🔙 🔛 🔝 🔜 ✔️ ☑️ 🔘 ⚪️ ⚫️ 🔴 🔵 🔺 🔻 🔸 🔹 🔶 🔷 🔳 🔲 ▪️ ▫️ ◾️ ◽️ ◼️ ◻️ ⬛️ ⬜️ 🔈 🔇 🔉 🔊 🔔 🔕 📣 📢 👁‍🗨 💬 💭 🗯 ♠️ ♣️ ♥️ ♦️ 🃏 🎴 🀄️ 🕐 🕑 🕒 🕓 🕔 🕕 🕖 🕗 🕘 🕙 🕚 🕛 🕜 🕝 🕞 🕟 🕠 🕡 🕢 🕣 🕤 🕥 🕦 🕧🏳️ 🏴 🏁 🚩 🏳️‍🌈 🏴‍☠️ 🇦🇫 🇦🇽 🇦🇱 🇩🇿 🇦🇸 🇦🇩 🇦🇴 🇦🇮 🇦🇶 🇦🇬 🇦🇷 🇦🇲 🇦🇼 🇦🇺 🇦🇹 🇦🇿 🇧🇸 🇧🇭 🇧🇩 🇧🇧 🇧🇾 🇧🇪 🇧🇿 🇧🇯 🇧🇲 🇧🇹 🇧🇴 🇧🇦 🇧🇼 🇧🇷 🇮🇴 🇻🇬 🇧🇳 🇧🇬 🇧🇫 🇧🇮 🇰🇭 🇨🇲 🇨🇦 🇮🇨 🇨🇻 🇧🇶 🇰🇾 🇨🇫 🇹🇩 🇨🇱 🇨🇳 🇨🇽 🇨🇨 🇨🇴 🇰🇲 🇨🇬 🇨🇩 🇨🇰 🇨🇷 🇨🇮 🇭🇷 🇨🇺 🇨🇼 🇨🇾 🇨🇿 🇩🇰 🇩🇯 🇩🇲 🇩🇴 🇪🇨 🇪🇬 🇸🇻 🇬🇶 🇪🇷 🇪🇪 🇪🇹 🇪🇺 🇫🇰 🇫🇴 🇫🇯 🇫🇮 🇫🇷 🇬🇫 🇵🇫 🇹🇫 🇬🇦 🇬🇲 🇬🇪 🇩🇪 🇬🇭 🇬🇮 🇬🇷 🇬🇱 🇬🇩 🇬🇵 🇬🇺 🇬🇹 🇬🇬 🇬🇳 🇬🇼 🇬🇾 🇭🇹 🇭🇳 🇭🇰 🇭🇺 🇮🇸 🇮🇳 🇮🇩 🇮🇷 🇮🇶 🇮🇪 🇮🇲 🇮🇱 🇮🇹 🇯🇲 🇯🇵 🎌 🇯🇪 🇯🇴 🇰🇿 🇰🇪 🇰🇮 🇽🇰 🇰🇼 🇰🇬 🇱🇦 🇱🇻 🇱🇧 🇱🇸 🇱🇷 🇱🇾 🇱🇮 🇱🇹 🇱🇺 🇲🇴 🇲🇰 🇲🇬 🇲🇼 🇲🇾 🇲🇻 🇲🇱 🇲🇹 🇲🇭 🇲🇶 🇲🇷 🇲🇺 🇾🇹 🇲🇽 🇫🇲 🇲🇩 🇲🇨 🇲🇳 🇲🇪 🇲🇸 🇲🇦 🇲🇿 🇲🇲 🇳🇦 🇳🇷 🇳🇵 🇳🇱 🇳🇨 🇳🇿 🇳🇮 🇳🇪 🇳🇬 🇳🇺 🇳🇫 🇰🇵 🇲🇵 🇳🇴 🇴🇲 🇵🇰 🇵🇼 🇵🇸 🇵🇦 🇵🇬 🇵🇾 🇵🇪 🇵🇭 🇵🇳 🇵🇱 🇵🇹 🇵🇷 🇶🇦 🇷🇪 🇷🇴 🇷🇺 🇷🇼 🇼🇸 🇸🇲 🇸🇦 🇸🇳 🇷🇸 🇸🇨 🇸🇱 🇸🇬 🇸🇽 🇸🇰 🇸🇮 🇬🇸 🇸🇧 🇸🇴 🇿🇦 🇰🇷 🇸🇸 🇪🇸 🇱🇰 🇧🇱 🇸🇭 🇰🇳 🇱🇨 🇵🇲 🇻🇨 🇸🇩 🇸🇷 🇸🇿 🇸🇪 🇨🇭 🇸🇾 🇹🇼 🇹🇯 🇹🇿 🇹🇭 🇹🇱 🇹🇬 🇹🇰 🇹🇴 🇹🇹 🇹🇳 🇹🇷 🇹🇲 🇹🇨 🇹🇻 🇻🇮 🇺🇬 🇺🇦 🇦🇪 🇬🇧 🏴󠁧󠁢󠁥󠁮󠁧󠁿 🏴󠁧󠁢󠁳󠁣󠁴󠁿 🏴󠁧󠁢󠁷󠁬󠁳󠁿 🇺🇳 🇺🇸 🇺🇾 🇺🇿 🇻🇺 🇻🇦 🇻🇪 🇻🇳 🇼🇫 🇪🇭 🇾🇪 🇿🇲 🇿🇼🥱 🤏 🦾 🦿 🦻 🧏 🧏‍♂️ 🧏‍♀️ 🧍 🧍‍♂️ 🧍‍♀️ 🧎 🧎‍♂️ 🧎‍♀️ 👨‍🦯 👩‍🦯 👨‍🦼 👩‍🦼 👨‍🦽 👩‍🦽 🦧 🦮 🐕‍🦺 🦥 🦦 🦨 🦩 🧄 🧅 🧇 🧆 🧈 🦪 🧃 🧉 🧊 🛕 🦽 🦼 🛺 🪂 🪐 🤿 🪀 🪁 🦺 🥻 🩱 🩲 🩳 🩰 🪕 🪔 🪓 🦯 🩸 🩹 🩺 🪑 🪒 🤎 🤍 🟠 🟡 🟢 🟣 🟤 🟥 🟧 🟨 🟩 🟦 🟪 🟫 + + diff --git a/src/tests/backend/specs/api/fuzzImportTest.ts b/src/tests/backend/specs/api/fuzzImportTest.ts new file mode 100644 index 000000000..3caa185da --- /dev/null +++ b/src/tests/backend/specs/api/fuzzImportTest.ts @@ -0,0 +1,70 @@ +/* + * Fuzz testing the import endpoint + */ +/* +const common = require('../../common'); +const froth = require('mocha-froth'); +const request = require('request'); +const settings = require('../../../container/loadSettings.js').loadSettings(); + +const host = "http://" + settings.ip + ":" + settings.port; + +var apiVersion = 1; +var testPadId = "TEST_fuzz" + makeid(); + +var endPoint = function(point, version){ + version = version || apiVersion; + return '/api/'+version+'/'+point+'?apikey='+apiKey; +} + +//console.log("Testing against padID", testPadId); +//console.log("To watch the test live visit " + host + "/p/" + testPadId); +//console.log("Tests will start in 5 seconds, click the URL now!"); + +setTimeout(function(){ + for (let i=1; i<5; i++) { // 5000 runs + setTimeout( function timer(){ + runTest(i); + }, i*100 ); // 100 ms + } + process.exit(0); +},5000); // wait 5 seconds + +function runTest(number){ + request(host + endPoint('createPad') + '&padID=' + testPadId, function(err, res, body){ + var req = request.post(host + '/p/'+testPadId+'/import', function (err, res, body) { + if (err) { + throw new Error("FAILURE", err); + }else{ + console.log("Success"); + } + }); + + var fN = '/tmp/fuzztest.txt'; + var cT = 'text/plain'; + + if (number % 2 == 0) { + fN = froth().toString(); + cT = froth().toString(); + } + + let form = req.form(); + + form.append('file', froth().toString(), { + filename: fN, + contentType: cT + }); +console.log("here"); + }); +} + +function makeid() { + var text = ""; + var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + + for( var i=0; i < 5; i++ ){ + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; +} +*/ diff --git a/src/tests/backend/specs/api/image.png b/src/tests/backend/specs/api/image.png new file mode 100644 index 000000000..0694e2c2d Binary files /dev/null and b/src/tests/backend/specs/api/image.png differ diff --git a/src/tests/backend/specs/api/importexport.ts b/src/tests/backend/specs/api/importexport.ts new file mode 100644 index 000000000..5b93ea346 --- /dev/null +++ b/src/tests/backend/specs/api/importexport.ts @@ -0,0 +1,288 @@ +'use strict'; +/* + * ACHTUNG: there is a copied & modified version of this file in + * /src/tests/container/spacs/api/pad.js + * + * TODO: unify those two files, and merge in a single one. + */ + +import { strict as assert } from 'assert'; +import {MapArrayType} from "../../../../node/types/MapType"; +const common = require('../../common'); + +let agent:any; +const apiVersion = 1; + +const endPoint = (point: string, version?:string) => `/api/${version || apiVersion}/${point}`; + +const testImports:MapArrayType = { + 'malformed': { + input: '
  • wtf', + wantHTML: 'wtf

    ', + wantText: 'wtf\n\n', + disabled: true, + }, + 'nonelistiteminlist #3620': { + input: '
      test
    • FOO
    ', + wantHTML: '
      test
    • FOO

    ', + wantText: '\ttest\n\t* FOO\n\n', + disabled: true, + }, + 'whitespaceinlist #3620': { + input: '
    • FOO
    ', + wantHTML: '
    • FOO

    ', + wantText: '\t* FOO\n\n', + }, + 'prefixcorrectlinenumber': { + input: '
    1. should be 1
    2. should be 2
    ', + wantHTML: '
    1. should be 1
    2. should be 2

    ', + wantText: '\t1. should be 1\n\t2. should be 2\n\n', + }, + 'prefixcorrectlinenumbernested': { + input: '
    1. should be 1
      1. foo
    2. should be 2
    ', + wantHTML: '
    1. should be 1
      1. foo
    2. should be 2

    ', + wantText: '\t1. should be 1\n\t\t1.1. foo\n\t2. should be 2\n\n', + }, + + /* + "prefixcorrectlinenumber when introduced none list item - currently not supported see #3450": { + input: '
    1. should be 1
    2. test
    3. should be 2
    ', + wantHTML: '
    1. should be 1
    2. test
    3. should be 2

    ', + wantText: '\t1. should be 1\n\ttest\n\t2. should be 2\n\n', + } + , + "newlinesshouldntresetlinenumber #2194": { + input: '
    1. should be 1
    2. test
    3. should be 2
    ', + wantHTML: '
    1. should be 1
    2. test
    3. should be 2

    ', + wantText: '\t1. should be 1\n\ttest\n\t2. should be 2\n\n', + } + */ + 'ignoreAnyTagsOutsideBody': { + description: 'Content outside body should be ignored', + input: 'titleempty
    ', + wantHTML: 'empty

    ', + wantText: 'empty\n\n', + }, + 'indentedListsAreNotBullets': { + description: 'Indented lists are represented with tabs and without bullets', + input: '
    • indent
    • indent
    ', + wantHTML: '
    • indent
    • indent

    ', + wantText: '\tindent\n\tindent\n\n', + }, + 'lineWithMultipleSpaces': { + description: 'Multiple spaces should be collapsed', + input: 'Text with more than one space.
    ', + wantHTML: 'Text with more than one space.

    ', + wantText: 'Text with more than one space.\n\n', + }, + 'lineWithMultipleNonBreakingAndNormalSpaces': { + // XXX the HTML between "than" and "one" looks strange + description: 'non-breaking space should be preserved, but can be replaced when it', + input: 'Text with  more   than  one space.
    ', + wantHTML: 'Text with  more   than  one space.

    ', + wantText: 'Text with more than one space.\n\n', + }, + 'multiplenbsp': { + description: 'Multiple non-breaking space should be preserved', + input: '  
    ', + wantHTML: '  

    ', + wantText: ' \n\n', + }, + 'multipleNonBreakingSpaceBetweenWords': { + description: 'A normal space is always inserted before a word', + input: '  word1  word2   word3
    ', + wantHTML: '  word1  word2   word3

    ', + wantText: ' word1 word2 word3\n\n', + }, + 'nonBreakingSpacePreceededBySpaceBetweenWords': { + description: 'A non-breaking space preceded by a normal space', + input: '  word1  word2  word3
    ', + wantHTML: ' word1  word2  word3

    ', + wantText: ' word1 word2 word3\n\n', + }, + 'nonBreakingSpaceFollowededBySpaceBetweenWords': { + description: 'A non-breaking space followed by a normal space', + input: '  word1  word2  word3
    ', + wantHTML: '  word1  word2  word3

    ', + wantText: ' word1 word2 word3\n\n', + }, + 'spacesAfterNewline': { + description: 'Collapse spaces that follow a newline', + input: 'something
    something
    ', + wantHTML: 'something
    something

    ', + wantText: 'something\nsomething\n\n', + }, + 'spacesAfterNewlineP': { + description: 'Collapse spaces that follow a paragraph', + input: 'something

    something
    ', + wantHTML: 'something

    something

    ', + wantText: 'something\n\nsomething\n\n', + }, + 'spacesAtEndOfLine': { + description: 'Collapse spaces that preceed/follow a newline', + input: 'something
    something
    ', + wantHTML: 'something
    something

    ', + wantText: 'something\nsomething\n\n', + }, + 'spacesAtEndOfLineP': { + description: 'Collapse spaces that preceed/follow a paragraph', + input: 'something

    something
    ', + wantHTML: 'something

    something

    ', + wantText: 'something\n\nsomething\n\n', + }, + 'nonBreakingSpacesAfterNewlines': { + description: 'Don\'t collapse non-breaking spaces that follow a newline', + input: 'something
       something
    ', + wantHTML: 'something
       something

    ', + wantText: 'something\n something\n\n', + }, + 'nonBreakingSpacesAfterNewlinesP': { + description: 'Don\'t collapse non-breaking spaces that follow a paragraph', + input: 'something

       something
    ', + wantHTML: 'something

       something

    ', + wantText: 'something\n\n something\n\n', + }, + 'collapseSpacesInsideElements': { + description: 'Preserve only one space when multiple are present', + input: 'Need more space s !
    ', + wantHTML: 'Need more space s !

    ', + wantText: 'Need more space s !\n\n', + }, + 'collapseSpacesAcrossNewlines': { + description: 'Newlines and multiple spaces across newlines should be collapsed', + input: ` + Need + more + space + s + !
    `, + wantHTML: 'Need more space s !

    ', + wantText: 'Need more space s !\n\n', + }, + 'multipleNewLinesAtBeginning': { + description: 'Multiple new lines and paragraphs at the beginning should be preserved', + input: '

    first line

    second line
    ', + wantHTML: '



    first line

    second line

    ', + wantText: '\n\n\n\nfirst line\n\nsecond line\n\n', + }, + 'multiLineParagraph': { + description: 'A paragraph with multiple lines should not loose spaces when lines are combined', + input: ` +

    + а б в г ґ д е є ж з и і ї й к л м н о + п р с т у ф х ц ч ш щ ю я ь +

    +`, + wantHTML: 'а б в г ґ д е є ж з и і ї й к л м н о п р с т у ф х ц ч ш щ ю я ь

    ', + wantText: 'а б в г ґ д е є ж з и і ї й к л м н о п р с т у ф х ц ч ш щ ю я ь\n\n', + }, + 'multiLineParagraphWithPre': { + // XXX why is there   before "in"? + description: 'lines in preformatted text should be kept intact', + input: ` +

    + а б в г ґ д е є ж з и і ї й к л м н о

    multiple
    +   lines
    + in
    +      pre
    +

    п р с т у ф х ц ч ш щ ю я +ь

    +`, + wantHTML: 'а б в г ґ д е є ж з и і ї й к л м н о
    multiple
       lines
     in
          pre

    п р с т у ф х ц ч ш щ ю я ь

    ', + wantText: 'а б в г ґ д е є ж з и і ї й к л м н о\nmultiple\n lines\n in\n pre\n\nп р с т у ф х ц ч ш щ ю я ь\n\n', + }, + 'preIntroducesASpace': { + description: 'pre should be on a new line not preceded by a space', + input: `

    + 1 +

    preline
    +

    `, + wantHTML: '1
    preline


    ', + wantText: '1\npreline\n\n\n', + }, + 'dontDeleteSpaceInsideElements': { + description: 'Preserve spaces inside elements', + input: 'Need more space s !
    ', + wantHTML: 'Need more space s !

    ', + wantText: 'Need more space s !\n\n', + }, + 'dontDeleteSpaceOutsideElements': { + description: 'Preserve spaces outside elements', + input: 'Need more space s !
    ', + wantHTML: 'Need more space s !

    ', + wantText: 'Need more space s !\n\n', + }, + 'dontDeleteSpaceAtEndOfElement': { + description: 'Preserve spaces at the end of an element', + input: 'Need more space s !
    ', + wantHTML: 'Need more space s !

    ', + wantText: 'Need more space s !\n\n', + }, + 'dontDeleteSpaceAtBeginOfElements': { + description: 'Preserve spaces at the start of an element', + input: 'Need more space s !
    ', + wantHTML: 'Need more space s !

    ', + wantText: 'Need more space s !\n\n', + }, +}; + +describe(__filename, function () { + this.timeout(1000); + + before(async function () { agent = await common.init(); }); + + Object.keys(testImports).forEach((testName) => { + describe(testName, function () { + const testPadId = makeid(); + const test = testImports[testName]; + if (test.disabled) { + return xit(`DISABLED: ${testName}`, function (done) { + done(); + }); + } + + it('createPad', async function () { + const res = await agent.get(`${endPoint('createPad')}?padID=${testPadId}`) + .set("authorization", await common.generateJWTToken()) + .expect(200) + .expect('Content-Type', /json/); + assert.equal(res.body.code, 0); + }); + + it('setHTML', async function () { + const res = await agent.get(`${endPoint('setHTML')}?padID=${testPadId}` + + `&html=${encodeURIComponent(test.input)}`) + .set("authorization", await common.generateJWTToken()) + .expect(200) + .expect('Content-Type', /json/); + assert.equal(res.body.code, 0); + }); + + it('getHTML', async function () { + const res = await agent.get(`${endPoint('getHTML')}?padID=${testPadId}`) + .set("authorization", await common.generateJWTToken()) + .expect(200) + .expect('Content-Type', /json/); + assert.equal(res.body.data.html, test.wantHTML); + }); + + it('getText', async function () { + const res = await agent.get(`${endPoint('getText')}?padID=${testPadId}`) + .set("authorization", await common.generateJWTToken()) + .expect(200) + .expect('Content-Type', /json/); + assert.equal(res.body.data.text, test.wantText); + }); + }); + }); +}); + +function makeid() { + let text = ''; + const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + + for (let i = 0; i < 5; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; +} diff --git a/src/tests/backend/specs/api/importexportGetPost.ts b/src/tests/backend/specs/api/importexportGetPost.ts new file mode 100644 index 000000000..355699bc2 --- /dev/null +++ b/src/tests/backend/specs/api/importexportGetPost.ts @@ -0,0 +1,805 @@ +'use strict'; + +/* + * Import and Export tests for the /p/whateverPadId/import and /p/whateverPadId/export endpoints. + */ + +import {MapArrayType} from "../../../../node/types/MapType"; +import {SuperTestStatic} from "supertest"; +import TestAgent from "supertest/lib/agent"; + +const assert = require('assert').strict; +const common = require('../../common'); +const fs = require('fs'); +const settings = require('../../../../node/utils/Settings'); +const superagent = require('superagent'); +const padManager = require('../../../../node/db/PadManager'); +const plugins = require('../../../../static/js/pluginfw/plugin_defs'); + +const padText = fs.readFileSync(`${__dirname}/test.txt`); +const etherpadDoc = fs.readFileSync(`${__dirname}/test.etherpad`); +const wordDoc = fs.readFileSync(`${__dirname}/test.doc`); +const wordXDoc = fs.readFileSync(`${__dirname}/test.docx`); +const odtDoc = fs.readFileSync(`${__dirname}/test.odt`); +const pdfDoc = fs.readFileSync(`${__dirname}/test.pdf`); + +let agent: TestAgent; +const apiVersion = 1; +const testPadId = makeid(); +const testPadIdEnc = encodeURIComponent(testPadId); + +const deleteTestPad = async () => { + if (await padManager.doesPadExist(testPadId)) { + const pad = await padManager.getPad(testPadId); + await pad.remove(); + } +}; + +describe(__filename, function () { + this.timeout(45000); + before(async function () { agent = await common.init(); }); + + describe('Connectivity', function () { + it('can connect', async function () { + await agent.get('/api/') + .set("authorization", await common.generateJWTToken()) + .expect(200) + .expect('Content-Type', /json/); + }); + }); + + describe('API Versioning', function () { + it('finds the version tag', async function () { + await agent.get('/api/') + .set("authorization", await common.generateJWTToken()) + .expect(200) + .expect((res:any) => assert(res.body.currentVersion)); + }); + }); + + /* + Tests + ----- + + Test. + / Create a pad + / Set pad contents + / Try export pad in various formats + / Get pad contents and ensure it matches imported contents + + Test. + / Try to export a pad that doesn't exist // Expect failure + + Test. + / Try to import an unsupported file to a pad that exists + + -- TODO: Test. + Try to import to a file and abort it half way through + + Test. + Try to import to files of varying size. + + Example Curl command for testing import URI: + curl -s -v --form file=@/home/jose/test.txt http://127.0.0.1:9001/p/foo/import + */ + + describe('Imports and Exports', function () { + const backups:MapArrayType = {}; + + beforeEach(async function () { + backups.hooks = {}; + for (const hookName of ['preAuthorize', 'authenticate', 'authorize']) { + backups.hooks[hookName] = plugins.hooks[hookName]; + plugins.hooks[hookName] = []; + } + // Note: This is a shallow copy. + backups.settings = Object.assign({}, settings); + settings.requireAuthentication = false; + settings.requireAuthorization = false; + settings.users = {user: {password: 'user-password'}}; + }); + + afterEach(async function () { + Object.assign(plugins.hooks, backups.hooks); + // Note: This does not unset settings that were added. + Object.assign(settings, backups.settings); + }); + + it('creates a new Pad, imports content to it, checks that content', async function () { + await agent.get(`${endPoint('createPad')}?padID=${testPadId}`) + .set("authorization", await common.generateJWTToken()) + .expect(200) + .expect('Content-Type', /json/) + .expect((res:any) => assert.equal(res.body.code, 0)); + await agent.post(`/p/${testPadId}/import`) + .set("authorization", await common.generateJWTToken()) + .attach('file', padText, {filename: '/test.txt', contentType: 'text/plain'}) + .expect(200); + await agent.get(`${endPoint('getText')}?padID=${testPadId}`) + .set("authorization", await common.generateJWTToken()) + .expect(200) + .expect((res:any) => assert.equal(res.body.data.text, padText.toString())); + }); + + describe('export from read-only pad ID', function () { + let readOnlyId:string; + + // This ought to be before(), but it must run after the top-level beforeEach() above. + beforeEach(async function () { + if (readOnlyId != null) return; + await agent.post(`/p/${testPadId}/import`) + .set("authorization", await common.generateJWTToken()) + .attach('file', padText, {filename: '/test.txt', contentType: 'text/plain'}) + .expect(200); + const res = await agent.get(`${endPoint('getReadOnlyID')}?padID=${testPadId}`) + .set("authorization", await common.generateJWTToken()) + .expect(200) + .expect('Content-Type', /json/) + .expect((res:any) => assert.equal(res.body.code, 0)); + readOnlyId = res.body.data.readOnlyID; + }); + + for (const authn of [false, true]) { + describe(`requireAuthentication = ${authn}`, function () { + // This ought to be before(), but it must run after the top-level beforeEach() above. + beforeEach(async function () { + settings.requireAuthentication = authn; + }); + + for (const exportType of ['html', 'txt', 'etherpad']) { + describe(`export to ${exportType}`, function () { + let text:string; + + // This ought to be before(), but it must run after the top-level beforeEach() above. + beforeEach(async function () { + if (text != null) return; + let req = agent.get(`/p/${readOnlyId}/export/${exportType}`) + .set("authorization", await common.generateJWTToken()); + if (authn) req = req.auth('user', 'user-password'); + const res = await req + .expect(200) + .buffer(true).parse(superagent.parse.text); + text = res.text; + }); + + it('export OK', async function () { + assert.match(text, /This is the/); + }); + + it('writable pad ID is not leaked', async function () { + assert(!text.includes(testPadId)); + }); + + it('re-import to read-only pad ID gives 403 forbidden', async function () { + let req = agent.post(`/p/${readOnlyId}/import`) + .set("authorization", await common.generateJWTToken()) + .attach('file', Buffer.from(text), { + filename: `/test.${exportType}`, + contentType: 'text/plain', + }); + if (authn) req = req.auth('user', 'user-password'); + await req.expect(403); + }); + + it('re-import to read-write pad ID gives 200 OK', async function () { + // The new pad ID must differ from testPadId because Etherpad refuses to import + // .etherpad files on top of a pad that already has edits. + let req = agent.post(`/p/${testPadId}_import/import`) + .set("authorization", await common.generateJWTToken()) + .attach('file', Buffer.from(text), { + filename: `/test.${exportType}`, + contentType: 'text/plain', + }); + if (authn) req = req.auth('user', 'user-password'); + await req.expect(200); + }); + }); + } + }); + } + }); + + describe('Import/Export tests requiring AbiWord/LibreOffice', function () { + before(async function () { + if ((!settings.abiword || settings.abiword.indexOf('/') === -1) && + (!settings.soffice || settings.soffice.indexOf('/') === -1)) { + this.skip(); + } + }); + + // For some reason word import does not work in testing.. + // TODO: fix support for .doc files.. + it('Tries to import .doc that uses soffice or abiword', async function () { + await agent.post(`/p/${testPadId}/import`) + .set("authorization", await common.generateJWTToken()) + .attach('file', wordDoc, {filename: '/test.doc', contentType: 'application/msword'}) + .expect(200) + .expect('Content-Type', /json/) + .expect((res:any) => assert.deepEqual(res.body, { + code: 0, + message: 'ok', + data: {directDatabaseAccess: false}, + })); + }); + + it('exports DOC', async function () { + await agent.get(`/p/${testPadId}/export/doc`) + .set("authorization", await common.generateJWTToken()) + .buffer(true).parse(superagent.parse['application/octet-stream']) + .expect(200) + .expect((res:any) => assert(res.body.length >= 9000)); + }); + + it('Tries to import .docx that uses soffice or abiword', async function () { + await agent.post(`/p/${testPadId}/import`) + .set("authorization", await common.generateJWTToken()) + .attach('file', wordXDoc, { + filename: '/test.docx', + contentType: + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + }) + .expect(200) + .expect('Content-Type', /json/) + .expect((res:any) => assert.deepEqual(res.body, { + code: 0, + message: 'ok', + data: {directDatabaseAccess: false}, + })); + }); + + it('exports DOC from imported DOCX', async function () { + await agent.get(`/p/${testPadId}/export/doc`) + .set("authorization", await common.generateJWTToken()) + .buffer(true).parse(superagent.parse['application/octet-stream']) + .expect(200) + .expect((res:any) => assert(res.body.length >= 9100)); + }); + + it('Tries to import .pdf that uses soffice or abiword', async function () { + await agent.post(`/p/${testPadId}/import`) + .set("authorization", await common.generateJWTToken()) + .attach('file', pdfDoc, {filename: '/test.pdf', contentType: 'application/pdf'}) + .expect(200) + .expect('Content-Type', /json/) + .expect((res:any) => assert.deepEqual(res.body, { + code: 0, + message: 'ok', + data: {directDatabaseAccess: false}, + })); + }); + + it('exports PDF', async function () { + await agent.get(`/p/${testPadId}/export/pdf`) + .set("authorization", await common.generateJWTToken()) + .buffer(true).parse(superagent.parse['application/octet-stream']) + .expect(200) + .expect((res:any) => assert(res.body.length >= 1000)); + }); + + it('Tries to import .odt that uses soffice or abiword', async function () { + await agent.post(`/p/${testPadId}/import`) + .set("authorization", await common.generateJWTToken()) + .attach('file', odtDoc, {filename: '/test.odt', contentType: 'application/odt'}) + .expect(200) + .expect('Content-Type', /json/) + .expect((res:any) => assert.deepEqual(res.body, { + code: 0, + message: 'ok', + data: {directDatabaseAccess: false}, + })); + }); + + it('exports ODT', async function () { + await agent.get(`/p/${testPadId}/export/odt`) + .set("authorization", await common.generateJWTToken()) + .buffer(true).parse(superagent.parse['application/octet-stream']) + .expect(200) + .expect((res:any) => assert(res.body.length >= 7000)); + }); + }); // End of AbiWord/LibreOffice tests. + + it('Tries to import .etherpad', async function () { + this.timeout(3000); + await agent.post(`/p/${testPadId}/import`) + .set("authorization", await common.generateJWTToken()) + .attach('file', etherpadDoc, { + filename: '/test.etherpad', + contentType: 'application/etherpad', + }) + .expect(200) + .expect('Content-Type', /json/) + .expect((res:any) => assert.deepEqual(res.body, { + code: 0, + message: 'ok', + data: {directDatabaseAccess: true}, + })); + }); + + it('exports Etherpad', async function () { + this.timeout(3000); + await agent.get(`/p/${testPadId}/export/etherpad`) + .set("authorization", await common.generateJWTToken()) + .buffer(true).parse(superagent.parse.text) + .expect(200) + .expect(/hello/); + }); + + it('exports HTML for this Etherpad file', async function () { + this.timeout(3000); + await agent.get(`/p/${testPadId}/export/html`) + .set("authorization", await common.generateJWTToken()) + .expect(200) + .expect('content-type', 'text/html; charset=utf-8') + .expect(/