diff --git a/.babelrc b/.babelrc index 55de8382cc..e5efe292f9 100644 --- a/.babelrc +++ b/.babelrc @@ -1,19 +1,20 @@ -{ - "presets": [ - [ - "@babel/preset-env", - { - "useBuiltIns": "entry", - "corejs": "3.22" - } - ] - ], - "plugins": [ - "html-tag-js/jsx/jsx-to-tag.js", - "html-tag-js/jsx/syntax-parser.js", - "@babel/plugin-transform-runtime", - "@babel/plugin-transform-block-scoping" - ], - "compact": false, - "sourceMaps": "inline" -} \ No newline at end of file +{ + "presets": [ + [ + "@babel/preset-env", + { + "useBuiltIns": "entry", + "corejs": "3.22" + } + ], + "@babel/preset-typescript" + ], + "plugins": [ + "html-tag-js/jsx/jsx-to-tag.js", + "html-tag-js/jsx/syntax-parser.js", + "@babel/plugin-transform-runtime", + "@babel/plugin-transform-block-scoping" + ], + "compact": false, + "sourceMaps": "inline" +} diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000000..7545f75644 --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,76 @@ +# Acode Development Container +# +# Devcontainer usage: automatic via devcontainer.json +# Standalone usage: +# docker build --target standalone -t acode-dev .devcontainer/ +# docker run -it -v $(pwd):/workspaces/acode acode-dev + +FROM mcr.microsoft.com/devcontainers/java:1-21-bookworm AS base + +ARG ANDROID_PLATFORM=36 +ARG ANDROID_BUILD_TOOLS=36.0.0 +ARG CMDLINE_TOOLS_VERSION=11076708 +ARG NODE_VERSION=22 +ARG GRADLE_VERSION=8.11 + +ENV GRADLE_HOME=/opt/gradle + +# removes broken yarn repo present in base image +RUN rm -f /etc/apt/sources.list.d/yarn.list + +RUN apt-get update && apt-get install -y --no-install-recommends \ + wget \ + unzip \ + curl \ + && rm -rf /var/lib/apt/lists/* + +# Install Gradle +RUN wget -q "https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-bin.zip" -O /tmp/gradle.zip \ + && unzip -q /tmp/gradle.zip -d /opt \ + && rm /tmp/gradle.zip \ + && ln -s /opt/gradle-${GRADLE_VERSION} ${GRADLE_HOME} + +ENV PATH="${PATH}:${GRADLE_HOME}/bin" + +WORKDIR /workspaces/acode + +LABEL org.opencontainers.image.authors="Acode Foundation " +LABEL description="Development environment for building Acode - Code Editor for Android" + + +# Devcontainer stage +# Android SDK and Node handled by devcontainer features. +FROM base AS devcontainer + + +# Standalone stage +# Includes Android SDK and Node/pnpm for plain docker build/run usage. +FROM base AS standalone + +ENV ANDROID_HOME=/usr/local/lib/android +ENV ANDROID_SDK_ROOT=/usr/local/lib/android +ENV PATH="${PATH}:${ANDROID_HOME}/cmdline-tools/latest/bin:${ANDROID_HOME}/platform-tools:${ANDROID_HOME}/build-tools/${ANDROID_BUILD_TOOLS}" + +# Install Android SDK +RUN mkdir -p ${ANDROID_HOME}/cmdline-tools \ + && cd ${ANDROID_HOME}/cmdline-tools \ + && wget -q "https://dl.google.com/android/repository/commandlinetools-linux-${CMDLINE_TOOLS_VERSION}_latest.zip" -O cmdline-tools.zip \ + && unzip -q cmdline-tools.zip \ + && rm cmdline-tools.zip \ + && mv cmdline-tools latest \ + && yes | ${ANDROID_HOME}/cmdline-tools/latest/bin/sdkmanager --licenses 2>/dev/null || true \ + && ${ANDROID_HOME}/cmdline-tools/latest/bin/sdkmanager --update \ + && ${ANDROID_HOME}/cmdline-tools/latest/bin/sdkmanager \ + "platform-tools" \ + "platforms;android-${ANDROID_PLATFORM}" \ + "build-tools;${ANDROID_BUILD_TOOLS}" + +# Install fnm and Node.js +ENV FNM_DIR=/usr/local/fnm +RUN curl -fsSL https://fnm.vercel.app/install | bash -s -- --install-dir "${FNM_DIR}" --skip-shell \ + && eval "$(${FNM_DIR}/fnm env)" \ + && fnm install ${NODE_VERSION} \ + && fnm default ${NODE_VERSION} \ + && npm install -g pnpm + +ENV PATH="${FNM_DIR}/aliases/default/bin:${PATH}" diff --git a/.devcontainer/devcontainer-lock.json b/.devcontainer/devcontainer-lock.json new file mode 100644 index 0000000000..e71fffa015 --- /dev/null +++ b/.devcontainer/devcontainer-lock.json @@ -0,0 +1,14 @@ +{ + "features": { + "ghcr.io/devcontainers/features/node:2.1": { + "version": "2.1.2", + "resolved": "ghcr.io/devcontainers/features/node@sha256:20ac718cc67e7999a9d3fbb8387f1a3a5d53ecbd41fe7c075ebadb8e9b431b17", + "integrity": "sha256:20ac718cc67e7999a9d3fbb8387f1a3a5d53ecbd41fe7c075ebadb8e9b431b17" + }, + "ghcr.io/nordcominc/devcontainer-features/android-sdk:2": { + "version": "2.0.0", + "resolved": "ghcr.io/nordcominc/devcontainer-features/android-sdk@sha256:17c25d5721b31e45564e864d5bdfead9eefab7a1624e69ac5cf51079e9f62f0b", + "integrity": "sha256:17c25d5721b31e45564e864d5bdfead9eefab7a1624e69ac5cf51079e9f62f0b" + } + } +} diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 1489d285f2..9b60c448ae 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,6 +1,45 @@ { - "image": "mcr.microsoft.com/devcontainers/universal:2", - "features": { - "ghcr.io/nordcominc/devcontainer-features/android-sdk:1": {} - } -} \ No newline at end of file + "name": "Acode Development", + "build": { + "dockerfile": "Dockerfile", + "target": "devcontainer" + }, + + "containerEnv": { + "JAVA_HOME": "/usr/local/openjdk-21" + }, + "remoteEnv": { + "JAVA_HOME": "/usr/local/openjdk-21", + "ANDROID_SDK_ROOT": "${containerEnv:ANDROID_HOME}", + "PATH": "${containerEnv:PATH}:${containerEnv:ANDROID_HOME}/build-tools/36.0.0" + }, + + "features": { + "ghcr.io/nordcominc/devcontainer-features/android-sdk:2": { + "platform": "36", + "build_tools": "36.0.0" + }, + "ghcr.io/devcontainers/features/node:2.1": { + "nodeGypDependencies": false, + "installYarnUsingApt": false, + "version": "lts", + "pnpmVersion": "latest", + "nvmVersion": "latest" + } + }, + "overrideCommand": true, + "postCreateCommand": "pnpm run setup", + "remoteUser": "root", + "customizations": { + "vscode": { + "extensions": ["biomejs.biome", "redhat.java"], + "settings": { + "editor.formatOnSave": true, + "editor.defaultFormatter": "biomejs.biome", + "[java]": { + "editor.defaultFormatter": "redhat.java" + } + } + } + } +} diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000..56e1f21c53 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,24 @@ +# Dependencies +node_modules/ +.pnpm-store/ + +# Build outputs +platforms/ +plugins/ +www/css/build/ +www/js/build/ + +# IDE +.vscode/ +.idea/ + +# Git +.git/ +.gitignore + +# Misc +*.log +*.apk +*.aab +.DS_Store +Thumbs.db diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..d015b0d352 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.sh text eol=lf +config.xml text eol=lf diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000000..421cbeac99 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,7 @@ +.github/CODEOWNERS @Acode-Foundation/acode + +# workflows +.github/workflows/nightly-build.yml @unschooledgamer +.github/workflows/on-demand-preview-releases-PR.yml @unschooledgamer +.github/workflows/community-release-notifier.yml @unschooledgamer +.github/workflows/nightly-release.yml @unschooledgamer diff --git a/.github/ISSUE_TEMPLATE/0_bug_report.yml b/.github/ISSUE_TEMPLATE/0_bug_report.yml index 308a129fb3..c24c87c4e9 100644 --- a/.github/ISSUE_TEMPLATE/0_bug_report.yml +++ b/.github/ISSUE_TEMPLATE/0_bug_report.yml @@ -1,6 +1,7 @@ name: Bug Report description: | Use this template for bug reports. +type: Bug labels: [] body: - type: checkboxes diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..d290d60bf5 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,17 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for more information: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates +# https://containers.dev/guide/dependabot + +version: 2 +updates: + - package-ecosystem: "devcontainers" + directory: "/" + schedule: + interval: weekly + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: weekly diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 0000000000..848bd7a5c6 --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,13 @@ +translations: + - any: + - changed-files: + - any-glob-to-any-file: 'src/lang/*.json' + +docs: + - any: + - changed-files: + - any-glob-to-any-file: '**/*.md' + +enhancement: + - any: + - head-branch: ['^feature', 'feature', '^feat', '^add'] \ No newline at end of file diff --git a/.github/workflows/add-pr-labels.yml b/.github/workflows/add-pr-labels.yml new file mode 100644 index 0000000000..28082a4181 --- /dev/null +++ b/.github/workflows/add-pr-labels.yml @@ -0,0 +1,17 @@ +name: Add Pull Requests Labels +on: + pull_request_target: + types: [opened, closed, ready_for_review] + +jobs: + add-labels: + timeout-minutes: 5 + runs-on: ubuntu-latest + + if: github.event.action == 'opened' + permissions: + contents: read + pull-requests: write + + steps: + - uses: actions/labeler@v7 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 788d228c41..db104d8948 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,7 +2,12 @@ name: CI on: push: + branches: + - main pull_request: + branches: + - '**' + merge_group: jobs: spell-check: @@ -12,10 +17,10 @@ jobs: steps: - name: Checkout Actions Repository - uses: actions/checkout@v5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Check spelling - uses: crate-ci/typos@master + uses: crate-ci/typos@main with: config: ./_typos.toml @@ -26,10 +31,69 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup Biome - uses: biomejs/setup-biome@v2 + uses: biomejs/setup-biome@4c91541eaada48f67d7dbd7833600ce162b68f51 # v2.7.1 - name: Run Biome run: biome ci . + + unit-tests: + name: Unit Tests (On PR Only) + timeout-minutes: 10 + runs-on: ubuntu-latest + permissions: + contents: read + if: github.event_name == 'pull_request' + steps: + - name: Checkout Repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + submodules: recursive + + - name: Use Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + cache: npm + cache-dependency-path: '**/package-lock.json' + + - name: Install dependencies + run: npm ci --no-audit --no-fund + + - name: Run unit tests + run: npm run test + + translation-check: + name: Translation Check (On PR Only) + timeout-minutes: 5 + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + if: github.event_name == 'pull_request' + steps: + - name: Checkout Repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + submodules: recursive + - name: Use Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + cache: npm + cache-dependency-path: '**/package-lock.json' + + - name: Detect Changed Files + uses: dorny/paths-filter@v4 + id: file-changes + with: + list-files: shell + filters: | + translation: + - 'src/lang/*.json' + token: ${{ secrets.GITHUB_TOKEN }} + - name: Translation Files Check (if changed) + if: steps.file-changes.outputs.translation == 'true' + run: | + npm ci --no-audit --no-fund + npm run lang check diff --git a/.github/workflows/close-inactive-issues.yml b/.github/workflows/close-inactive-issues.yml index bcb2e71dfb..7a85f97fe2 100644 --- a/.github/workflows/close-inactive-issues.yml +++ b/.github/workflows/close-inactive-issues.yml @@ -10,7 +10,7 @@ jobs: issues: write pull-requests: write steps: - - uses: actions/stale@v9 + - uses: actions/stale@v11 with: days-before-issue-stale: 60 days-before-issue-close: 14 @@ -22,9 +22,10 @@ jobs: Thanks for your help! close-issue-message: "This issue was closed because it has been inactive for 14 days since being marked as stale." + exempt-all-milestones: true days-before-pr-stale: -1 days-before-pr-close: -1 - exempt-issue-labels: "new plugin idea, todo" + exempt-issue-labels: "new plugin idea, todo, enhancement, bug, Low priority, documentation" operations-per-run: 100 repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/community-release-notifier.yml b/.github/workflows/community-release-notifier.yml index 9b418a1b27..5dc9daa458 100644 --- a/.github/workflows/community-release-notifier.yml +++ b/.github/workflows/community-release-notifier.yml @@ -1,38 +1,153 @@ name: community-release-notifier + on: release: types: [ released ] + workflow_dispatch: + inputs: + tag_name: + required: true + description: "Release tag_name" + type: string + url: + required: true + description: "release URL" + type: string + body: + required: true + description: "Release Body" + type: string + default: '' workflow_call: inputs: - tag_name: - required: true - description: "Release tag_name" - type: 'string' - url: - required: true - description: "release URL" - type: 'string' + tag_name: + required: true + description: "Release tag_name" + type: string + url: + required: true + description: "release URL" + type: string + body: + required: true + description: "Release Body" + type: string + default: '' secrets: DISCORD_WEBHOOK_RELEASE_NOTES: description: 'Discord Webhook for Notifying Releases to Discord' required: true + TELEGRAM_BOT_TOKEN: + description: 'Telegram Bot Token' + required: true + TELEGRAM_CHAT_ID: + description: 'Telegram Chat ID (group/channel/supergroup)' + required: true + TELEGRAM_MESSAGE_THREAD_ID: + description: 'Topic / message_thread_id for Telegram forum/topic' + required: true jobs: - discord-release: + notify: if: github.repository_owner == 'Acode-Foundation' runs-on: ubuntu-latest steps: - - name: Get Release Content - id: get-release-content - uses: 2428392/gh-truncate-string-action@b3ff790d21cf42af3ca7579146eedb93c8fb0757 # v1.4.1 - with: - maxLength: 2000 - stringToTruncate: | - 📢 Acode [${{ github.event.release.tag_name || inputs.tag_name }}](<${{ github.event.release.url || inputs.url }}>) was just Released 🎉! + - name: Prepare release variables + id: vars + env: + INPUT_TAG: ${{ github.event.release.tag_name || inputs.tag_name }} + INPUT_URL: ${{ github.event.release.html_url || inputs.url }} + INPUT_BODY: ${{ github.event.release.body || inputs.body }} + run: | + TAG="$INPUT_TAG" + URL="$INPUT_URL" + + # Generate a random delimiter (hex string, safe and collision-resistant) + DELIMITER=$(openssl rand -hex 16 || head -c 16 /dev/urandom | xxd -p -c 16) + # Escape problematic characters for MarkdownV2 (very conservative escaping) + # We escape: _ * [ ] ( ) ~ ` > # + - = | { } . ! \ + BODY_SAFE=$(printf '%s' "$INPUT_BODY" | \ + sed -E \ + -e 's/^[[:space:]]*##[[:space:]]*//' \ + -e 's/^[[:space:]]*\*[[:space:]]+/- /' \ + -e 's/\*\*([^*]*)\*\*/\*\1\*/g' \ + -e 's/\\!/!/g' \ + -e 's/@([A-Za-z0-9-]+)/@\1/g') + TAG_SAFE=$(printf '%s' "$TAG" | sed 's/[_*[\]()~`>#+=|{}.!\\-]/\\&/g') + + if [[ "$TAG" == *"-nightly"* ]]; then + SUFFIX=" \(Nightly Release\)" + SUFFIXPLAIN=" (Nightly Release)" + else + SUFFIX="" + SUFFIXPLAIN="" + fi + + # Announcement line — also escape for safety + ANNOUNCE_SAFE="📢 Acode [$TAG_SAFE]($URL) was just Released 🎉${SUFFIX}\\!" + + echo "announce=$ANNOUNCE_SAFE" >> $GITHUB_OUTPUT + { + echo "body_safe<<$DELIMITER" + printf '%s\n' "$BODY_SAFE" + echo "$DELIMITER" + } >> $GITHUB_OUTPUT + + # Plain (MD) Announcement for Discord + ANNOUNCE_PLAIN="📢 Acode [$TAG](<$URL>) was just Released 🎉${SUFFIXPLAIN}!" + echo "announce_plain=$ANNOUNCE_PLAIN" >> $GITHUB_OUTPUT + { + echo "body_plain<<$DELIMITER" + printf '%s\n' "$INPUT_BODY" + echo "$DELIMITER" + } >> $GITHUB_OUTPUT + + # ──────────────────────────────────────────────── + # Truncate for Discord + # ──────────────────────────────────────────────── + - name: Truncate message for Discord + id: truncate-discord + uses: 2428392/gh-truncate-string-action@b3ff790d21cf42af3ca7579146eedb93c8fb0757 # v1.4.1 + env: + # https://github.blog/changelog/2025-09-19-deprecation-of-node-20-on-github-actions-runners/ + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + with: + maxLength: 2000 + stringToTruncate: | + ${{ steps.vars.outputs.announce_plain }} + + ${{ steps.vars.outputs.body_plain }} + + # ──────────────────────────────────────────────── + # Discord notification + # ──────────────────────────────────────────────── + - name: Discord Webhook (Publishing) + uses: tsickert/discord-webhook@b217a69502f52803de774ded2b1ab7c282e99645 # v7.0.0 + env: + # https://github.blog/changelog/2025-09-19-deprecation-of-node-20-on-github-actions-runners/ + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + with: + webhook-url: ${{ secrets.DISCORD_WEBHOOK_RELEASE_NOTES }} + content: ${{ steps.truncate-discord.outputs.string }} + flags: 4 # 1 << 2 - SUPPRESS_EMBEDS! + + # ──────────────────────────────────────────────── + # Telegram notification — MarkdownV2 + no link preview + # ──────────────────────────────────────────────── + - name: Send to Telegram + #if: ${{ secrets.TELEGRAM_BOT_TOKEN != '' && secrets.TELEGRAM_CHAT_ID != '' && secrets.TELEGRAM_MESSAGE_THREAD_ID != '' }} + uses: Salmansha08/telegram-github-action@17c9ce6b4210d2659dca29d34028b02fa29d70ad # or newer tag if available + with: + to: ${{ secrets.TELEGRAM_CHAT_ID }} + token: ${{ secrets.TELEGRAM_BOT_TOKEN }} + message: | + ${{ steps.vars.outputs.announce }} - - name: Discord Webhook Action (Publishing) - uses: tsickert/discord-webhook@c840d45a03a323fbc3f7507ac7769dbd91bfb164 # v5.3.0 - with: - webhook-url: ${{ secrets.DISCORD_WEBHOOK_RELEASE_NOTES }} - content: ${{ steps.get-release-content.outputs.string }} + ${{ steps.vars.outputs.body_safe }} + # disabled for time being see https://github.com/Acode-Foundation/Acode/pull/2832#discussion_r3887130617 + #format: markdown + disable_web_page_preview: true + # Only needed for topic-enabled supergroups/channels + message_thread_id: ${{ secrets.TELEGRAM_MESSAGE_THREAD_ID }} + continue-on-error: true diff --git a/.github/workflows/congrats.yml b/.github/workflows/congrats.yml new file mode 100644 index 0000000000..34fb958a8f --- /dev/null +++ b/.github/workflows/congrats.yml @@ -0,0 +1,77 @@ +name: Congrats + +on: + push: + branches: + - main + +permissions: + contents: read + +jobs: + check-author: + runs-on: ubuntu-latest + if: github.repository_owner == 'acode-foundation' && github.event.head_commit.message != '' + outputs: + should_congratulate: ${{ steps.check.outputs.should_congratulate }} + steps: + - name: Check PR author + id: check + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + github-token: ${{ secrets.CONGRATSBOT_GITHUB_TOKEN }} + script: | + const { owner, repo } = context.repo; + const sha = context.sha; + + // Find the merged PR associated with this push commit + const { data: prs } = await github.rest.repos.listPullRequestsAssociatedWithCommit({ + owner, + repo, + commit_sha: sha, + }); + + const mergedPr = prs.find(pr => pr.merged_at !== null); + + if (!mergedPr) { + core.info('No merged PR found for this push.'); + core.setOutput('should_congratulate', 'false'); + return; + } + + const author = mergedPr.user; + + // Skip bots + if (author.type === 'Bot') { + core.info(`Skipping bot user: ${author.login}`); + core.setOutput('should_congratulate', 'false'); + return; + } + + // Check organization membership in team slug 'acode' + try { + await github.rest.teams.getMembershipForUserInOrg({ + org: owner, + team_slug: 'acode', + username: author.login, + }); + + core.info(`User ${author.login} is a member of team 'acode'. Skipping congrats.`); + core.setOutput('should_congratulate', 'false'); + } catch (error) { + if (error.status === 404) { + core.info(`User ${author.login} is not a member of team 'acode'. Sending congrats.`); + core.setOutput('should_congratulate', 'true'); + } else { + core.setFailed(`Error checking team membership: ${error.message}`); + } + } + + congrats: + needs: check-author + if: needs.check-author.outputs.should_congratulate == 'true' + uses: UnschooledGamer/automation/.github/workflows/congratsbot.yml@patch-1 # patch-1 for now + with: + EMOJIS: 🎉,🎊,🧑‍🚀,🥳,🙌,🚀,🦀,🔥,🚢 + secrets: + DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK_CONGRATS }} diff --git a/.github/workflows/nightly-build.yml b/.github/workflows/nightly-build.yml index cc7b3ea765..beb371e43a 100644 --- a/.github/workflows/nightly-build.yml +++ b/.github/workflows/nightly-build.yml @@ -1,233 +1,211 @@ - name: Nightly Build - - on: - schedule: - # Fire every day at 7:00am UTC (Roughly before EU workday and after US workday) - - cron: "0 7 * * *" - push: - tags: - - nightly - workflow_call: - inputs: - is_PR: - default: false - type: boolean - description: If a Pull Request has triggered it. - PR_NUMBER: - required: true - type: number - description: The Pull Request that triggered this workflow - skip_tagging_and_releases: - required: false - default: true - type: boolean - description: Skips Tagging & releases, since workflow_call isn't available for github.event_name, default is true - outputs: - job_result: - description: "Build job result" - value: ${{ jobs.build.result }} - - workflow_dispatch: - - concurrency: - # Allow only one workflow per any non-`main` branch. - group: ${{ github.workflow }}-${{ github.ref_name }}-${{ github.ref_name == 'main' && github.sha || 'anysha' }}-${{ inputs.is_PR && 'is_PR' || 'not_PR'}} - cancel-in-progress: true - - permissions: - contents: read - - env: - STORE_FILE_PATH: /tmp/app-debug.keystore - BUILD_JSON_PATH: build.json - VERSION_LABEL: ${{ (inputs.is_PR && 'pr') || 'nightly' }} - DISCORD_RELEASE_NOTIFIER_ENABLED: "true" - jobs: - build: - timeout-minutes: 60 - runs-on: ubuntu-latest - if: github.repository_owner == 'Acode-Foundation' - - permissions: -# contents write is needed to create Nightly Releases. - contents: write - issues: write - pull-requests: write - - outputs: - release_output_url: ${{ steps.release.outputs.url }} - updated_version: ${{ steps.update-version.outputs.UPDATED_VERSION}} - steps: - - name: Fast Fail if secrets are missing - if: ${{ env.KEYSTORE_CONTENT == '' || env.BUILD_JSON_CONTENT == '' }} - env: - KEYSTORE_CONTENT: ${{ secrets.KEYSTORE_CONTENT }} - BUILD_JSON_CONTENT: ${{ secrets.BUILD_JSON_CONTENT }} - run: | - echo "::error title=Missing Secrets::KEYSTORE_CONTENT or BUILD_JSON_CONTENT secrets are missing! Aborting workflow." - exit 1 - - - name: Logging & summaries - run: | - echo "::group::Logging" - echo "🎯 github trigger event name: ${{ github.event_name }}" - echo "is_PR: ${{ inputs.is_PR }} " - echo "PR_NUMBER: ${{ inputs.PR_NUMBER }}" - echo "env: STORE_FILE_PATH: ${{ env.STORE_FILE_PATH }}" - echo "env: BUILD_JSON_PATH: ${{ env.BUILD_JSON_PATH }}" - echo "env: VERSION_LABEL: ${{ env. VERSION_LABEL }}" - echo "github sha: ${{ github.sha }}" - echo "should not skip tags, releases: ${{ ! inputs.skip_tagging_and_releases }} " - echo "::endgroup::" - - echo "## 🚀 Build Type: ${{ env.VERSION_LABEL }}" >> $GITHUB_STEP_SUMMARY - echo "is_PR: ${{ inputs.is_PR || 'NOT a PR' }}" >> $GITHUB_STEP_SUMMARY - echo "PR_NUMBER: ${{ inputs.PR_NUMBER || 'not a PR' }}" >> $GITHUB_STEP_SUMMARY - echo "should not skip tags, releases: ${{ ! inputs.skip_tagging_and_releases }}" >> $GITHUB_STEP_SUMMARY - - - name: Checkout Repository - uses: actions/checkout@v4 - with: - fetch-depth: 0 # Required for tags - - - name: Set up Java 21 - uses: actions/setup-java@v4 - with: - distribution: 'temurin' - java-version: '21' - cache: ${{ (github.ref == 'refs/heads/main' && 'gradle') || '' }} - - - name: Set up Node.js - uses: actions/setup-node@v4 - with: - node-version: 'lts/*' # or '18.x' for latest stable - - - name: Add keystore and build.json from secrets - run: | - echo "${{ secrets.KEYSTORE_CONTENT }}" | base64 -d > $STORE_FILE_PATH - echo "${{ secrets.BUILD_JSON_CONTENT }}" | base64 -d > $BUILD_JSON_PATH - echo "Keystore and build.json added successfully." - - - name: Export Commit Hash & prev tag - run: | - echo "GIT_COMMIT=$(git rev-parse HEAD)" >> $GITHUB_ENV - echo "PREV_TAG=$(git describe --tags --abbrev=0 || git rev-list --max-parents=0 HEAD)" >> $GITHUB_ENV - - - name: Extract versionCode and version from config.xml - id: extract_version - run: | - if [ ! -f config.xml ]; then - echo "config.xml not found!" - exit 1 - fi - VERSION_CODE=$(grep 'versionCode=' config.xml | sed -E 's/.*versionCode="([0-9]+)".*/\1/') - VERSION=$(grep -oP 'version="\K[0-9.]+' config.xml) - echo "VERSION_CODE=$VERSION_CODE" >> $GITHUB_OUTPUT - echo "VERSION=$VERSION" >> $GITHUB_OUTPUT - echo "Extracted Version Code: $VERSION_CODE" - echo "Extracted Version: $VERSION" - - - name: Append Commit Hash to Version and Update config.xml - id: update-version - run: | - SHORT_COMMIT_HASH=$(echo "${{ env.GIT_COMMIT }}" | cut -c 1-7) - if ${{ inputs.is_PR || false }}; then - PR_NUMBER=${{ inputs.PR_NUMBER }} - else - PR_NUMBER= - fi - UPDATED_VERSION="${{ steps.extract_version.outputs.VERSION }}-${{ env.VERSION_LABEL }}.${PR_NUMBER:-$SHORT_COMMIT_HASH}" - echo "Updated Version: $UPDATED_VERSION" - - # Update config.xml with the new version - sed -i "s/version=\"${{ steps.extract_version.outputs.VERSION }}\"/version=\"$UPDATED_VERSION\"/g" config.xml - echo "Updated version in config.xml" - # Output the updated version - echo "UPDATED_VERSION=$UPDATED_VERSION" >> $GITHUB_ENV - echo "UPDATED_VERSION=$UPDATED_VERSION" >> $GITHUB_OUTPUT - - - name: Install Node.js Packages - run: npm install - - - name: Run npm setup - run: npm run setup - - - name: Run npm build paid dev apk - run: | - npm run build paid dev apk - echo "VERSION: $UPDATED_VERSION" >> $GITHUB_STEP_SUMMARY - - - name: Upload APK Artifact - uses: actions/upload-artifact@v4 - with: - name: app-debug-${{ env.GIT_COMMIT }} - path: platforms/android/app/build/outputs/apk/debug/app-debug.apk - - - name: remove keystore and build.json - run: | - rm $STORE_FILE_PATH $BUILD_JSON_PATH - echo "Keystore and build.json removed successfully." - - - name: Check Nightly Tag and Force Update - #if: github.event_name == 'push' && contains(github.event.ref, 'tags/nightly') == false - if: ${{ ! inputs.skip_tagging_and_releases }} - run: | - # Check if the nightly tag exists and get the commit it points to - if git show-ref --quiet refs/tags/nightly; then - TAG_COMMIT=$(git rev-parse nightly) - else - TAG_COMMIT="" - fi - - # If the current commit is the same as the tag, skip updating the tag - if [ "$TAG_COMMIT" != "${{ env.GIT_COMMIT }}" ]; then - echo "releaseRequired=true" >> $GITHUB_ENV - # export tag commit before updating for change logs comparing. - echo "TAG_COMMIT=$TAG_COMMIT" >> $GITHUB_ENV - - git config --global user.name 'GitHub Actions' - git config --global user.email 'github-actions@github.com' - git tag -f nightly - git push origin nightly --force - else - echo "Nightly tag already points to this commit. Skipping update." - fi - - - name: Release Nightly Version -# Only run this step, if not called from another workflow. And a previous step is successful with releasedRequired=true - id: release - if: ${{ ! inputs.skip_tagging_and_releases && success() && env.releaseRequired == 'true' }} - uses: softprops/action-gh-release@v2 - with: - prerelease: true - name: ${{ env.UPDATED_VERSION }} - tag_name: ${{ env.UPDATED_VERSION }} - files: | - platforms/android/app/build/outputs/apk/debug/app-debug.apk - body: | - Automated Nightly (pre-release) Releases for Today - \n\n[Compare Changes](https://github.com/${{ github.repository }}/compare/${{ env.TAG_COMMIT }}...${{ github.sha }}) - - - name: Update Last Comment by bot (If ran in PR) - if: inputs.is_PR - uses: marocchino/sticky-pull-request-comment@v2 - with: - hide_and_recreate: true - hide_classify: "OUTDATED" - header: on-demand-build-status - message: | - Preview Release for this, has been built. - - [Click here to view that github actions build](https://github.com/${{ github.repository}}/actions/runs/${{ github.run_id }}) - - - community-release-notifier: - needs: build -# Run only if push tags, or triggered by a schedule - if: ${{ github.repository_owner == 'Acode-Foundation' && (contains(fromJSON('["push", "schedule"]'), github.event_name) || ! inputs.skip_tagging_and_releases) && needs.build.outputs.release_output_url }} - uses: Acode-Foundation/acode/.github/workflows/community-release-notifier.yml@main - with: - tag_name: ${{ needs.build.outputs.updated_version }} - url: ${{ needs.build.outputs.release_output_url }} - secrets: - DISCORD_WEBHOOK_RELEASE_NOTES: ${{ secrets.DISCORD_WEBHOOK_RELEASE_NOTES }} +# Implement to use environment secrets someday, At the moment GH Actions doesn't support those in reusable workflows (ref: https://github.com/actions/runner/issues/1490) +# at least that's what I found. +# This workflow executes PR Code when triggered from PR via workflow_call, +# MUST approve the PR code BEFORE triggering this workflow. + +name: Nightly Build + +on: + workflow_call: + inputs: + is_PR: + default: false + type: boolean + description: If a Pull Request has triggered it. + is_trusted_pr: + default: false + type: boolean + description: If a Pull Request is from the same repository (not a fork). + PR_NUMBER: + required: false + type: number + description: Pull Request number (for PR builds) + secrets: + KEYSTORE_CONTENT: + required: true + BUILD_JSON_CONTENT: + required: true + outputs: + job_result: + description: Build job result + value: ${{ jobs.build.result }} + updated_version: + description: Computed build version + value: ${{ jobs.build.outputs.updated_version }} + git_commit: + description: Commit SHA used for artifact naming + value: ${{ jobs.build.outputs.git_commit }} + normal_artifact_name: + description: Artifact name for normal APK + value: ${{ jobs.build.outputs.normal_artifact_name }} + fdroid_artifact_name: + description: Artifact name for fdroid APK + value: ${{ jobs.build.outputs.fdroid_artifact_name }} + + workflow_dispatch: + +permissions: + contents: read + +concurrency: + # Allow only one workflow per branch. + group: ${{ github.workflow }}-${{ github.ref_name }}-${{ inputs.is_PR && 'is_PR' || 'not_PR' }} + cancel-in-progress: true + +env: + STORE_FILE_PATH: /tmp/app-debug.keystore + BUILD_JSON_PATH: build.json + VERSION_LABEL: ${{ inputs.is_PR && 'pr' || 'nightly' }} + +jobs: + build: + runs-on: ubuntu-latest + timeout-minutes: 60 + if: github.repository_owner == 'Acode-Foundation' + permissions: + contents: read + pull-requests: read + + outputs: + updated_version: ${{ steps.version.outputs.updated_version }} + git_commit: ${{ steps.meta.outputs.git_commit }} + normal_artifact_name: ${{ steps.meta.outputs.normal_artifact_name }} + fdroid_artifact_name: ${{ steps.meta.outputs.fdroid_artifact_name }} + + steps: + - name: Validate required secrets (Fast Fail If missing on nightly builds) + if: ${{ !inputs.is_PR || inputs.is_trusted_pr }} + env: + KEYSTORE_CONTENT: ${{ secrets.KEYSTORE_CONTENT }} + BUILD_JSON_CONTENT: ${{ secrets.BUILD_JSON_CONTENT }} + run: | + [ -n "$KEYSTORE_CONTENT" ] && [ -n "$BUILD_JSON_CONTENT" ] || { echo "::error title=Missing secrets::KEYSTORE_CONTENT or BUILD_JSON_CONTENT is missing"; exit 1; } + + - name: Logging & summaries + run: | + echo "::group::Logging" + echo "🎯 github trigger event name: ${{ github.event_name }}" + echo "is_PR: ${{ inputs.is_PR }} " + echo "PR_NUMBER: ${{ inputs.PR_NUMBER }}" + echo "env: STORE_FILE_PATH: ${{ env.STORE_FILE_PATH }}" + echo "env: BUILD_JSON_PATH: ${{ env.BUILD_JSON_PATH }}" + echo "env: VERSION_LABEL: ${{ env.VERSION_LABEL }}" + echo "github sha: ${{ github.sha }}" + echo "should skip signing with our keys: ${{ inputs.is_PR && !inputs.is_trusted_pr && 'true' || 'false' }}" + echo "::endgroup::" + echo "## 🚀 Build Type: ${{ env.VERSION_LABEL }}" >> $GITHUB_STEP_SUMMARY + echo "is_PR: ${{ inputs.is_PR || 'NOT a PR' }}" >> $GITHUB_STEP_SUMMARY + echo "PR_NUMBER: ${{ inputs.PR_NUMBER || 'not a PR' }}" >> $GITHUB_STEP_SUMMARY + + - name: Checkout repository + uses: actions/checkout@v7 + with: + fetch-depth: 0 # Required for tags + persist-credentials: false + submodules: recursive + ref: ${{ (inputs.is_PR && inputs.PR_NUMBER) && github.event.pull_request.head.sha || '' }} + allow-unsafe-pr-checkout: ${{ !!(inputs.is_PR && inputs.PR_NUMBER && github.event.pull_request.head.sha) }} + + - name: Setup Java + uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: "21" + cache: ${{ (!(inputs.is_PR && inputs.PR_NUMBER) && github.ref == 'refs/heads/main' && 'gradle') || '' }} + + - name: Setup Node + uses: actions/setup-node@v7 + with: + node-version: "lts/*" # or '18.x' for latest stable + cache: ${{ (!(inputs.is_PR && inputs.PR_NUMBER) && github.ref == 'refs/heads/main' && 'npm') || '' }} + + - name: Compute metadata + id: meta + run: | + GIT_COMMIT="$(git rev-parse HEAD)" + echo "git_commit=$GIT_COMMIT" >> "$GITHUB_OUTPUT" + echo "normal_artifact_name=app-debug-$GIT_COMMIT" >> "$GITHUB_OUTPUT" + echo "fdroid_artifact_name=app-debug-fdroid-$GIT_COMMIT" >> "$GITHUB_OUTPUT" + + - name: Inject signing files + if: ${{ !inputs.is_PR || inputs.is_trusted_pr }} + run: | + echo "${{ secrets.KEYSTORE_CONTENT }}" | base64 -d > "${{ env.STORE_FILE_PATH }}" + echo "${{ secrets.BUILD_JSON_CONTENT }}" | base64 -d > "${{ env.BUILD_JSON_PATH }}" + + - name: Extract base version + id: base + run: | + VERSION=$(grep -oP 'version="\K[0-9.]+' config.xml) + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + + - name: Compose and set build version in config.xml + id: version + run: | + SHORT="$(echo "${{ steps.meta.outputs.git_commit }}" | cut -c1-7)" + if ${{ inputs.is_PR || false }}; then + SUFFIX="${{ inputs.PR_NUMBER }}" + else + SUFFIX="$SHORT" + fi + UPDATED="${{ steps.base.outputs.version }}-${{ env.VERSION_LABEL }}.$SUFFIX" + sed -i "s/version=\"${{ steps.base.outputs.version }}\"/version=\"$UPDATED\"/g" config.xml + echo "updated_version=$UPDATED" >> "$GITHUB_OUTPUT" + echo "NORMAL_APK_PATH=/tmp/acode-debug-normal-$UPDATED.apk" >> "$GITHUB_ENV" + echo "FDROID_APK_PATH=/tmp/acode-debug-fdroid-$UPDATED.apk" >> "$GITHUB_ENV" + + - name: Install deps + run: | + npm install + npm install -g cordova + npm run setup + + - name: Build normal APK + run: | + node utils/storage_manager.mjs y + npm run build paid dev apk + mv platforms/android/app/build/outputs/apk/debug/app-debug.apk ${{ env.NORMAL_APK_PATH }} + + - name: Upload normal artifact + uses: actions/upload-artifact@v7 + with: + name: ${{ steps.meta.outputs.normal_artifact_name }} + path: ${{ env.NORMAL_APK_PATH }} + + - name: Build fdroid APK + if: ${{ !inputs.is_PR }} + run: | + node utils/storage_manager.mjs y + npm run build paid dev apk fdroid + mv platforms/android/app/build/outputs/apk/debug/app-debug.apk ${{ env.FDROID_APK_PATH }} + + - name: Upload fdroid artifact + if: ${{ !inputs.is_PR }} + uses: actions/upload-artifact@v7 + with: + name: ${{ steps.meta.outputs.fdroid_artifact_name }} + path: ${{ env.FDROID_APK_PATH }} + + - name: Cleanup signing files + if: ${{ !inputs.is_PR || inputs.is_trusted_pr }} + run: rm -f ${{ env.STORE_FILE_PATH }} ${{ env.BUILD_JSON_PATH }} + + - name: Post Build - SHA256 signature computation (output) + id: sha256 + run: | + echo "normal_apk_sha256=$(sha256sum ${{ env.NORMAL_APK_PATH }} | awk '{print $1}')" >> "$GITHUB_OUTPUT" + if [ -f "${{ env.FDROID_APK_PATH }}" ]; then + echo "fdroid_apk_sha256=$(sha256sum ${{ env.FDROID_APK_PATH }} | awk '{print $1}')" >> "$GITHUB_OUTPUT" + fi + + - name: Post build summary (Table) + run: | + echo "## 🏗️ Build Summary" >> $GITHUB_STEP_SUMMARY + echo "| Key | Value |" >> $GITHUB_STEP_SUMMARY + echo "| --- | ----- |" >> $GITHUB_STEP_SUMMARY + echo "| Build Version | ${{ steps.version.outputs.updated_version }} |" >> $GITHUB_STEP_SUMMARY + echo "| Git Commit | ${{ steps.meta.outputs.git_commit }} |" >> $GITHUB_STEP_SUMMARY + echo "| Normal APK Artifact Name | ${{ steps.meta.outputs.normal_artifact_name }} |" >> $GITHUB_STEP_SUMMARY + echo "| F-Droid APK Artifact Name | ${{ steps.meta.outputs.fdroid_artifact_name || 'N/A' }} |" >> $GITHUB_STEP_SUMMARY + echo "| Normal APK Artifact SHA256 | ${{ steps.sha256.outputs.normal_apk_sha256 }} |" >> $GITHUB_STEP_SUMMARY + echo "| F-Droid APK Artifact SHA256 | ${{ steps.sha256.outputs.fdroid_apk_sha256 || 'N/A' }} |" >> $GITHUB_STEP_SUMMARY diff --git a/.github/workflows/nightly-release.yml b/.github/workflows/nightly-release.yml new file mode 100644 index 0000000000..33191fbad1 --- /dev/null +++ b/.github/workflows/nightly-release.yml @@ -0,0 +1,228 @@ +name: Nightly Release + +on: + schedule: + # Fire every day at 7:00am UTC (Roughly before EU workday and after US workday) + - cron: "0 7 * * *" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref_name }} + cancel-in-progress: true + +jobs: + build: + if: ${{ github.repository_owner == 'Acode-Foundation' }} + uses: Acode-Foundation/acode/.github/workflows/nightly-build.yml@main + permissions: + contents: read + pull-requests: read + secrets: + KEYSTORE_CONTENT: ${{ secrets.KEYSTORE_CONTENT }} + BUILD_JSON_CONTENT: ${{ secrets.BUILD_JSON_CONTENT }} + with: + is_PR: false + is_trusted_pr: false + + release: + needs: build + runs-on: ubuntu-latest + if: ${{ github.repository_owner == 'Acode-Foundation' && needs.build.result == 'success' }} + permissions: + contents: write + id-token: write + + outputs: + should_publish: ${{ steps.publish_gate.outputs.should_publish }} + release_output_url: ${{ steps.gh_release.outputs.url }} + release_notes: ${{ env.RELEASE_NOTES }} + previous_tag_commit: ${{ steps.prev.outputs.tag_commit }} + nightly_tag_name: ${{ needs.build.outputs.updated_version }} + subjects_file: ${{ steps.subjects_file.outputs.handle }} + + steps: + - name: Checkout repository + uses: actions/checkout@v7 + with: + fetch-depth: 0 # Required for tags + persist-credentials: true + + - name: Install cosign + uses: sigstore/cosign-installer@v4.1.3 + + - name: Set Publish Metadata + shell: bash + run: | + set -euo pipefail + echo "ARTIFACTS_DIR=${{ env.ARTIFACTS_DIR}}" >> $GITHUB_ENV + echo "NORMAL_ARTIFACT_NAME=app-debug-${{ github.sha }}" >> $GITHUB_ENV + echo "FDROID_ARTIFACT_NAME=app-debug-fdroid-${{ github.sha }}" >> $GITHUB_ENV + echo "SUBJECTS_FILE=${{ env.SUBJECTS_FILE }}" >> $GITHUB_ENV + env: + ARTIFACTS_DIR: ${{ runner.temp }}/artifacts + SUBJECTS_FILE: ${{ runner.temp }}/slsa-subjects.txt + + + - name: Download normal APK artifact + uses: actions/download-artifact@v8 + with: + name: ${{ needs.build.outputs.normal_artifact_name }} + path: ${{ env.ARTIFACTS_DIR }}/normal + + - name: Download fdroid APK artifact + uses: actions/download-artifact@v8 + with: + name: ${{ needs.build.outputs.fdroid_artifact_name }} + path: ${{ env.ARTIFACTS_DIR }}/fdroid + + - name: Resolve previous nightly tag commit + id: prev + shell: bash + run: | + set -euo pipefail + VERSION_TAG="${{ needs.build.outputs.updated_version }}" + FALLBACK_TAG="nightly" + git fetch --tags --force + + if git show-ref --quiet "refs/tags/${VERSION_TAG}"; then + echo "tag_exists=true" >> "$GITHUB_OUTPUT" + echo "tag_commit=$(git rev-parse "${VERSION_TAG}")" >> "$GITHUB_OUTPUT" + elif git show-ref --quiet "refs/tags/${FALLBACK_TAG}"; then + echo "tag_exists=true" >> "$GITHUB_OUTPUT" + echo "tag_commit=$(git rev-parse "${FALLBACK_TAG}")" >> "$GITHUB_OUTPUT" + else + echo "tag_exists=false" >> "$GITHUB_OUTPUT" + echo "tag_commit=" >> "$GITHUB_OUTPUT" + fi + + - name: Decide whether to publish + id: publish_gate + shell: bash + run: | + set -euo pipefail + if [[ "${{ steps.prev.outputs.tag_exists }}" != "true" || "${{ steps.prev.outputs.tag_commit }}" != "${GITHUB_SHA}" ]]; then + echo "should_publish=true" >> "$GITHUB_OUTPUT" + else + echo "should_publish=false" >> "$GITHUB_OUTPUT" + fi + + - name: Build SLSA subjects file + if: steps.publish_gate.outputs.should_publish == 'true' + shell: bash + run: | + set -euo pipefail + find ${{ env.ARTIFACTS_DIR }} -type f -name '*.apk' -print0 | sort -z | while IFS= read -r -d '' f; do + sha256sum "$f" + done | base64 -w0 > "${SUBJECTS_FILE}" + + test -s "${SUBJECTS_FILE}" || { echo "No subjects found"; exit 1; } + env: + ARTIFACTS_DIR: ${{ env.ARTIFACTS_DIR }} + SUBJECTS_FILE: ${{ env.SUBJECTS_FILE }} + + + - name: Generate per-APK sha256 files + shell: bash + run: | + set -euo pipefail + find ${{ env.ARTIFACTS_DIR }} -type f -name '*.apk' -print0 | while IFS= read -r -d '' f; do + sha256sum "$f" > "${f}.sha256" + done + + - name: Create subjects file handle + id: subjects_file + if: steps.publish_gate.outputs.should_publish == 'true' + uses: slsa-framework/slsa-github-generator/actions/generator/generic/create-base64-subjects-from-file@v2.1.0 + with: + path: ${{ env.SUBJECTS_FILE }} + + - name: Move nightly tag + if: steps.publish_gate.outputs.should_publish == 'true' + run: | + git config --global user.name 'GitHub Actions' + git config --global user.email 'github-actions@github.com' + git tag -f nightly "${GITHUB_SHA}" + git push origin refs/tags/nightly --force + + - name: Generate release notes + if: steps.publish_gate.outputs.should_publish == 'true' + id: notes + continue-on-error: true + run: | + RELEASE_NOTES="$(node utils/scripts/generate-release-notes.js \ + ${{ github.repository_owner }} Acode ${{ github.sha }} \ + --format md --from-tag ${{ steps.prev.outputs.tag_commit }} --important-only --quiet --changelog-only || true)" + { + echo "RELEASE_NOTES<> "$GITHUB_ENV" + env: + GITHUB_TOKEN: ${{ secrets.NIGHTLY_RELEASE_NOTES_GH_TOKEN }} + + - name: Create nightly prerelease + if: steps.publish_gate.outputs.should_publish == 'true' + id: gh_release + uses: softprops/action-gh-release@v3 + env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + with: + prerelease: true + tag_name: ${{ needs.build.outputs.updated_version }} + name: ${{ needs.build.outputs.updated_version }} + files: | + ${{ env.ARTIFACTS_DIR }}/normal/*.apk + ${{ env.ARTIFACTS_DIR }}/normal/*.apk.sha256 + ${{ env.ARTIFACTS_DIR }}/fdroid/*.apk + ${{ env.ARTIFACTS_DIR }}/fdroid/*.apk.sha256 + body: | + Automated Nightly pre-release + + [Compare Changes](https://github.com/${{ github.repository }}/compare/${{ steps.prev.outputs.tag_commit }}...${{ github.sha }}) + + ${{ env.RELEASE_NOTES }} + + - name: Post Job summary + if: always() + run: | + echo "| Variable | Value |" >> "$GITHUB_STEP_SUMMARY" + echo "| --- | --- |" >> "$GITHUB_STEP_SUMMARY" + echo "| should_publish | ${{ steps.publish_gate.outputs.should_publish == 'true' && 'true' || 'false' }} |" >> "$GITHUB_STEP_SUMMARY" + echo "| (pre-release versioned/nightly tag) tag_exists | ${{ steps.prev.outputs.tag_exists }} |" >> "$GITHUB_STEP_SUMMARY" + echo "| (pre-release versioned/nightly tag) tag_commit | ${{ steps.prev.outputs.tag_commit }} |" >> "$GITHUB_STEP_SUMMARY" + echo "| release_output_url | ${{ steps.gh_release.outputs.url || 'N/A' }} |" >> "$GITHUB_STEP_SUMMARY" + + provenance: + name: Generate SLSA provenance + needs: [release] + if: needs.release.outputs.should_publish == 'true' + permissions: + actions: read + id-token: write + contents: write + uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v2.1.0 + with: + base64-subjects-as-file: "${{ needs.release.outputs.subjects_file }}" + upload-assets: true + upload-tag-name: "${{ needs.release.outputs.nightly_tag_name }}" + draft-release: false + + community-release-notifier: + name: Notify community of nightly release + needs: [release] + if: ${{ needs.release.outputs.should_publish == 'true' && needs.release.outputs.release_output_url }} + permissions: + contents: read + uses: Acode-Foundation/acode/.github/workflows/community-release-notifier.yml@main + with: + url: ${{ needs.release.outputs.release_output_url }} + tag_name: ${{ needs.release.outputs.nightly_tag_name }} + body: ${{ needs.release.outputs.release_notes }} + secrets: + DISCORD_WEBHOOK_RELEASE_NOTES: ${{ secrets.DISCORD_WEBHOOK_RELEASE_NOTES }} + TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} + TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }} + TELEGRAM_MESSAGE_THREAD_ID: ${{ secrets.TELEGRAM_MESSAGE_THREAD_ID }} diff --git a/.github/workflows/on-demand-preview-releases-PR.yml b/.github/workflows/on-demand-preview-releases-PR.yml index 103d35aed2..8254116d6a 100644 --- a/.github/workflows/on-demand-preview-releases-PR.yml +++ b/.github/workflows/on-demand-preview-releases-PR.yml @@ -1,18 +1,18 @@ name: On Demand Preview Releases for PR # avoids paths like .md, and anything in .github folder on: - pull_request: + # This workflow executes PR Code by checkout later + # MUST approve the PR Code BEFORE using this workflow on PRs. + # Uses this trigger to keep up-to-date execution of the workflow (triggers from Default Branch) + pull_request_target: paths-ignore: - '!*.md' # - '.github/**' types: [labeled, synchronize] # defined at workflow-level as the workflow, Requires these permissions to function. -permissions: - contents: write - pull-requests: write - # All Pull Requests are issues, but not all issues are Pull Requests (like GitHub says 🙃) - issues: write +permissions: + contents: read concurrency: # Allow only one workflow per any non-`main` branch. @@ -22,22 +22,27 @@ concurrency: jobs: job_trigger: name: Trigger Preview Release (if conditions met) - if: | - github.event.pull_request.draft == false - && (github.repository_owner == 'Acode-Foundation' - && (!contains(github.event.pull_request.labels.*.name, 'DO NOT PREVIEW RELEASE') - && (contains(github.event.pull_request.labels.*.name, 'Bypass check - PREVIEW RELEASE') - || contains(github.event.pull_request.labels.*.name, 'CI: RUN ON-DEMAND PREVIEW RELEASES'))) + permissions: + contents: read + pull-requests: write + issues: write + if: >- + github.event.pull_request.draft == false && + github.repository_owner == 'Acode-Foundation' && + (!contains(github.event.pull_request.labels.*.name, 'DO NOT PREVIEW RELEASE') && + (github.event.action == 'labeled' && github.event.label.name == 'CI: RUN ON-DEMAND PREVIEW RELEASES' || + github.event.action == 'synchronize' && contains(github.event.pull_request.labels.*.name, 'Bypass check - PREVIEW RELEASE')) ) runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: clean: false fetch-depth: 0 + persist-credentials: false - name: Remove Manually added PR Label if: | @@ -50,7 +55,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Add comment to PR - uses: marocchino/sticky-pull-request-comment@v2 + uses: marocchino/sticky-pull-request-comment@v3 with: hide_and_recreate: true hide_classify: "OUTDATED" @@ -58,11 +63,11 @@ jobs: message: | ⚒️ Starting a workflow to build, Your On-Demand Preview Release/build for ${{ github.event.pull_request.html_url || github.event.pull_request.url }}. - status: **\`🟡 in_progress\`** + status: **`🟡 in_progress`** Kindly wait, this message may be updated with success or failure status. - For Owners: Please [Click here to view that github actions](https://github.com/${{ github.repository}}/actions/runs/${{ github.run_id }})/ + Please [Click here to view that github actions](https://github.com/${{ github.repository}}/actions/runs/${{ github.run_id }})/ env: PR: ${{ github.event.pull_request.number }} @@ -70,26 +75,43 @@ jobs: trigger_builder: needs: job_trigger - secrets: inherit + permissions: + contents: read + pull-requests: read + issues: read + secrets: + KEYSTORE_CONTENT: ${{ secrets.KEYSTORE_CONTENT }} + BUILD_JSON_CONTENT: ${{ secrets.BUILD_JSON_CONTENT }} uses: Acode-Foundation/acode/.github/workflows/nightly-build.yml@main with: is_PR: true PR_NUMBER: ${{ github.event.pull_request.number }} - skip_tagging_and_releases: true + is_trusted_pr: ${{ github.event.pull_request.head.repo.full_name == github.repository }} update_Last_Comment: needs: [job_trigger,trigger_builder] + permissions: + contents: read + pull-requests: write runs-on: ubuntu-latest - if: ${{ github.repository_owner == 'Acode-Foundation' && always() && contains(fromJSON('["failure","cancelled"]'), needs.trigger_builder.result) }} + if: ${{ github.repository_owner == 'Acode-Foundation' && always() && contains(fromJSON('["failure","cancelled", "success"]'), needs.trigger_builder.result) }} steps: -# - name: Checkout code -# uses: actions/checkout@v4 -# with: -# clean: false -# fetch-depth: 0 + + - name: Update Last Comment by bot (If Workflow Triggering succeeded) + if: ${{ needs.trigger_builder.result == 'success' && github.event.pull_request.number }} + uses: marocchino/sticky-pull-request-comment@v3 + with: + hide_and_recreate: true + hide_classify: "OUTDATED" + header: on-demand-build-status + message: | + Preview Release for this, has been built. + + [Click here to view that github actions build](https://github.com/${{ github.repository}}/actions/runs/${{ github.run_id }}) - name: Update Last Comment by bot (if Workflow Triggering failed) - uses: marocchino/sticky-pull-request-comment@v2 + if: ${{ needs.trigger_builder.result != 'success' && github.event.pull_request.number }} + uses: marocchino/sticky-pull-request-comment@v3 with: hide_and_recreate: true hide_classify: "OUTDATED" @@ -99,4 +121,4 @@ jobs: status: **${{ needs.trigger_builder.result || 'failure'}}** --- - For Owners: Please [Click here to view that github actions](https://github.com/${{ github.repository}}/actions/runs/${{ github.run_id }}) + Please [Click here to view that github actions](https://github.com/${{ github.repository}}/actions/runs/${{ github.run_id }}) diff --git a/.gitignore b/.gitignore index 92f020ea1d..99babd15df 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,26 @@ -/node_modules -/build.json -/www/build -/plugins -/platforms -/keystore.jks -/platforms/android/debug-signing.properties -/platforms/android/release-signing.properties -**/*/.DS_Store -.DS_Store -pnpm-lock.yaml -.zed -.idea -ace-builds -fdroid.bool +node_modules +/build.json +/www/build +/plugins +/platforms +/keystore.jks +/platforms/android/debug-signing.properties +/platforms/android/release-signing.properties +**/*/.DS_Store +.DS_Store +pnpm-lock.yaml +.zed +.idea +ace-builds +fdroid.bool +CLAUDE.md +graphify-out/ +.graphify_python +.gradle/ +local.properties +tsconfig.tsbuildinfo +.dev-cert.pem +.dev-key.pem +/www/cordova.js +/www/cordova_plugins.js +.pnpm-store/ \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000000..4d07829ae2 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "codemirror-lsp-client"] + path = codemirror-lsp-client + url = https://github.com/Acode-Foundation/codemirror-lsp-client diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/.prettierrc @@ -0,0 +1 @@ +{} diff --git a/.vscode/settings.json b/.vscode/settings.json index ad71d61d31..4a16b5167c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,13 +1,11 @@ { "editor.formatOnSave": true, - "autoimport.doubleQuotes": false, - "java.configuration.updateBuildConfiguration": "disabled", "prettier.requireConfig": true, - "javascript.format.enable": true, + "js/ts.format.enabled": true, "editor.defaultFormatter": "esbenp.prettier-vscode", "prettier.tabWidth": 2, "prettier.useTabs": false, - "javascript.format.semicolons": "insert", + "js/ts.format.semicolons": "insert", "[scss]": { "editor.defaultFormatter": "vscode.css-language-features" }, @@ -27,6 +25,13 @@ "attr_quotes": "single" } }, + "[javascript]": { + "editor.defaultFormatter": "biomejs.biome" + }, + "editor.codeActionsOnSave": { + "quickFix.biome": "explicit", + "source.organizeImports.biome": "explicit" + }, "cSpell.words": [ "abap", "Acode", @@ -126,6 +131,7 @@ "flac", "Flix", "floobits", + "FOXBIZ", "Foxdebug", "freemarker", "gamemaker", @@ -167,6 +173,7 @@ "intoview", "Invisibles", "irid", + "isfiles", "jbuilder", "JEXL", "jsbeautify", @@ -243,6 +250,7 @@ "onscrollleft", "onscrolltop", "onsearch", + "onwillconnect", "onwilldisconnect", "onwriteend", "opencl", @@ -364,13 +372,17 @@ "watchmanconfig", "webp", "wercker", + "willconnect", + "willdisconnect", "Wollok", "wpgm", "wpml", "wtest", "wxml", "wxss", + "xhrs", + "XMLHTTP", "xquery", "Zeek" ] -} \ No newline at end of file +} diff --git a/CHANGELOG.md b/CHANGELOG.md index eac0279bf7..0b037b296e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,468 @@ # Change Log +## v1.13.5 + +* fix(terminal): stop proot "can't sanitize binding" fd warnings by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2878 +* fix(editor): preserve indentation on soft-wrapped lines by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2880 +* feat(editor): add context menu for closing file tabs by @TonyGeez in https://github.com/Acode-Foundation/Acode/pull/2863 +* perf(editor): index language modes instead of sorting on every lookup by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2881 +* feat: improve console virtualisation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2882 +* fix(search): prevent discovery restarts and stream results efficiently by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2883 +* feat(editor): add configurable word wrap indentation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2886 +* fix: API calls throwing internal server errors by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2888 +* fix(editor): add monaco-style punctuation wrap opportunities by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2890 + +## v1.13.4 + +* fix: prevent Cordova exec startup race by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2851 +* fix(editor): improve selection contrast on active lines by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2852 +* fix(editor): treat missing write capability as editable by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2853 +* fix: race condition when moving to exact line/col by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2856 +* Add GitHub Actions workflow for congratulating Community PRs by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/2855 +* Shortcut For Opening Welcome Tab by @Game-Dev-Shubham in https://github.com/Acode-Foundation/Acode/pull/2773 +* chore: Add Lingala (ln) translation by @Degrace15 in https://github.com/Acode-Foundation/Acode/pull/2775 +* feat: added icons and api by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2732 +* feat: httpStream api by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2841 +* fix: app icon picker and banner hide on reload by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2867 +* fix: settings category for app icon and theme by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2872 +* fix(devcontainer): update docker base image from bullseye to bookworm by @maaz7409 in https://github.com/Acode-Foundation/Acode/pull/2870 + +## v1.13.3 + +* refactor(file-browser): Replace plain object directory cache with `Map` by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2831 +* fix(editor): stabilize selection menu sizing and transitions by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2833 +* fix(editor): keep fullscreen controls above bottom pane tabs by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2834 +* chore(community-release-notifier): Change sed parsing - TG release notes by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/2832 +* fix(editor): restore cursor state and prevent tab-switch flash by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2835 +* feat(lsp): improve actions, navigation, and position handling by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2837 +* fix(editor): highlight all visible search matches by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2838 +* Translation: Update hu-hu.json by @summoner001 in https://github.com/Acode-Foundation/Acode/pull/2828 +* chore(deps): bump actions/setup-java from 5 to 6 by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/2821 +* feat: improved pluginContext by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2806 +* fix(webview): retain instance when destroy fails by @azamkassim in https://github.com/Acode-Foundation/Acode/pull/2836 +* fix(sftp): recover from failed profile migration by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2840 + +## v1.13.2 + +* feat: stabilize SFTP and add secure SSH terminal integration by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2694 +* fix(lsp): correct workspace and document color capabilities and add tailwind lsp by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2736 +* refactor: Standardize DOM element dataset attributes across file browser component by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2543 +* fix(lsp): preserve websocket clients across tab switches by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2764 +* feat(plugins): expose static CodeMirror highlighter by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2769 +* refactor(loader): Extract `tailSpin` SVG component and dynamic gradient logic by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2776 +* fix(quick-tools): prevent scrollbars during editor gestures by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2777 +* fix: fall back to internal storage when external storage is unavailable by @ulite-Amr in https://github.com/Acode-Foundation/Acode/pull/2781 +* fix(theme): prevent freeze when switching to system theme by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2790 +* fix(sftp): cancel stalled connections and prevent delayed errors by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2791 +* fix: admob issues by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2800 +* fix(android): avoid splash surface crash on realme Android 13 by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2805 +* fix(session): restore picker documents and skip intent files tab by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2809 +* feat(console): isolate execution and improve mobile REPL UX by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2808 +* feat(console): follow active Acode theme by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2814 +* chore: improve Indonesian (id) language translations by @MatrixTM26 in https://github.com/Acode-Foundation/Acode/pull/2798 +* fix: preserve MIME type for plugin icons on plugin details page by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2818 +* fix(console): run JavaScript files in isolated worker by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2819 +* feat: plugin review by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2826 +* Improve selection menu UX and plugin action overflow by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2813 +* fix(search): include restored files in global search by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2830 + +## v1.12.9 + +* fix(admob): remove the policy-prohibited interstitial shown while exiting the app + +## v1.12.8 + +* fix(terminal): close tab on process end and speed up long-press select by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2587 +* fix(editor): prevent false language mode recommendations by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2621 +* fix(lsp): send workspace folders during initialization by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2623 +* fix(admob): harden consent, banners, and variant builds by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2553 +* feat(lsp): add multi-server support to CodeMirror LSP client by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2627 + +## v1.12.7 + +* fix: scroll shift when tab switching by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2329 +* Fixes several small querks and inconsistencies to improve UI/UX by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2331 +* feat: add setting to toggle emmet by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2332 +* feat: add a ui to manage running Terminal (Executor) processes by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2333 +* fix(settings): preserve scroll state and avoid full rerenders by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2348 +* fix: removed annoying terminal dialog by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2349 +* Better regex by @Palloxin in https://github.com/Acode-Foundation/Acode/pull/2325 +* fix(lsp): hover tooltip code highlighting by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2353 +* fix(lsp): scope cache fallback by runtime provider by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2354 +* feat: dont invoke acode service when uninstalling terminal by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2350 +* fix: run new files even if marked saved by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2360 +* perf(settings): lazy load sub-settings pages to optimize load time by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2358 +* fix: ignore files to be treated as plugin in src/plugins by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2362 +* feat: add setting to toggle `language package completion` by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2361 +* feat(performance): removed double memory usage when reading/writing text files by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2359 +* feat: add language-mode plugin recommendation system by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2368 +* feat(keybind): add code folds keybinds by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/2369 +* fix(editor): apply plugin language modes after restore (for plugin modes) by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2375 +* fix: Use inline themed SVG for loader spinner by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2379 +* fix: wait for plugin load before recommendation trigger by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2383 +* fix: don't check for app updates from github when app is from playstore by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2385 +* feat: improved ux by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2382 +* fix: Fixes bug in settings UI by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2388 +* feat: lazy load things which are low-risk from main by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2386 +* fix(quicktools): preserve editor focus during rapid taps and stale issue by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2408 +* feat: new 'SEL' Command for Quick Tools by @Elitex07 in https://github.com/Acode-Foundation/Acode/pull/2414 +* feat(ui): use motion for page, tab, switch and press gestures animation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2406 +* refactor(core): centralize plugin unmount error boundary and fix console telemetry by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2422 +* fix: language mode mapping to add maps for paths which doesnt exists by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2430 +* fix(editor): preserve restored tab editability while loading by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2431 +* fix(quicktools): prevent editor blur when tapping toolbar immediately after typing by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2432 +* feat: add native app auth code login flow by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2440 +* feat: improve CodeMirror quick tools modifier support by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2435 +* fix(security) critical security issue by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2442 +* fix: skip recommendation for binary file by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2446 +* feat(editor): implement multi-pane split layout by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2416 +* fix: plugin page ui for big screen by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2448 +* fix(editor): prevent styling loss flash on custom page tabs when splitting/closing panes by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2449 +* feat(lsp): group language servers into built-in, plugin, and custom categories by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2452 +* refactor(ui): improved toast and notification animations using motion by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2453 +* feat: added native crash handler by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2450 +* feat: make the clear command behave as reset by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2458 +* feat: Add hover and long press tooltips to quicktools items by @gahanad in https://github.com/Acode-Foundation/Acode/pull/2456 +* fix: add missing autoclosebracket keymap(paired bracket deletion) by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2472 +* fix: implement editor tab history navigation (#1819) by @Elitex07 in https://github.com/Acode-Foundation/Acode/pull/2459 +* fix(lsp): refresh installation status on the correct settings page by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2482 +* fix(editor): sync replacement untitled file state by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2483 +* feat: add cobalt editor theme by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2484 +* fix: zip project import by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2473 +* chore: update the xtermjs to v6 and fix session creation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2487 +* fix(editor): improve wrapped line indentation and keep text wrap off by default by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2507 +* fix(editor): prevent syntax highlight color flicker on state recreation (#2304) by @Elitex07 in https://github.com/Acode-Foundation/Acode/pull/2457 +* Make line commands aware of folded blocks by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2508 +* fix: move bashrc sourcing to bottom of initrc so bashrc can override … by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2523 +* fix(settings): sync global search switch behavior and animation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2527 +* refactor(editor): centralize CodeMirror commands and keybindings by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2516 +* feat(lsp): add document color chips with regex fallback by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2533 +* feat(lsp): add pull diagnostics and native TypeScript 7 by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2537 +* feat(lsp): add web worker language servers as defaults by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2531 +* fix: system theme by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2524 +* feat(editor): add indentation folding for legacy modes(as fallback) by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2538 +* feat: add WebView Plugin API by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2525 +* feat(files): move workspace indexing and search to native for saf/files by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2529 +* fix: upgrade tar to 7.5.19 (CVE-2026-59873) by @anupamme in https://github.com/Acode-Foundation/Acode/pull/2544 +* fix(fileBrowser): exclude non-selectable system utility tiles from batch selection operations by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2545 +* refactor(file-browser): extract reusable deletion logic and abstract Termux URI validation by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2548 +* feat(file-browser): integrate selection mode state with `actionStack` for back navigation by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2546 +* feat(files): skip excluded paths during copy operations by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2555 +* fix: the processutils in ProcessUtils.java by @anupamme in https://github.com/Acode-Foundation/Acode/pull/2557 +* fix: sanitize input hints to prevent XSS by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2559 +* feat: proot debug toggle by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2563 +* Improve recent dialog path readability by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2567 +* Fix CodeMirror theme colors and add Catppuccin variants by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2568 +* feat(editor): add configurable horizontal scroll margin to CodeMirror by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2569 +* fix(quick-tools): add visible close button to search when toggler is off by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2570 +* i18n: update Hungarian translations by @summoner001 in https://github.com/Acode-Foundation/Acode/pull/2207, https://github.com/Acode-Foundation/Acode/pull/2387, https://github.com/Acode-Foundation/Acode/pull/2429, https://github.com/Acode-Foundation/Acode/pull/2478, https://github.com/Acode-Foundation/Acode/pull/2485, https://github.com/Acode-Foundation/Acode/pull/2542, https://github.com/Acode-Foundation/Acode/pull/2558 +* i18n: update Indonesian translations and localization strings by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2330, https://github.com/Acode-Foundation/Acode/pull/2372, https://github.com/Acode-Foundation/Acode/pull/2417, https://github.com/Acode-Foundation/Acode/pull/2479 +* i18n: update Simplified and Traditional Chinese translations by @LaunchLee in https://github.com/Acode-Foundation/Acode/pull/2468, https://github.com/Acode-Foundation/Acode/pull/2571 +* i18n: update Yemeni Arabic translations by @mohamedElneser in https://github.com/Acode-Foundation/Acode/pull/2480 +* i18n: update Indonesian translations by @Elderellerser in https://github.com/Acode-Foundation/Acode/pull/2491 + +## v1.12.6 + +* Refactor boot script and add editor interaction handler by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2216 +* fix(touchSelectionMenu): prevent menu overlap with cm-tooltips by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2220 +* fix: suppressed startup auth related toast instead just log it by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2222 +* feat: add option to control scrollbar height by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2223 +* feat: add astro mode (with lezer parser and grammar) by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2224 +* fix: improve cursor and quicktoolbar by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2225 +* feat(editor): make scroll-past-end bottom margin configurable by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2226 +* feat: Improve binary file skipping in sidebar search by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2229 +* fix(editor): preserve selected theme after sidebar file moves by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2230 +* ux improvements by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2231 +* feat(terminal): add custom touch scrolling with momentum physics by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2232 +* feat(terminal): add terminal theme picker to Theme Settings page by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2234 +* fix(lsp): show dynamic install status label with loader feedback by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2235 +* i18n(id-id): update strings by @hyperz111 in https://github.com/Acode-Foundation/Acode/pull/2228 +* feat: Improve LSP server reuse check with bridge status endpoint by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2238 +* i18n(lang.js): Update Indonesian language name to Bahasa Indonesia by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2236 +* feat(color-picker): add format dropdown, cancel button, and cancellat… by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2240 +* fix: pro detection by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2248 +* i18n(id): refine translations for a more natural and accurate phrasing by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2239 +* refactor(lsp): decouple runtime execution from built-in Alpine & support custom runtime providers by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2241 +* feat: improve the indexing and search UI/UX and few fallbacks stuff by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2256 +* fix: version parsing failure on nightly tags by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2249 +* feat: added config proxy by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2246 +* fix: disable CodeMirror EditContext by default by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2258 +* fix(lsp): check Terminal installation before installing server for builtin Alpine by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2259 +* fix(sidebar): preserve state across orientation changes by @Elitex07 in https://github.com/Acode-Foundation/Acode/pull/2219 +* fix: make indent guide stable and close to vscode one by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2266 +* fix(editor): prevent cursor snap after scrollbar drag by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2263 +* feat(quickTools): replace checkbox with height select & dynamic toggler by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2278 +* chore(deps): bump markdown-it from 14.1.1 to 14.2.0 by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/2286 +* chore(deps): bump dompurify from 3.4.3 to 3.4.10 by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/2271 +* chote(i18n): update german translation by @Mythryl-dev in https://github.com/Acode-Foundation/Acode/pull/2293 +* feat: do file-listing and index on java for file:/// and saf locations by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2283 +* improve vscode editor theme +* add few more popular editor themes like nord, AyuDark, GruvboxDark, MaterialPalenight. +* enable jsx in js mode + +## v1.12.5 + +* fix: custom fonts by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2192 +* fix(editor): stabilize restored tab highlighting by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2193 +* feat(terminal): bundle everything into the apk by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2197 +* improve the lsp message and ace to codemirror related clarrification by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2203 +* fix(terminal): handle axs symlink runtime checks by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2204 +* fix(i18n): Improve Indonesian translation naturalness and fix missing entries by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2190 +* fix(lsp): add dont ask again for missing terminal prompt by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2208 + +## v1.12.4 + +* chore(i18n): update strings in hu_hu.json by @summoner001 in https://github.com/Acode-Foundation/Acode/pull/2171 +* fix: Executor arguments getting ignored by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2176 +* fix: allow subdomain of acode.app by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2179 +* fix: highlighting issue happening due to state reuse by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2180 +* i18n(id-id): update strings by @hyperz111 in https://github.com/Acode-Foundation/Acode/pull/2178 +* feat: polish welcome tab with dynamic shortcuts, dismiss tracking, an… by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2182 +* fix: revert customtabs for plugins by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2183 +* fix: error when terminating terminal + fixed build by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2184 + +## v1.12.0 (970) + +### Important +* important(editor): Acode has migrated from Ace to CodeMirror. This is a major editor engine change and some plugins that depend on Ace internals may need updates for full compatibility. + +### Features +* feat(file-browser): add Copy Relative Path context menu option by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1854 +* feat(plugin-api): add PluginContext by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1867 +* feat(ui): improve splash screen by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1888 +* feat(shortcuts): pin file shortcuts to the home screen by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1889 +* feat(plugin-api): expose `isCodeMirror` flag on editor manager by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1892 +* feat(plugin-api): add Ace compatibility shims for plugins by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1893 +* feat(codemirror): support `shift` + click selection by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/1899 +* feat(terminal): add touch selection More menu API and select dialog wiring by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1905 +* feat(settings): add sponsor sidebar icon visibility toggle by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1906 +* feat(plugin-api): add secrets plugin API by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1902 +* feat(ads): add rewarded ads so free users can earn ad-free time by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1918 +* feat(plugin-api): expose CodeMirror packages for plugins by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1924 +* feat(editor): add Luau mode by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1927 +* feat(themes): add premium themes and overhaul legacy themes by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1930 +* feat(settings): add swatch previews to theme settings by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1931 +* feat(settings): redesign settings UI and localize help text by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1933 +* feat(native): move `checksumText` to native by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1942 +* feat(plugins): limit plugin installation load by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1951 +* feat(executor): add spawn stream support by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1972 +* feat(codemirror): improve teardrop handles, scrolling, and selection quality by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1971 +* feat(tabs): add pin and unpin support for editor and non-editor tabs by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1984 +* feat(native): improve `launchApp` by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1987 +* feat(fonts): add target-based font assignments and app font option by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1994 +* feat(tabs): add close left, close right, and close other tab commands by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2026 +* feat(storage): add public directory and merge `/home` with `/public` by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2049 +* feat(editor): add setting to disable HTML tag auto closing by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2051 +* feat(editor): select line on CodeMirror line number gutter click by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2052 +* feat(settings): add editor and UI zoom commands by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2058 +* feat(commands): restore `formatCode` command in CodeMirror 6 by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/2063 + +### Fixes +* fix(terminal): normalize `acode open` paths so folder name is not `.` by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1864 +* fix(plugin): prevent plugin `; + const $script = ( + + ); + + const iconApi = fileIcons.bindPlugin($script, pluginId); $script.onerror = (error) => { + fileIcons.unregisterByPlugin(pluginId); reject( new Error( `Failed to load script for plugin ${pluginId}: ${error.message || error}`, @@ -53,13 +81,19 @@ export default async function loadPlugin(pluginId, justInstalled = false) { } await acode.initPlugin(pluginId, baseUrl, $page, { + fileIcons: iconApi, cacheFileUrl: await helpers.toInternalUri(cacheFile), cacheFile: fsOperation(cacheFile), firstInit: justInstalled, + ctx: await generatePluginContext( + pluginId, + JSON.stringify(pluginJson), + ), }); resolve(); } catch (error) { + fileIcons.unregisterByPlugin(pluginId); reject(error); } }; diff --git a/src/lib/loadPlugins.js b/src/lib/loadPlugins.js index 415a159444..c3475fdaba 100644 --- a/src/lib/loadPlugins.js +++ b/src/lib/loadPlugins.js @@ -22,77 +22,217 @@ const THEME_IDENTIFIERS = new Set([ "moonlight", "bluloco", "acode.plugin.extra_syntax_highlights", + "documentsviewer", ]); -export default async function loadPlugins(loadOnlyTheme = false) { - const plugins = await fsOperation(PLUGIN_DIR).lsDir(); - const results = []; - const failedPlugins = []; - const loadedPlugins = new Set(); +export const onPluginLoadCallback = Symbol("onPluginLoadCallback"); +export const onPluginsLoadCompleteCallback = Symbol( + "onPluginsLoadCompleteCallback", +); + +export const LOADED_PLUGINS = new Set(); +export const BROKEN_PLUGINS = new Map(); +const AUTO_DISABLED_PLUGINS = new Set(); +const PLUGIN_LOAD_TIMEOUT = 15000; +const PLUGIN_DISABLE_TIMEOUT = 60000; +let pluginDisabledUpdateQueue = Promise.resolve(); +let initialPluginLoadComplete = false; + +class PluginLoadTimeoutError extends Error { + constructor() { + super("Plugin load timeout"); + this.name = "PluginLoadTimeoutError"; + } +} - if (plugins.length > 0) { - toast(strings["loading plugins"]); +export default async function loadPlugins(loadOnlyTheme = false) { + if (!loadOnlyTheme) { + initialPluginLoadComplete = false; } - let pluginsToLoad = []; - const currentTheme = settings.value.appTheme; - const enabledMap = settings.value.pluginsDisabled || {}; + try { + const plugins = await fsOperation(PLUGIN_DIR).lsDir(); + const results = []; - if (loadOnlyTheme) { - // Only load theme plugins matching current theme - pluginsToLoad = plugins.filter((pluginDir) => { - const pluginId = Url.basename(pluginDir.url); - return isThemePlugin(pluginId) && !loadedPlugins.has(pluginId); - }); - } else { - // Load non-theme plugins that aren't loaded yet and are enabled - pluginsToLoad = plugins.filter((pluginDir) => { + if (plugins.length > 0) { + toast(strings["loading plugins"]); + } + + let pluginsToLoad = []; + const currentTheme = settings.value.appTheme; + const enabledMap = settings.value.pluginsDisabled || {}; + + if (loadOnlyTheme) { + // Only load theme plugins matching current theme + pluginsToLoad = plugins.filter((pluginDir) => { + const pluginId = Url.basename(pluginDir.url); + // Skip already loaded and plugins that were previously marked broken + return ( + isThemePlugin(pluginId) && + !LOADED_PLUGINS.has(pluginId) && + enabledMap[pluginId] !== true && + !BROKEN_PLUGINS.has(pluginId) + ); + }); + } else { + // Load non-theme plugins that aren't loaded yet and are enabled + pluginsToLoad = plugins.filter((pluginDir) => { + const pluginId = Url.basename(pluginDir.url); + // Skip theme plugins, already loaded, disabled or previously marked broken + return ( + !isThemePlugin(pluginId) && + !LOADED_PLUGINS.has(pluginId) && + enabledMap[pluginId] !== true && + !BROKEN_PLUGINS.has(pluginId) + ); + }); + } + + const loadPromises = pluginsToLoad.map(async (pluginDir) => { const pluginId = Url.basename(pluginDir.url); - return ( - !isThemePlugin(pluginId) && - !loadedPlugins.has(pluginId) && - enabledMap[pluginId] !== true - ); + + if (loadOnlyTheme && currentTheme) { + const pluginIdLower = pluginId.toLowerCase(); + const currentThemeLower = currentTheme.toLowerCase(); + const matchFound = pluginIdLower.includes(currentThemeLower); + // Skip if: + // 1. No match found with current theme AND + // 2. It's not a theme plugin at all + if (!matchFound && !isThemePlugin(pluginId)) { + return; + } + } + + try { + results.push(await loadPluginWithTimeout(pluginId)); + } catch (error) { + console.error(`Error loading plugin ${pluginId}:`, error); + results.push(false); + } }); + + await Promise.allSettled(loadPromises); + + acode[onPluginsLoadCompleteCallback](); + return results.filter(Boolean).length; + } finally { + if (!loadOnlyTheme) { + initialPluginLoadComplete = true; + } } +} - // Load plugins concurrently - const loadPromises = pluginsToLoad.map(async (pluginDir) => { - const pluginId = Url.basename(pluginDir.url); - - if (loadOnlyTheme && currentTheme) { - const pluginIdLower = pluginId.toLowerCase(); - const currentThemeLower = currentTheme.toLowerCase(); - const matchFound = pluginIdLower.includes(currentThemeLower); - // Skip if: - // 1. No match found with current theme AND - // 2. It's not a theme plugin at all - if (!matchFound && !isThemePlugin(pluginId)) { - return; - } +export function isInitialPluginLoadComplete() { + return initialPluginLoadComplete; +} + +export async function loadPluginWithTimeout(pluginId, justInstalled = false) { + const pluginState = { settled: false }; + const pluginLoadPromise = loadPlugin(pluginId, justInstalled) + .catch(async (error) => { + pluginState.settled = true; + await markPluginBroken(pluginId, error); + throw error; + }) + .then(async () => { + pluginState.settled = true; + await markPluginLoaded(pluginId, justInstalled); + }); + + try { + // Let app startup continue if a plugin is slow, but keep loading it in + // the background so good plugins on slower devices can still recover. + await Promise.race([ + pluginLoadPromise, + new Promise((_, rej) => + setTimeout( + () => rej(new PluginLoadTimeoutError()), + PLUGIN_LOAD_TIMEOUT, + ), + ), + ]); + return true; + } catch (error) { + if (error instanceof PluginLoadTimeoutError) { + markPluginTimedOut(pluginId, pluginState); + return false; } + throw error; + } +} + +async function markPluginLoaded(pluginId, justInstalled = false) { + LOADED_PLUGINS.add(pluginId); + acode[onPluginLoadCallback](pluginId); + + // clear broken mark if present + if (BROKEN_PLUGINS.has(pluginId)) { + BROKEN_PLUGINS.delete(pluginId); + } + + if (justInstalled || AUTO_DISABLED_PLUGINS.has(pluginId)) { + AUTO_DISABLED_PLUGINS.delete(pluginId); + await updatePluginDisabled(pluginId, false); + } +} + +async function markPluginBroken(pluginId, error) { + // mark plugin as broken to avoid repeated attempts until user intervenes + BROKEN_PLUGINS.set(pluginId, { + error: String(error.message || error), + timestamp: Date.now(), + }); + + AUTO_DISABLED_PLUGINS.add(pluginId); + await updatePluginDisabled(pluginId, true); +} + +function markPluginTimedOut(pluginId, pluginState) { + BROKEN_PLUGINS.set(pluginId, { + error: "Plugin load timeout", + timestamp: Date.now(), + }); + + setTimeout(async () => { try { - await loadPlugin(pluginId); - loadedPlugins.add(pluginId); - results.push(true); + if (pluginState.settled || LOADED_PLUGINS.has(pluginId)) return; + await markPluginBroken(pluginId, new Error("Plugin load timeout")); } catch (error) { - console.error(`Error loading plugin ${pluginId}:`, error); - failedPlugins.push(pluginId); - results.push(false); + console.error(`Failed to disable timed out plugin ${pluginId}:`, error); + window.log("error", `Failed to disable timed out plugin ${pluginId}:`); + window.log("error", error); } - }); + }, PLUGIN_DISABLE_TIMEOUT - PLUGIN_LOAD_TIMEOUT); +} - await Promise.allSettled(loadPromises); +function updatePluginDisabled(pluginId, disabled) { + const updatePromise = pluginDisabledUpdateQueue + .catch(() => {}) + .then(async () => { + const disabledMap = { ...(settings.value.pluginsDisabled || {}) }; + if (!disabled && !(pluginId in disabledMap)) return; + if (disabledMap[pluginId] === disabled) return; - if (failedPlugins.length > 0) { - setTimeout(() => { - cleanupFailedPlugins(failedPlugins).catch((error) => { - console.error("Failed to cleanup plugins:", error); - }); - }, 1000); - } - return results.filter(Boolean).length; + if (disabled) { + disabledMap[pluginId] = true; + } else { + delete disabledMap[pluginId]; + } + + await settings.update({ pluginsDisabled: disabledMap }, false); + }); + + pluginDisabledUpdateQueue = updatePromise.catch((error) => { + console.error("Failed to update plugin disabled state:", error); + window.log( + "error", + `Failed to update plugin (ID: ${pluginId}) disabled state:`, + ); + window.log("error", error); + }); + + return updatePromise; } function isThemePlugin(pluginId) { @@ -101,16 +241,3 @@ function isThemePlugin(pluginId) { // Check if any theme identifier is present in the plugin ID return Array.from(THEME_IDENTIFIERS).some((theme) => id.includes(theme)); } - -async function cleanupFailedPlugins(pluginIds) { - for (const pluginId of pluginIds) { - try { - const pluginDir = Url.join(PLUGIN_DIR, pluginId); - if (await fsOperation(pluginDir).exists()) { - await fsOperation(pluginDir).delete(); - } - } catch (error) { - console.error(`Failed to cleanup plugin ${pluginId}:`, error); - } - } -} diff --git a/src/lib/logger.js b/src/lib/logger.js index a2e8d05c69..48c58b9fa5 100644 --- a/src/lib/logger.js +++ b/src/lib/logger.js @@ -1,6 +1,6 @@ import fsOperation from "fileSystem"; import Url from "utils/Url"; -import constants from "./constants"; +import config from "./config"; /* /** @@ -33,7 +33,7 @@ class Logger { this.#logBuffer = new Map(); this.#maxBufferSize = maxBufferSize; this.#logLevel = logLevel; - this.#logFileName = constants.LOG_FILE_NAME; + this.#logFileName = config.LOG_FILE_NAME; this.#flushInterval = flushInterval; this.#maxFileSize = maxFileSize; this.#startAutoFlush(); // Automatically flush logs at intervals @@ -76,10 +76,10 @@ class Logger { #writeLogToFile = async (logContent) => { try { - const logFilePath = Url.join(DATA_STORAGE, constants.LOG_FILE_NAME); + const logFilePath = Url.join(DATA_STORAGE, config.LOG_FILE_NAME); if (!(await fsOperation(logFilePath).exists())) { await fsOperation(window.DATA_STORAGE).createFile( - constants.LOG_FILE_NAME, + config.LOG_FILE_NAME, logContent, ); } else { diff --git a/src/lib/notificationManager.js b/src/lib/notificationManager.js index 52518402dd..0ec79beea5 100644 --- a/src/lib/notificationManager.js +++ b/src/lib/notificationManager.js @@ -1,10 +1,33 @@ import sidebarApps from "sidebarApps"; +import DOMPurify from "dompurify"; +import Ref from "html-tag-js/ref"; +import { animate } from "motion"; + +/** + * Notification create param + * @typedef {object} NotificationProps + * @prop {string} [props.id] + * @prop {string} props.title + * @prop {string} props.message + * @prop {string} [props.icon] + * @prop {number} [props.time] + * @prop {(notification: NotificationProps) => void} [props.action] + * @prop {(notification: NotificationProps) => void} [props.onDismiss] + * @prop {{text:string, icon?:string, action:(notification: NotificationProps) => void}[]} [props.actions] + * @prop {() => number} [props.progress] + * @prop {() => loading} [props.loading = false] + * @prop {"info"|"success"|"warning"|"error"} [props.type] + */ // Singleton instance let instance = null; +let notificationCounter = 0; + +const notificationToastContainer = ( +
+); -export default class NotificationManager { - DEFAULT_ICON = ``; +class NotificationManager { MAX_NOTIFICATIONS = 20; notifications = []; REFRESH_INTERVAL = 60000; // 1 minute refresh interval @@ -19,16 +42,9 @@ export default class NotificationManager { } init() { - document.body.appendChild( -
, - ); + document.body.appendChild(notificationToastContainer); this.renderNotifications(); this.startTimeUpdates(); - - sidebarApps - .get("notification") - ?.querySelector(".notifications-container") - .addEventListener("click", this.handleClick.bind(this)); } startTimeUpdates() { @@ -50,14 +66,12 @@ export default class NotificationManager { container.querySelectorAll(".notification-time").forEach((timeElement) => { const notificationItem = timeElement.closest(".notification-item"); - const id = notificationItem?.dataset.id; + const id = notificationItem?.id; if (!id) return; - const notification = this.notifications.find( - (n) => n.id === Number.parseInt(id), - ); + const notification = this.notifications.find((n) => n.id === id); if (notification) { - timeElement.textContent = this.formatTime(notification.time); + timeElement.textContent = this.#formatTime(notification.time); } }); } @@ -79,92 +93,195 @@ export default class NotificationManager { }); } - handleClick(e) { - const dismissButton = e.target.closest(".action-button"); - if (!dismissButton) return; + /** + * + * @param {NotificationProps} notification + * @returns + */ + createNotificationElement(notification) { + return this.#createNotification(notification, "notification"); + } - e.stopPropagation(); - const notificationElement = dismissButton.closest(".notification-item"); - if (!notificationElement) return; + /** + * + * @param {NotificationProps} notification + * @returns + */ + createToastNotification(notification) { + return this.#createNotification(notification, "toast"); + } - const id = notificationElement.dataset.id; - if (id) { - const index = this.notifications.findIndex( - (n) => n.id === Number.parseInt(id), - ); - if (index > -1) { - notificationElement.remove(); - this.notifications.splice(index, 1); - this.renderNotifications(); + /** + * + * @param {NotificationProps} notification + * @param {"toast" | "notification"} type + * @returns + */ + #createNotification(notification, type) { + let onDismiss; + + if (type === "toast") { + onDismiss = (e) => { + e.stopPropagation(); + this.#hideNotificationToast(notification); + if (typeof notification.onDismiss === "function") { + notification.onDismiss(notification); + } + }; + + if ( + typeof notification.loading !== "function" || + !notification.loading() + ) { + setTimeout(() => { + if (!notificationToastContainer.get(`#${notification.id}`)) return; + this.#hideNotificationToast(notification); + if (typeof notification.onDismiss === "function") { + notification.onDismiss(notification); + } + }, 5000); } + } else { + onDismiss = (e) => { + e.stopPropagation(); + this.#clearNotification(notification.id); + }; } - } - createNotificationElement(notification) { - const element = ( + const safeIcon = this.#parseIcon(notification.icon); + const safeTitle = this.#sanitizeText(notification.title); + const safeMessage = this.#sanitizeText(notification.message); + const elementRef = Ref(); + + if (typeof notification.loading === "function" && notification.loading()) { + elementRef.onref = (el) => { + if (notification.loading()) { + elementRef.classList.add("loading"); + const nextFrame = () => { + if (!notification.loading()) { + if (type === "toast") { + this.#hideNotificationToast(notification); + if (typeof notification.onDismiss === "function") { + notification.onDismiss(notification); + } + } + + elementRef.classList.remove("loading"); + } else { + requestAnimationFrame(nextFrame); + } + }; + + requestAnimationFrame(nextFrame); + } + }; + } + + return (
- ); - element.innerHTML = ` -
- ${this.parseIcon(notification.icon)} -
-
-
- ${notification.title} - ${this.formatTime(notification.time)} -
-
${notification.message}
-
-
Dismiss
+ onclick={ + notification.action ? () => notification.action(notification) : null + } + > +
+
{safeIcon}
+
+ {safeTitle} + {type === "notification" && ( + + {this.#formatTime(notification.time)} + + )} +
+
+
{safeMessage}
+ {Array.isArray(notification.actions) && + notification.actions.length > 0 && ( +
+ {notification.actions.map((action) => ( + + ))} +
+ )}
- `; - if (notification.action) { - element.addEventListener("click", (e) => { - if (e.target.closest(".action-button")) { - return; - } - notification.action(notification); - }); - } - return element; + ); } - createToastNotification(notification) { - const element = ( -
+ /** + * + * @param {NotificationProps} notification + */ + closeNotification(notification) { + this.#hideNotificationToast(notification); + this.#clearNotification(notification.id); + } + + /** + * hide notification + * @param {NotificationProps} notification + * @returns + */ + #hideNotificationToast(notification) { + const notificationElement = notificationToastContainer.get( + `#${notification.id}`, ); - element.innerHTML = ` -
${this.parseIcon(notification.icon)}
-
-
- ${notification.title} -
-
${notification.message}
-
- ${notification.autoClose ? "" : ``} - `; - if (notification.action) { - element.addEventListener("click", () => - notification.action(notification), - ); - } - if (notification.autoClose) { - setTimeout(() => { - element.classList.add("hiding"); - setTimeout(() => element.remove(), 300); - }, 5000); + if (!notificationElement) return; + animate( + notificationElement, + { opacity: 0, transform: "translateX(100%)" }, + { duration: 0.25, ease: "easeIn" }, + ).then(() => { + notificationElement.remove(); + }); + } + + #clearNotification(id) { + const container = sidebarApps + .get("notification") + ?.querySelector(".notifications-container"); + + if (!container) return; + + const index = this.notifications.findIndex((n) => n.id === id); + if (index > -1) { + this.notifications.splice(index, 1); + if (!this.notifications.length) this.#setUnread(false); + this.renderNotifications(); } - return element; } - addNotification(notification) { + /** + * Notification create + * @param {NotificationProps} notification + */ + pushNotification(notification) { + if (!notification) { + throw new Error("Notification param not provided"); + } + + notification = { + ...notification, + id: `notification_${++notificationCounter}`, + time: new Date(), + }; + this.notifications.unshift(notification); // Remove oldest if exceeding limit @@ -172,57 +289,114 @@ export default class NotificationManager { this.notifications.pop(); } + if (!this.timeUpdateInterval) { + this.startTimeUpdates(); + } + this.renderNotifications(); + if (!this.#isPanelVisible()) this.#setUnread(true); // show toast notification - document - .querySelector(".notification-toast-container") - ?.appendChild(this.createToastNotification(notification)); - } - - pushNotification({ - title, - message, - icon, - autoClose = true, - action = null, - type = "info", - }) { - const notification = { - id: Date.now(), - title, - message, - icon, - action, - autoClose, - type, - time: new Date(), - }; - this.addNotification(notification); + const $toastEl = this.createToastNotification(notification); + const $container = document.querySelector(".notification-item-container"); + if ($container) { + $container.appendChild($toastEl); + + $toastEl.style.opacity = "0"; + $toastEl.style.transform = "translateX(100%)"; + + animate( + $toastEl, + { opacity: 1, transform: "translateX(0)" }, + { type: "spring", stiffness: 300, damping: 26 }, + ); + } } - parseIcon(icon) { - if (!icon) return this.DEFAULT_ICON; - if (icon.startsWith("`; - return ``; + #parseIcon(icon) { + if (typeof icon !== "string" || !icon) { + return ; + } + if (icon.startsWith("; + } + if (icon.startsWith("data:") || icon.startsWith("http")) { + return notification; + } + return ; } - formatTime(date) { + #sanitizeText(text) { + return DOMPurify.sanitize(String(text ?? ""), { + ALLOWED_TAGS: [], + ALLOWED_ATTR: [], + }); + } + + #sanitizeIcon(iconMarkup) { + return DOMPurify.sanitize(iconMarkup, { + USE_PROFILES: { html: true, svg: true }, + ALLOW_DATA_ATTR: false, + }); + } + + #formatTime(date) { const now = new Date(); const diff = Math.floor((now - date) / 1000); + const count = (unit) => Math.floor(diff / unit); + + if (diff < 60) return strings["just now"]; - if (diff < 60) return "Just now"; - if (diff < 3600) return `${Math.floor(diff / 60)}m`; - if (diff < 86400) return `${Math.floor(diff / 3600)}h`; - if (diff < 604800) return `${Math.floor(diff / 86400)}d`; + if (diff < 3600) { + const val = count(60); + return strings[val === 1 ? "min singular" : "min plural"].replace( + /\{count\}/, + val, + ); + } + + if (diff < 86400) { + const val = count(3600); + return strings[val === 1 ? "hour singular" : "hour plural"].replace( + /\{count\}/, + val, + ); + } + + if (diff < 604800) { + const val = count(86400); + return strings[val === 1 ? "day singular" : "day plural"].replace( + /\{count\}/, + val, + ); + } return date.toLocaleDateString(); } + /** + * Clears the unread dot on the notifications sidebar icon + */ + markAllRead() { + this.#setUnread(false); + } + + #isPanelVisible() { + const $panel = sidebarApps.get("notification"); + return !!($panel?.isConnected && $panel.closest("#sidebar")?.activated); + } + + /** + * @param {boolean} unread + */ + #setUnread(unread) { + // Kept on so it applies even before the sidebar icon exists + document.body.classList.toggle("has-unread-notifications", unread); + } + clearAll() { this.notifications = []; + this.#setUnread(false); this.renderNotifications(); if (this.timeUpdateInterval) { clearInterval(this.timeUpdateInterval); @@ -230,3 +404,6 @@ export default class NotificationManager { } } } + +const notificationManager = new NotificationManager(); +export default notificationManager; diff --git a/src/lib/openFile.js b/src/lib/openFile.js index 58319a09da..c90b4f8523 100644 --- a/src/lib/openFile.js +++ b/src/lib/openFile.js @@ -1,4 +1,5 @@ import fsOperation from "fileSystem"; +import { Text } from "@codemirror/state"; import AudioPlayer from "components/audioPlayer"; import alert from "dialogs/alert"; import confirm from "dialogs/confirm"; @@ -7,10 +8,13 @@ import { reopenWithNewEncoding } from "palettes/changeEncoding"; import { decode, detectEncoding } from "utils/encodings"; import helpers from "utils/helpers"; import EditorFile from "./editorFile"; +import { promoteSessionPersistence } from "./fileSessionPersistence"; import fileTypeHandler from "./fileTypeHandler"; import recents from "./recents"; import appSettings from "./settings"; +let loadingFileCount = 0; + /** * @typedef {object} FileOptions * @property {string} text @@ -20,6 +24,10 @@ import appSettings from "./settings"; * @property {string} encoding * @property {string} mode * @property {string} uri + * @property {string} paneId + * @property {boolean} persistInSession + * @property {AbortSignal} signal Discard an obsolete open before activating its file. + * @property {boolean} external Receive an Android file intent; report failures to the batch and require document handlers. */ /** @@ -29,27 +37,51 @@ import appSettings from "./settings"; */ export default async function openFile(file, options = {}) { + const { signal } = options; + if (signal?.aborted) return; + let releaseTitleLoader; try { let uri = typeof file === "string" ? file : file.uri; if (!uri) return; /**@type {EditorFile} */ const existingFile = editorManager.getFile(uri, "uri"); - const { cursorPos, render, onsave, text, mode, encoding } = options; + const { + cursorPos, + render, + onsave, + text, + mode, + encoding, + paneId, + persistInSession, + } = options; if (existingFile) { + promoteSessionPersistence(existingFile, persistInSession); // If file is already opened and new text is provided - const existingText = existingFile.session.getValue(); - const existingCursorPos = existingFile.session.selection.getCursor(); + const incomingDoc = + text != null ? Text.of(String(text).split("\n")) : null; // If file is already opened - existingFile.makeActive(); + const targetPane = paneId + ? editorManager.panes?.find((pane) => pane.id === paneId) + : null; + if (targetPane) { + editorManager.moveFileToPane?.(existingFile, targetPane, { + activate: true, + }); + } else { + existingFile.makeActive(); + } + + const { editor } = editorManager; if (onsave) { existingFile.onsave = onsave; } - if (text && existingText !== text) { + if (incomingDoc && !existingFile.session?.doc?.eq?.(incomingDoc)) { // let confirmation = true; // if (existingFile.isUnsaved) { // const message = strings['reopen file'].replace('{file}', existingFile.filename); @@ -57,18 +89,27 @@ export default async function openFile(file, options = {}) { // } // if (confirmation) { // } - existingFile.session.setValue(text); + editor.dispatch({ + changes: { + from: 0, + to: editor.state.doc.length, + insert: String(text), + }, + }); } - if ( - cursorPos && - existingCursorPos && - existingCursorPos.row !== cursorPos.row && - existingCursorPos.column !== cursorPos.column - ) { - existingFile.session.selection.moveCursorTo( - cursorPos.row, - cursorPos.column, + // Move cursor if requested and different + try { + if (cursorPos) { + const cur = editor.getCursorPosition(); + if (cur.row !== cursorPos.row || cur.column !== cursorPos.column) { + editor.gotoLine(cursorPos.row, cursorPos.column); + } + } + } catch (error) { + console.warn( + `Failed to move cursor for ${existingFile.filename || existingFile.uri}`, + error, ); } @@ -78,13 +119,15 @@ export default async function openFile(file, options = {}) { return; } - loader.showTitleLoader(); + releaseTitleLoader = acquireTitleLoader(signal); const settings = appSettings.value; const fs = fsOperation(uri); const fileInfo = await fs.stat(); + if (signal?.aborted) return; const name = fileInfo.name || file.filename || uri; - const readOnly = fileInfo.canWrite ? false : true; + const readOnly = fileInfo.canWrite === false; const createEditor = (isUnsaved, text, detectedEncoding) => { + if (signal?.aborted) return; new EditorFile(name, { uri, text, @@ -95,11 +138,24 @@ export default async function openFile(file, options = {}) { readOnly, encoding: detectedEncoding || encoding, SAFMode: mode, + savedMtime: helpers.getStatMtime(fileInfo), + diskMtime: helpers.getStatMtime(fileInfo), + paneId, + persistInSession, }); }; // Check for registered file handlers const customHandler = fileTypeHandler.getFileHandler(name); + const needsDocumentHandler = + options.external && + /\.(pdf|docx|dotx|xlsx|xls|ods|pptx|ppsx|potx)$/i.test(name); + if (needsDocumentHandler && !customHandler) { + throw Object.assign(new Error("Document handler unavailable"), { + code: "DOCUMENT_HANDLER_UNAVAILABLE", + filename: name, + }); + } if (customHandler) { try { await customHandler.handleFile({ @@ -114,17 +170,27 @@ export default async function openFile(file, options = {}) { encoding, mode, createEditor, + signal, }, }); return; } catch (error) { + if (signal?.aborted) return; console.error(`File handler '${customHandler.id}' failed:`, error); + if (options.external) { + throw Object.assign( + new Error("Document handler failed", { cause: error }), + { + filename: name, + }, + ); + } // Continue with default handling if custom handler fails } } - if (text) { - // If file is not opened and has unsaved text + if (text != null) { + // If file is not opened and has unsaved text (may be "" after a replace) createEditor(true, text); return; } @@ -135,6 +201,10 @@ export default async function openFile(file, options = {}) { if (videoRegex.test(name)) { const objectUrl = await fileToDataUrl(uri); + if (signal?.aborted) { + URL.revokeObjectURL(objectUrl); + return; + } const videoContainer = (
{ audioPlayer.cleanup(); @@ -370,8 +454,10 @@ export default async function openFile(file, options = {}) { // Else open a new file // Checks for valid file if (fileInfo.length * 0.000001 > settings.maxFileSize) { + if (options.external) + throw Object.assign(new Error("File too large"), { filename: name }); return alert( - strings.error.toUpperCase(), + strings.error, strings["file too large"].replace( "{size}", settings.maxFileSize + "MB", @@ -379,12 +465,20 @@ export default async function openFile(file, options = {}) { ); } + if ( + options.external && + (helpers.isBinary(name) || + helpers.isBinary({ name, mime: fileInfo.mime || fileInfo.type })) + ) { + throw Object.assign(new Error("Unsupported file"), { filename: name }); + } if (helpers.isBinary(uri)) { const confirmation = await confirm(strings.info, strings["binary file"]); - if (!confirmation) return; + if (!confirmation || signal?.aborted) return; } const binData = await fs.readFile(); + if (signal?.aborted) return; // Determine encoding: if explicit provided use it, otherwise // if settings.defaultFileEncoding === 'auto' then detect; else use the default as-is @@ -404,18 +498,37 @@ export default async function openFile(file, options = {}) { } } + if (signal?.aborted) return; const fileContent = await decode(binData, detectedEncoding); + if (signal?.aborted) return; createEditor(false, fileContent, detectedEncoding); if (mode !== "single") recents.addFile(uri); return; } catch (error) { - console.error(error); + if (options.external && !signal?.aborted) throw error; + if (!signal?.aborted) console.error(error); } finally { - loader.removeTitleLoader(); + releaseTitleLoader?.(); } } +/** Keep the shared indicator visible while any file open still needs it. */ +function acquireTitleLoader(signal) { + if (loadingFileCount++ === 0) loader.showTitleLoader(); + let released = false; + const release = () => { + // An aborted filesystem call may settle much later. Release immediately + // on abort, and make its eventual finally block a no-op. + if (released) return; + released = true; + signal?.removeEventListener("abort", release); + if (--loadingFileCount === 0) loader.removeTitleLoader(); + }; + signal?.addEventListener("abort", release, { once: true }); + return release; +} + /** * Converts file to data url * @param {string} file file url diff --git a/src/lib/openFolder.js b/src/lib/openFolder.js index 40c82e80fb..90b69856b6 100644 --- a/src/lib/openFolder.js +++ b/src/lib/openFolder.js @@ -1,6 +1,8 @@ import fsOperation from "fileSystem"; import sidebarApps from "sidebarApps"; +import fileSelection from "sidebarApps/files/selection"; import collapsableList from "components/collapsableList"; +import FileTree from "components/fileTree"; import Sidebar from "components/sidebar"; import tile from "components/tile"; import toast from "components/toast"; @@ -9,25 +11,101 @@ import confirm from "dialogs/confirm"; import prompt from "dialogs/prompt"; import select from "dialogs/select"; import escapeStringRegexp from "escape-string-regexp"; -import FileBrowser from "pages/fileBrowser"; +import tag from "html-tag-js"; +import fileIcons from "lib/fileIcons"; +import copyEntry from "utils/copyEntry"; +import { isExcludedFileOperationPath } from "utils/fileOperationExclusions"; import helpers from "utils/helpers"; import Path from "utils/Path"; +import Uri from "utils/Uri"; import Url from "utils/Url"; -import constants from "./constants"; +import config from "./config"; import * as FileList from "./fileList"; +import { loadFileBrowser } from "./lazyImports"; import openFile from "./openFile"; import recents from "./recents"; import appSettings from "./settings"; +const isTermuxSafUri = (value = "") => + value.startsWith("content://com.termux.documents/tree/"); +const isAcodeTerminalPublicSafUri = (value = "") => + value.startsWith("content://com.foxdebug.acode.documents/tree/"); +const isTerminalSafUri = (value = "") => + isTermuxSafUri(value) || isAcodeTerminalPublicSafUri(value); + +const getTerminalPaths = () => { + const packageName = window.BuildInfo?.packageName || "com.foxdebug.acode"; + const dataDir = `/data/user/0/${packageName}`; + const alpineRoot = `${dataDir}/files/alpine`; + const publicDir = `${dataDir}/files/public`; + return { alpineRoot, publicDir, dataDir }; +}; + +const isTerminalAccessiblePath = (url = "") => { + if (isAcodeTerminalPublicSafUri(url)) return true; + const { alpineRoot, publicDir } = getTerminalPaths(); + const cleanUrl = url.replace(/^file:\/\//, ""); + if (cleanUrl.startsWith(alpineRoot) || cleanUrl.startsWith(publicDir)) { + return true; + } + return false; +}; + +const convertToProotPath = (url = "") => { + const { alpineRoot, publicDir } = getTerminalPaths(); + if (isAcodeTerminalPublicSafUri(url)) { + try { + const { docId } = Uri.parse(url); + const cleanDocId = /::/.test(url) + ? decodeURIComponent(docId || "") + : docId || ""; + if (!cleanDocId) return "/public"; + if (cleanDocId.startsWith(publicDir)) { + return cleanDocId.replace(publicDir, "/public") || "/public"; + } + if (cleanDocId.startsWith("/public")) { + return cleanDocId; + } + if (cleanDocId.startsWith("public:")) { + const relativePath = cleanDocId.slice("public:".length); + return relativePath ? Path.join("/public", relativePath) : "/public"; + } + const relativePath = cleanDocId + .replace(/^\/+/, "") + .replace(/^public\//, ""); + return relativePath ? Path.join("/public", relativePath) : "/public"; + } catch (error) { + console.warn( + `Failed to parse public SAF URI for terminal conversion: ${url}`, + ); + return "/public"; + } + } + const cleanUrl = url.replace(/^file:\/\//, ""); + if (cleanUrl.startsWith(publicDir)) { + return cleanUrl.replace(publicDir, "/public"); + } + if (cleanUrl.startsWith(alpineRoot)) { + return cleanUrl.replace(alpineRoot, "") || "/"; + } + console.warn(`Unrecognized path for terminal conversion: ${url}`); + return cleanUrl; +}; + /** * @typedef {import('../components/collapsableList').Collapsible} Collapsible */ /** - * @typedef {object} ClipBoard + * @typedef {object} ClipBoardItem * @property {string} url - * @property {HTMLElement} $el - * @property {"cut"|"copy"} action + * @property {"file"|"dir"} type + */ + +/** + * @typedef {object} ClipBoard + * @property {ClipBoardItem[]} items + * @property {"cut"|"copy"|null} action */ /** @@ -46,6 +124,11 @@ import appSettings from "./settings"; /**@type {Folder[]} */ export const addedFolder = []; +/** + * Shared by every open folder so entries can be pasted across roots. + * @type {ClipBoard} + */ +const clipBoard = { items: [], action: null }; const ACODE_PLUGIN_MANIFEST_FILE = "plugin.json"; /** * Open a folder in the sidebar @@ -73,8 +156,26 @@ function openFolder(_path, opts = {}) { const $root = collapsableList(title, "folder", { allCaps: true, - ontoggle: () => expandList($root), + tail: createRootActions(() => $root), + ontoggle: () => { + setFolderLeadIcon($root, title, { isRoot: true }); + expandList($root); + // Folders also expand without a header tap (saved state, header + // actions, drag hover), so size them here rather than on click only. + // Only on expand: sizing collapses the other folders, and doing it on + // collapse would undo the folder that just opened. + // Imported lazily: the files app reads `strings` when it loads. + if ($root.unclasped) { + import("sidebarApps/files") + .then(({ fixHeight }) => { + // It may have closed again while the module loaded. + if ($root.unclasped) fixHeight($root); + }) + .catch(console.error); + } + }, }); + setFolderLeadIcon($root, title, { isRoot: true }); const $text = $root.$title.get(":scope>span.text"); $root.id = "r" + _path.hashCode(); @@ -108,35 +209,29 @@ function openFolder(_path, opts = {}) { url: _path, $node: $root, id: opts.id, - clipBoard: {}, + clipBoard, reload() { $root.collapse(); $root.expand(); }, }; + if (typeof listFiles !== "boolean") { + listFiles = appSettings.value.fileBrowser?.listFiles ?? true; + } + + folder.listFiles = listFiles; + addedFolder.push(folder); + editorManager.emit("update", "add-folder"); editorManager.onupdate("add-folder", event); editorManager.emit("add-folder", event); - (async () => { - if (typeof listFiles !== "boolean") { - const protocol = Url.getProtocol(_path).slice(0, -1); - const type = /^(content|file)$/.test(protocol) ? "" : ` (${protocol})`; - const message = strings["list files"].replace( - "{name}", - `${title}${type}`, - ); - listFiles = await confirm(strings.confirm, message, true); - } - - if (listFiles) { - FileList.addRoot({ url: _path, name: title }); - } - - folder.listFiles = listFiles; - addedFolder.push(folder); - })(); + if (listFiles) { + FileList.addRoot({ url: _path, name: title }).catch((err) => { + console.error("Failed to add root to FileList:", err); + }); + } if (listState[_path]) { $root.expand(); @@ -153,6 +248,7 @@ function openFolder(_path, opts = {}) { $root.remove(); } + FileList.remove(_path); const index = addedFolder.findIndex((folder) => folder.url === _path); if (index !== -1) addedFolder.splice(index, 1); editorManager.emit("update", "remove-folder"); @@ -161,6 +257,89 @@ function openFolder(_path, opts = {}) { } } +/** + * Quick actions on an open folder's header. With a mouse they appear on + * hover; on touch a single button opens the folder's menu (the same one as a + * long press), so idle headers stay clean. + * @param {() => Collapsible} getRoot + * @returns {HTMLElement} + */ +function createRootActions(getRoot) { + const $actions = tag("span", { className: "root-actions" }); + const buttons = [ + ["new file", "document-add", strings["new file"]], + ["new folder", "folder-add", strings["new folder"]], + ["refresh", "autorenew", strings.refresh], + ["collapse-all", "expand_less", strings["collapse all"] || "Collapse all"], + ["menu", "more_vert more-actions", strings.more], + ]; + + for (const [action, icon, title] of buttons) { + // tile children only receive clicks when they carry data-action. + const $button = tag("span", { className: `icon ${icon}`, title }); + $button.dataset.action = action; + $actions.append($button); + } + + $actions.addEventListener("click", (e) => { + const $button = e.target.closest("[data-action]"); + if (!$button) return; + e.preventDefault(); + e.stopPropagation(); + + const $root = getRoot(); + const { action } = $button.dataset; + if (action === "menu") { + const { url, name } = $root.$title.dataset; + handleContextmenu("root", url, name, $root.$title); + return; + } + + runRootAction($root, action, $button).catch(helpers.error); + }); + + return $actions; +} + +/** + * @param {Collapsible} $root + * @param {string} action + * @param {HTMLElement} [$button] + */ +async function runRootAction($root, action, $button) { + const { url, name } = $root.$title.dataset; + + switch (action) { + case "new file": + case "new folder": + if ($root.collapsed) $root.expand(); + return execOperation("root", action, url, $root.$title, name); + + case "refresh": { + if ($root.collapsed) { + $root.expand(); + return; + } + $button?.classList.add("spinning"); + try { + await getLoadedFileTree($root.$title)?.refresh(); + } finally { + $button?.classList.remove("spinning"); + } + return; + } + + case "collapse-all": { + // Deepest first, so each folder records its own collapsed state. + const $open = Array.from( + $root.$ul.querySelectorAll(".list.collapsible:not(.hidden)"), + ).reverse(); + for (const $list of $open) $list.collapse(); + return; + } + } +} + /** * Expand the list * @param {Collapsible} $list @@ -175,61 +354,57 @@ async function expandList($list) { if (!$ul) return; - $ul.textContent = null; + // Cleanup existing file tree, including one still loading: toggling while + // it loads would otherwise render both trees into the same list. + for (const tree of [$ul._fileTree, $ul._pendingFileTree]) tree?.destroy(); + $ul._fileTree = null; + $ul._pendingFileTree = null; + $ul.innerHTML = ""; + if (saveState) listState[url] = $list.unclasped; if (!$list.unclasped) return; + let fileTree; try { startLoading(); - const entries = await fsOperation(url).lsDir(); - helpers - .sortDir(entries, { - sortByName: true, - showHiddenFiles: true, - }) - .map((entry) => { - const name = entry.name || Path.basename(entry.url); - if (entry.isDirectory) { - const $list = createFolderTile(name, entry.url); - $ul.appendChild($list); - - if (listState[entry.url]) { - $list.expand(); - } - } else { - const $item = createFileTile(name, entry.url); - $ul.append($item); - } - }); + + fileTree = new FileTree($ul, { + getEntries: (dirUrl) => fsOperation(dirUrl).lsDir(), + expandedState: listState, + onExpandedChange: (folderUrl, isExpanded) => { + if (saveState) listState[folderUrl] = isExpanded; + }, + onFileClick: (fileUrl) => { + handleClick("file", fileUrl); + }, + onContextMenu: (type, itemUrl, name, $target) => { + handleContextmenu(type, itemUrl, name, $target); + }, + }); + + $ul._pendingFileTree = fileTree; + await fileTree.load(url); + // A later toggle replaced this tree while it loaded. + if ($ul._pendingFileTree !== fileTree) return; + $ul._pendingFileTree = null; + $ul._fileTree = fileTree; } catch (err) { + // A newer toggle owns the list now; don't collapse it. + if ($ul._pendingFileTree !== fileTree) return; + $ul._pendingFileTree = null; $list.collapse(); - if (err?.includes("Invalid message length")) { + if (err?.includes?.("Invalid message length")) { console.error(err); toast("SFTP connection broken. Restart the app"); return; } helpers.error(err); } finally { - stopLoading(); + // Leave the loading bar to a newer load that is still running. + if (!$ul._pendingFileTree) stopLoading(); } } -/** - * Gets weather the folder is collapsed or not - * @param {HTMLElement} $el - * @param {boolean} isFile - * @returns - */ -function collapsed($el, isFile) { - if (!$el.isConnected) return true; - $el = $el.parentElement; - if (!isFile) { - $el = $el.parentElement; - } - - return $el.previousElementSibling.collapsed; -} - /** * Handle click event * @param {Event} e @@ -259,31 +434,49 @@ function handleItems(e) { */ async function handleContextmenu(type, url, name, $target) { if (appSettings.value.vibrateOnTap) { - navigator.vibrate(constants.VIBRATION_TIME); + navigator.vibrate(config.VIBRATION_TIME); } - const { clipBoard, $node } = openFolder.find(url); - const cancel = `${strings.cancel}${clipBoard ? ` (${strings[clipBoard.action]})` : ""}`; + const { $node } = openFolder.find(url); + const hasClipboard = clipBoard.items.length > 0; + const cancel = `${strings.cancel}${hasClipboard ? ` (${strings[clipBoard.action]})` : ""}`; + const SELECT = ["select", strings.select, "check_circle_outline"]; const COPY = ["copy", strings.copy, "copy"]; const CUT = ["cut", strings.cut, "cut"]; + const COPY_RELATIVE_PATH = [ + "copy-relative-path", + strings["copy relative path"], + "attach_file", + ]; const REMOVE = ["delete", strings.delete, "delete"]; const RENAME = ["rename", strings.rename, "edit"]; - const PASTE = ["paste", strings.paste, "paste", !!clipBoard]; + const PASTE = ["paste", strings.paste, "paste", hasClipboard]; const NEW_FILE = ["new file", strings["new file"], "document-add"]; const NEW_FOLDER = ["new folder", strings["new folder"], "folder-add"]; const CANCEL = ["cancel", cancel, "clearclose"]; const OPEN_FOLDER = ["open-folder", strings["open folder"], "folder"]; const INSERT_FILE = ["insert-file", strings["insert file"], "file_copy"]; const CLOSE_FOLDER = ["close", strings["close"], "folder-remove"]; + const REFRESH = ["refresh", strings.refresh, "autorenew"]; + const COLLAPSE_ALL = [ + "collapse-all", + strings["collapse all"] || "Collapse all", + "expand_less", + ]; const INSTALL_PLUGIN = [ "install-plugin", strings["install as plugin"] || "Install as Plugin", "extension", ]; + const OPEN_SSH_TERMINAL = [ + "open-ssh-terminal", + strings["open ssh terminal"] || "Open SSH Terminal", + "terminal", + ]; let options; if (helpers.isFile(type)) { - options = [COPY, CUT, RENAME, REMOVE]; + options = [SELECT, COPY, CUT, COPY_RELATIVE_PATH, RENAME, REMOVE]; if ( url.toLowerCase().endsWith(".zip") && (await fsOperation( @@ -293,21 +486,45 @@ async function handleContextmenu(type, url, name, $target) { options.push(INSTALL_PLUGIN); } } else if (helpers.isDir(type)) { - options = [COPY, CUT, REMOVE, RENAME]; + options = [SELECT, COPY, CUT, COPY_RELATIVE_PATH, REMOVE, RENAME]; - if (clipBoard.url != null) { + if (hasClipboard) { options.push(PASTE); } options.push(NEW_FILE, NEW_FOLDER, OPEN_FOLDER, INSERT_FILE); + + if (isTerminalAccessiblePath(url)) { + const OPEN_IN_TERMINAL = [ + "open-in-terminal", + strings["open in terminal"] || "Open in Terminal", + "terminal", + ]; + options.push(OPEN_IN_TERMINAL); + } else if (/^sftp:/.test(url)) { + options.push(OPEN_SSH_TERMINAL); + } } else if (type === "root") { options = []; - if (clipBoard.url != null) { + if (hasClipboard) { options.push(PASTE); } - options.push(NEW_FILE, NEW_FOLDER, INSERT_FILE, CLOSE_FOLDER); + options.push(NEW_FILE, NEW_FOLDER, INSERT_FILE); + + if (isTerminalAccessiblePath(url)) { + const OPEN_IN_TERMINAL = [ + "open-in-terminal", + strings["open in terminal"] || "Open in Terminal", + "terminal", + ]; + options.push(OPEN_IN_TERMINAL); + } else if (/^sftp:/.test(url)) { + options.push(OPEN_SSH_TERMINAL); + } + + options.push(REFRESH, COLLAPSE_ALL, CLOSE_FOLDER); } if (clipBoard.action) options.push(CANCEL); @@ -325,17 +542,20 @@ async function handleContextmenu(type, url, name, $target) { /** * @param {"dir"|"file"|"root"} type - * @param {"copy"|"cut"|"delete"|"rename"|"paste"|"new file"|"new folder"|"cancel"|"open-folder"|"install-plugin"} action + * @param {"select"|"copy"|"cut"|"delete"|"rename"|"paste"|"new file"|"new folder"|"cancel"|"open-folder"|"install-plugin"|"open-in-terminal"|"open-ssh-terminal"|"copy-relative-path"} action * @param {string} url target url * @param {HTMLElement} $target target element * @param {string} name Name of file or folder */ function execOperation(type, action, url, $target, name) { - const { clipBoard, $node, remove } = openFolder.find(url); + const { $node, remove, url: rootUrl } = openFolder.find(url); const startLoading = () => $node.$title.classList.add("loading"); const stopLoading = () => $node.$title.classList.remove("loading"); switch (action) { + case "select": + return fileSelection.start($target); + case "copy": case "cut": return clipBoardAction(); @@ -367,6 +587,19 @@ function execOperation(type, action, url, $target, name) { case "install-plugin": return installPlugin(); + + case "open-in-terminal": + return openInTerminal(); + + case "open-ssh-terminal": + return openSshTerminal(); + + case "refresh": + case "collapse-all": + return runRootAction($node, action); + + case "copy-relative-path": + return copyRelativePath(); } async function installPlugin() { @@ -385,68 +618,104 @@ function execOperation(type, action, url, $target, name) { } } - async function deleteFile() { - const msg = strings["delete entry"].replace("{name}", name); - const confirmation = await confirm(strings.warning, msg); - if (!confirmation) return; - startLoading(); - if (!(await fsOperation(url).exists())) return; - // await fsOperation(url).delete(); - recents.removeFile(url); - if (helpers.isFile(type)) { - await fsOperation(url).delete(); - $target.remove(); - const file = editorManager.getFile(url, "uri"); - if (file) file.uri = null; - editorManager.onupdate("delete-file"); - editorManager.emit("update", "delete-file"); - } else { - if (url.startsWith("content://com.termux.documents/tree/")) { - const fs = fsOperation(url); - const entries = await fs.lsDir(); - if (entries.length === 0) { - await fs.delete(); - } else { - const deleteRecursively = async (currentUrl) => { - const currentFs = fsOperation(currentUrl); - const currentEntries = await currentFs.lsDir(); - for (const entry of currentEntries) { - if (entry.isDirectory) { - await deleteRecursively(entry.url); + async function copyRelativePath() { + try { + // Validate inputs + if (!url) { + console.error("File path not available"); + return; + } + + if (!rootUrl) { + console.error("Root folder not found"); + return; + } + + const relativePath = getRelativePath(url, rootUrl); + + if (!relativePath) { + console.error("Unable to calculate relative path"); + return; + } + + copyText(relativePath); + } catch (error) { + console.error("Failed to copy relative path:", error); + } + } + + async function openInTerminal() { + try { + const { TerminalManager } = await import( + /* webpackChunkName: "terminal" */ "components/terminal" + ); + const prootPath = convertToProotPath(url); + const terminal = await TerminalManager.createTerminal({ + name: `Terminal - ${name}`, + render: true, + }); + if (terminal?.component) { + const waitForConnection = (timeoutMs = 5000) => + new Promise((resolve, reject) => { + const startTime = Date.now(); + const check = () => { + if (terminal.component.isConnected) { + resolve(); + } else if (Date.now() - startTime > timeoutMs) { + reject(new Error("Terminal connection timeout")); } else { - await fsOperation(entry.url).delete(); + setTimeout(check, 50); } - } - await currentFs.delete(); - }; - await deleteRecursively(url); - } - } else { - await fsOperation(url).delete(); + }; + check(); + }); + await waitForConnection(); + terminal.component.write(`cd ${JSON.stringify(prootPath)}\n`); + Sidebar.hide(); } - recents.removeFolder(url); - helpers.updateUriOfAllActiveFiles(url, null); - $target.parentElement.remove(); - editorManager.onupdate("delete-folder"); - editorManager.emit("update", "delete-folder"); + } catch (error) { + console.error("Failed to open terminal:", error); + const errorMsg = error.message || "Unknown error occurred"; + toast(`Failed to open terminal: ${errorMsg}`); } + } + async function openSshTerminal() { + try { + const { TerminalManager } = await import( + /* webpackChunkName: "terminal" */ "components/terminal" + ); + await TerminalManager.createRemoteTerminal({ url, name }); + Sidebar.hide(); + } catch (error) { + console.error("Failed to open SSH terminal:", error); + toast(`Failed to open SSH terminal: ${error.message || "Unknown error"}`); + } + } + + async function deleteFile() { + const msg = strings["delete entry"].replace("{name}", name); + const confirmation = await confirm(strings.warning, msg); + if (!confirmation) return; + startLoading(); + if (!(await deleteEntry(url, type))) return; toast(strings.success); - FileList.remove(url); } async function renameFile() { - if ( - url.startsWith("content://com.termux.documents/tree/") && - !helpers.isFile(type) - ) { + if (isTermuxSafUri(url) && !helpers.isFile(type)) { alert(strings.warning, strings["rename not supported"]); return; } - let newName = await prompt(strings.rename, name, "text", { - match: constants.FILE_NAME_REGEX, - required: true, - }); + let newName = await prompt( + strings.rename, + name, + helpers.isFile(type) ? "filename" : "text", + { + match: config.FILE_NAME_REGEX, + required: true, + }, + ); newName = helpers.fixFilename(newName); if (!newName || newName === name) return; @@ -455,11 +724,8 @@ function execOperation(type, action, url, $target, name) { const fs = fsOperation(url); let newUrl; - if ( - url.startsWith("content://com.termux.documents/tree/") && - helpers.isFile(type) - ) { - // Special handling for Termux content files + if (isTermuxSafUri(url) && helpers.isFile(type)) { + // Special handling for Termux SAF content files const newFilePath = Url.join(Url.dirname(url), newName); const content = await fs.readFile(); await fsOperation(Url.dirname(url)).createFile(newName, content); @@ -470,12 +736,7 @@ function execOperation(type, action, url, $target, name) { } newName = Url.basename(newUrl); - $target.querySelector(":scope>.text").textContent = newName; - $target.dataset.url = newUrl; - $target.dataset.name = newName; if (helpers.isFile(type)) { - $target.querySelector(":scope>span").className = - helpers.getIconForFile(newName); let file = editorManager.getFile(url, "uri"); if (file) { file.uri = newUrl; @@ -483,12 +744,10 @@ function execOperation(type, action, url, $target, name) { } } else { helpers.updateUriOfAllActiveFiles(url, newUrl); - //Reloading the folder by collapsing and expanding the folder - $target.click(); //collapse - $target.click(); //expand } - toast(strings.success); FileList.rename(url, newUrl); + await refreshRenamedEntryInOpenFolders(url, newUrl); + toast(strings.success); } async function createNew() { @@ -498,219 +757,65 @@ function execOperation(type, action, url, $target, name) { : strings["enter folder name"]; let newName = await prompt(msg, "", "text", { - match: constants.FILE_NAME_REGEX, + match: config.FILE_NAME_REGEX, required: true, }); newName = helpers.fixFilename(newName); if (!newName) return; startLoading(); - let newUrl; + try { + const isNestedPath = newName.split("/").filter(Boolean).length > 1; + let newUrl; - if (action === "new file") { - newUrl = await helpers.createFileStructure(url, newName); - } else { - newUrl = await helpers.createFileStructure(url, newName, false); - } - if (!newUrl) return; - newName = Url.basename(newUrl.uri); - if ($target.unclasped) { - if (newUrl.type === "file") { - appendTile($target, createFileTile(newName, newUrl.uri)); - } else if (newUrl.type === "folder") { - appendList($target, createFolderTile(newName, newUrl.uri)); + if (action === "new file") { + newUrl = await helpers.createFileStructure(url, newName); + } else { + newUrl = await helpers.createFileStructure(url, newName, false); } - } + if (!newUrl.created) return; - FileList.append(url, newUrl.uri); - toast(strings.success); + if (isNestedPath) { + await refreshOpenFolder(url); + FileList.append(newUrl.parentUri, newUrl.uri); + toast(strings.success); + return; + } + + newName = Url.basename(newUrl.uri); + appendEntryToOpenFolder(url, newUrl.uri, newUrl.type); + + FileList.append(url, newUrl.uri); + toast(strings.success); + } catch (error) { + helpers.error(error); + } finally { + stopLoading(); + } } async function paste() { - if (clipBoard.url == null) { + if (!clipBoard.items.length) { alert(strings.warning, "Nothing to paste"); return; } - // Prevent pasting a folder into itself or its subdirectories - if (helpers.isDir(clipBoard.$el.dataset.type)) { - const sourceUrl = Url.parse(clipBoard.url).url; - const targetUrl = Url.parse(url).url; - - // Check if trying to paste folder into itself - if (sourceUrl === targetUrl) { - alert(strings.warning, "Cannot paste a folder into itself"); - return; - } - - // Check if trying to paste folder into one of its subdirectories - if ( - targetUrl.startsWith(sourceUrl + "/") || - targetUrl.startsWith(sourceUrl + "\\") - ) { - alert(strings.warning, "Cannot paste a folder into its subdirectory"); - return; - } - } - - let CASE = ""; - const $src = clipBoard.$el; - const srcType = $src.dataset.type; - const IS_FILE = helpers.isFile(srcType); - const IS_DIR = helpers.isDir(srcType); - const srcCollapsed = collapsed($src, IS_FILE); - - CASE += IS_FILE ? 1 : 0; - CASE += srcCollapsed ? 1 : 0; - CASE += $target.collapsed ? 1 : 0; + const { action: pasteAction, items } = clipBoard; startLoading(); try { - const fs = fsOperation(clipBoard.url); - const itemName = Url.basename(clipBoard.url); - const possibleConflictUrl = Url.join(url, itemName); - const doesExist = await fsOperation(possibleConflictUrl).exists(); - if (doesExist) { - let confirmation = await confirm( - strings.warning, - strings["already exists"] - ? strings["already exists"].replace("{name}", itemName) - : `"${itemName}" already exists in this location.`, - ); - if (!confirmation) return; - } - let newUrl; - if (clipBoard.action === "cut") { - // Special handling for Termux SAF folders - move manually due to SAF limitations - if ( - clipBoard.url.startsWith("content://com.termux.documents/tree/") && - IS_DIR - ) { - const moveRecursively = async (sourceUrl, targetParentUrl) => { - const sourceFs = fsOperation(sourceUrl); - const sourceName = Url.basename(sourceUrl); - const targetUrl = Url.join(targetParentUrl, sourceName); - - // Create target folder - await fsOperation(targetParentUrl).createDirectory(sourceName); - - // Get all entries in source folder - const entries = await sourceFs.lsDir(); - - // Move all files and folders recursively - for (const entry of entries) { - if (entry.isDirectory) { - await moveRecursively(entry.url, targetUrl); - } else { - const fileContent = await fsOperation(entry.url).readFile(); - const fileName = entry.name || Url.basename(entry.url); - await fsOperation(targetUrl).createFile(fileName, fileContent); - await fsOperation(entry.url).delete(); - } - } - - // Delete the now-empty source folder - await sourceFs.delete(); - return targetUrl; - }; - - newUrl = await moveRecursively(clipBoard.url, url); - } else { - newUrl = await fs.moveTo(url); - } - } else { - newUrl = await fs.copyTo(url); - } - const { name: newName } = await fsOperation(newUrl).stat(); - stopLoading(); - /** - * CASES: - * CASE 111: src is file and parent is collapsed where target is also collapsed - * CASE 110: src is file and parent is collapsed where target is unclasped - * CASE 101: src is file and parent is unclasped where target is collapsed - * CASE 100: src is file and parent is unclasped where target is also unclasped - * CASE 011: src is directory and parent is collapsed where target is also collapsed - * CASE 001: src is directory and parent is unclasped where target is also collapsed - * CASE 010: src is directory and parent is collapsed where target is also unclasped - * CASE 000: src is directory and parent is unclasped where target is also unclasped - */ - - if (clipBoard.action === "cut") { - //move - - if (IS_FILE) { - const file = editorManager.getFile(clipBoard.url, "uri"); - if (file) file.uri = newUrl; - } else if (IS_DIR) { - helpers.updateUriOfAllActiveFiles(clipBoard.url, newUrl); - } - - switch (CASE) { - case "111": - case "011": - break; - - case "110": - appendTile($target, createFileTile(newName, newUrl)); - break; - - case "101": - $src.remove(); - break; - - case "100": - appendTile($target, createFileTile(newName, newUrl)); - $src.remove(); - break; - - case "001": - $src.parentElement.remove(); - break; - - case "010": - appendList($target, createFolderTile(newName, newUrl)); - break; - - case "000": - appendList($target, createFolderTile(newName, newUrl)); - $src.parentElement.remove(); - break; + const { pasted, remaining, error } = await pasteEntries( + items, + url, + pasteAction, + ); - default: - break; - } - FileList.remove(clipBoard.url); - } else { - //copy - - switch (CASE) { - case "111": - case "101": - case "011": - case "001": - break; - - case "110": - case "100": - appendTile($target, createFileTile(newName, newUrl)); - break; - - case "010": - case "000": - appendList($target, createFolderTile(newName, newUrl)); - break; - - default: - break; - } - } + // Keep skipped or failed entries so the paste can be retried. + if (remaining.length) setClipboard(remaining, pasteAction); + else clearClipboard(); - FileList.append(url, newUrl); - toast(strings.success); - clearClipboard(); - } catch (error) { - console.error(error); - helpers.error(error); + if (error) helpers.error(error); + else if (pasted) toast(strings.success); } finally { stopLoading(); } @@ -719,6 +824,7 @@ function execOperation(type, action, url, $target, name) { async function insertFile() { startLoading(); try { + const FileBrowser = await loadFileBrowser(); const file = await FileBrowser("file", strings["insert file"]); const sourceFs = fsOperation(file.url); const data = await sourceFs.readFile(); @@ -736,15 +842,11 @@ function execOperation(type, action, url, $target, name) { } async function clipBoardAction() { - clipBoard.url = url; - clipBoard.action = action; - clipBoard.$el = $target; - - if (action === "cut") $target.classList.add("cut"); - else $target.classList.remove("cut"); + setClipboard([{ url, type }], action); } async function open() { + const FileBrowser = await loadFileBrowser(); FileBrowser.openFolder({ url, name, @@ -752,17 +854,466 @@ function execOperation(type, action, url, $target, name) { } function cancelAction() { - clipBoard.$el.classList.remove("cut"); clearClipboard(); } +} + +/** + * Delete a file or folder and update every view that references it. + * @param {string} url + * @param {"file"|"dir"} type + * @returns {Promise} false when the entry no longer exists + */ +async function deleteEntry(url, type) { + if (!(await fsOperation(url).exists())) return false; + recents.removeFile(url); + await deleteFromDisk(url, type); + if (helpers.isFile(type)) { + removeEntryFromOpenFolder(url); + const file = editorManager.getFile(url, "uri"); + if (file) file.uri = null; + editorManager.onupdate("delete-file"); + editorManager.emit("update", "delete-file"); + } else { + recents.removeFolder(url); + helpers.updateUriOfAllActiveFiles(url, null); + removeEntryFromOpenFolder(url); + editorManager.onupdate("delete-folder"); + editorManager.emit("update", "delete-folder"); + } + + FileList.remove(url); + return true; +} + +/** + * Remove a file or folder from its file system without touching any views. + * @param {string} url + * @param {"file"|"dir"} type + */ +async function deleteFromDisk(url, type) { + if (!helpers.isDir(type) || !isTerminalSafUri(url)) { + await fsOperation(url).delete(); + return; + } + + // Terminal SAF providers can't delete non-empty folders. + const deleteRecursively = async (currentUrl) => { + const currentFs = fsOperation(currentUrl); + const currentEntries = await currentFs.lsDir(); + for (const entry of currentEntries) { + if (entry.isDirectory) { + await deleteRecursively(entry.url); + } else { + await fsOperation(entry.url).delete(); + } + } + await currentFs.delete(); + }; + await deleteRecursively(url); +} + +/** + * Paste entries one by one so a failure doesn't stop the rest. + * @param {ClipBoardItem[]} items + * @param {string} targetUrl + * @param {"cut"|"copy"} action + * @returns {Promise<{pasted: number, remaining: ClipBoardItem[], error?: Error}>} + * `remaining` holds the entries that were skipped or failed. + */ +async function pasteEntries(items, targetUrl, action) { + const remaining = []; + let pasted = 0; + let error; + + for (const item of items) { + try { + if (await pasteEntry(item, targetUrl, action)) { + pasted++; + continue; + } + } catch (err) { + console.error(err); + error = err; + } + remaining.push(item); + } + + return { pasted, remaining, error }; +} + +/** + * Identify the connection a url belongs to. Providers can only move or copy + * within their own connection (e.g. one SFTP server or one SAF tree). + * @param {string} url + * @returns {string} + */ +function getConnectionKey(url) { + const { url: parsedUrl } = Url.parse(url); + const protocol = Url.getProtocol(parsedUrl); + + if (!protocol || protocol === "file:") return "file:"; + + if (protocol === "content:") { + try { + return `content:${Uri.parse(parsedUrl).rootUri}`; + } catch (error) { + return parsedUrl; + } + } + + const { username, hostname, port } = Url.decodeUrl(parsedUrl); + return `${protocol}//${username || ""}@${hostname}:${port || ""}`; +} + +/** + * Paste a clipboard entry into a folder. + * @param {ClipBoardItem} item + * @param {string} targetUrl + * @param {"cut"|"copy"} action + * @returns {Promise} New url, or null when skipped + */ +async function pasteEntry({ url: srcUrl, type: srcType }, targetUrl, action) { + const IS_FILE = helpers.isFile(srcType); + const IS_DIR = helpers.isDir(srcType); + + // Prevent pasting a folder into itself or its subdirectories + if (IS_DIR) { + const sourcePath = Url.parse(srcUrl).url; + const targetPath = Url.parse(targetUrl).url; + + if (sourcePath === targetPath) { + alert(strings.warning, "Cannot paste a folder into itself"); + return null; + } + + if ( + targetPath.startsWith(sourcePath + "/") || + targetPath.startsWith(sourcePath + "\\") + ) { + alert(strings.warning, "Cannot paste a folder into its subdirectory"); + return null; + } + } + + const fs = fsOperation(srcUrl); + const itemName = Url.basename(srcUrl); + const possibleConflictUrl = Url.join(targetUrl, itemName); + const doesExist = await fsOperation(possibleConflictUrl).exists(); + if (doesExist) { + const confirmation = await confirm( + strings.warning, + strings["already exists"] + ? strings["already exists"].replace("{name}", itemName) + : `"${itemName}" already exists in this location.`, + ); + if (!confirmation) return null; + } + + const excludePatterns = + action === "copy" && appSettings.value.useFileOperationExclusions + ? appSettings.value.excludeFolders + : null; + + let newUrl; + if (getConnectionKey(srcUrl) !== getConnectionKey(targetUrl)) { + // Different servers or storage: read from the source and write to the + // target, since the source provider can't reach the target. + // Check exclusions first so a skipped entry never replaces anything. + if ( + excludePatterns && + isExcludedFileOperationPath(srcUrl, excludePatterns) + ) { + toast(strings.skipped); + return null; + } + + if (doesExist && IS_FILE) { + // copyEntry only creates new files, so overwrite the confirmed one. + await fsOperation(possibleConflictUrl).writeFile(await fs.readFile()); + newUrl = possibleConflictUrl; + } else { + if (doesExist) { + // The user confirmed replacing what's there. + const { isDirectory } = await fsOperation(possibleConflictUrl).stat(); + await deleteFromDisk(possibleConflictUrl, isDirectory ? "dir" : "file"); + } + const result = await copyEntry(srcUrl, targetUrl, { + excludePatterns: excludePatterns || [], + }); + newUrl = result.url; + } + if (newUrl && action === "cut") await deleteFromDisk(srcUrl, srcType); + } else if (action === "cut") { + // Special handling for SAF folders backed by terminal providers - move manually due to SAF limitations + if (isTerminalSafUri(srcUrl) && IS_DIR) { + const moveRecursively = async (sourceUrl, targetParentUrl) => { + const sourceFs = fsOperation(sourceUrl); + const sourceName = Url.basename(sourceUrl); + const targetUrl = Url.join(targetParentUrl, sourceName); + + // Create target folder + await fsOperation(targetParentUrl).createDirectory(sourceName); + + // Get all entries in source folder + const entries = await sourceFs.lsDir(); + + // Move all files and folders recursively + for (const entry of entries) { + if (entry.isDirectory) { + await moveRecursively(entry.url, targetUrl); + } else { + const fileContent = await fsOperation(entry.url).readFile(); + const fileName = entry.name || Url.basename(entry.url); + await fsOperation(targetUrl).createFile(fileName, fileContent); + await fsOperation(entry.url).delete(); + } + } + + // Delete the now-empty source folder + await sourceFs.delete(); + return targetUrl; + }; + + newUrl = await moveRecursively(srcUrl, targetUrl); + } else { + newUrl = await fs.moveTo(targetUrl); + } + } else if (excludePatterns) { + const result = await copyEntry(srcUrl, targetUrl, { excludePatterns }); + newUrl = result.url; + } else { + newUrl = await fs.copyTo(targetUrl); + } + + if (!newUrl) { + toast(strings.skipped); + return null; + } + + if (action === "cut") { + if (IS_FILE) { + const file = editorManager.getFile(srcUrl, "uri"); + if (file) file.uri = newUrl; + } else if (IS_DIR) { + helpers.updateUriOfAllActiveFiles(srcUrl, newUrl); + migrateOpenFolderStateUrls(srcUrl, newUrl); + } + removeEntryFromOpenFolder(srcUrl); + FileList.rename(srcUrl, newUrl); + } else { + FileList.append(targetUrl, newUrl); + } + + appendEntryToOpenFolder(targetUrl, newUrl, IS_DIR ? "folder" : "file"); + return newUrl; +} + +/** + * Get the elements currently rendered for an entry. + * @param {string} url + * @returns {HTMLElement[]} + */ +function getRenderedEntries(url) { + const filesApp = sidebarApps.get("files"); + return Array.from(filesApp.getAll(`[data-url="${CSS.escape(url)}"]`)); +} + +/** + * @param {ClipBoardItem[]} items + * @param {"cut"|"copy"} action + */ +function setClipboard(items, action) { + clearClipboard(); + clipBoard.items = items.map(({ url, type }) => ({ url, type })); + clipBoard.action = action; + + if (action !== "cut") return; + for (const { url } of clipBoard.items) { + for (const $el of getRenderedEntries(url)) $el.classList.add("cut"); + } +} - function clearClipboard() { - clipBoard.$el = null; - clipBoard.url = null; - clipBoard.action = null; +function clearClipboard() { + for (const { url } of clipBoard.items) { + for (const $el of getRenderedEntries(url)) $el.classList.remove("cut"); } + clipBoard.items = []; + clipBoard.action = null; } +/** + * Get the path of an entry relative to its open folder. + * @param {string} url + * @param {string} rootUrl + * @returns {string} + */ +function getRelativePath(url, rootUrl) { + // Try using Url.pathname for protocol-based URLs + const rootPath = Url.pathname(rootUrl); + const targetPath = Url.pathname(url); + + if (rootPath && targetPath) { + // Both pathnames extracted successfully + return Path.convertToRelative(rootPath, targetPath); + } + + // Fallback: Use simple string comparison for URIs where pathname extraction fails + const cleanRoot = rootUrl.endsWith("/") ? rootUrl.slice(0, -1) : rootUrl; + const cleanTarget = url.endsWith("/") ? url.slice(0, -1) : url; + + // Check if target URL starts with root URL + if (cleanTarget.startsWith(cleanRoot)) { + return cleanTarget.slice(cleanRoot.length + 1); + } + + // If not a child path, just use basename + return Url.basename(url); +} + +/** + * @param {string} text + * @returns {boolean} Whether the text was copied + */ +function copyText(text) { + if (cordova.plugins.clipboard) { + cordova.plugins.clipboard.copy(text); + return true; + } + + console.error("Clipboard not available"); + toast("Clipboard not available"); + return false; +} + +/** + * Drop entries that are already covered by a selected parent folder. + * @template {ClipBoardItem} T + * @param {T[]} items + * @returns {T[]} + */ +function removeNestedItems(items) { + return items.filter( + (item) => + !items.some( + (other) => + other !== item && + helpers.isDir(other.type) && + !areSameOpenFolderUrl(other.url, item.url) && + isInsideOpenFolder(item.url, other.url), + ), + ); +} + +/** + * Run an action from the file selection bar. + * @param {import("sidebarApps/files/selection").SelectionAction} action + * @param {import("sidebarApps/files/selection").SelectedEntry[]} items + * @param {string} [targetUrl] Destination folder for "move" + * @returns {Promise} false keeps the selection open + */ +async function handleSelectionAction(action, items, targetUrl) { + // Entries inside a selected folder are handled with the folder, but open + // and copy path still act on everything that was picked. + if (["copy", "cut", "delete", "move"].includes(action)) { + items = removeNestedItems(items); + } + + switch (action) { + case "copy": + case "cut": + setClipboard(items, action); + return; + + case "delete": + return deleteEntries(items); + + case "move": + return moveEntries(items, targetUrl); + + case "copy-path": { + const paths = items.map(({ url }) => + getRelativePath(url, openFolder.find(url)?.url || url), + ); + if (copyText(paths.join("\n"))) toast(strings["copied to clipboard"]); + return; + } + + case "rename": { + const [{ type, url, $el, name }] = items; + return execOperation(type, "rename", url, $el, name); + } + + case "open": { + const files = items.filter(({ type }) => helpers.isFile(type)); + for (const [index, { url }] of files.entries()) { + await openFile(url, { render: index === files.length - 1 }); + } + Sidebar.hide(); + return; + } + } +} + +/** + * @param {ClipBoardItem[]} items + * @returns {Promise} false when cancelled + */ +async function deleteEntries(items) { + const msg = strings["delete entries"].replace("{count}", items.length); + const confirmation = await confirm(strings.warning, msg); + if (!confirmation) return false; + + const $titles = new Set( + items.map(({ url }) => openFolder.find(url)?.$node.$title).filter(Boolean), + ); + for (const $title of $titles) $title.classList.add("loading"); + + let failed = 0; + let lastError; + try { + for (const { url, type } of items) { + try { + await deleteEntry(url, type); + } catch (error) { + console.error(error); + failed++; + lastError = error; + } + } + } finally { + for (const $title of $titles) $title.classList.remove("loading"); + } + + if (failed) helpers.error(lastError); + else toast(strings.success); + return true; +} + +/** + * Move entries into a folder, skipping those already there. + * @param {ClipBoardItem[]} items + * @param {string} targetUrl + */ +async function moveEntries(items, targetUrl) { + const movable = items.filter( + ({ url }) => !areSameOpenFolderUrl(getParentUrl(url), targetUrl), + ); + if (!movable.length) return; + + const $title = openFolder.find(targetUrl)?.$node.$title; + $title?.classList.add("loading"); + try { + const { pasted, error } = await pasteEntries(movable, targetUrl, "cut"); + if (error) helpers.error(error); + else if (pasted) toast(strings.success); + } finally { + $title?.classList.remove("loading"); + } +} + +fileSelection.onAction(handleSelectionAction); + /** * * @param {"file"|"dir"|"root"} type @@ -798,6 +1349,228 @@ function appendList($target, $list) { else $target.append($list); } +/** + * Get the active file tree for a folder element, if it has been loaded. + * @param {HTMLElement} $el + * @returns {FileTree|null} + */ +function getLoadedFileTree($el) { + return ( + $el?.$ul?._fileTree || $el?.fileTree || $el?.nextElementSibling?._fileTree + ); +} + +function normalizeUrlPathKey(url) { + if (!url) return url; + const { url: parsedUrl } = Url.parse(url); + + if (Url.getProtocol(parsedUrl) === "content:") { + try { + const { rootUri, docId } = Uri.parse(parsedUrl); + const normalizedDocId = docId.endsWith("/") ? docId.slice(0, -1) : docId; + return `${rootUri}::${normalizedDocId}`; + } catch (error) { + return parsedUrl; + } + } + + if (parsedUrl.endsWith("/") && Url.pathname(parsedUrl) !== "/") { + return parsedUrl.slice(0, -1); + } + + return parsedUrl; +} + +function areSameOpenFolderUrl(leftUrl, rightUrl) { + return normalizeUrlPathKey(leftUrl) === normalizeUrlPathKey(rightUrl); +} + +function isInsideOpenFolder(url, folderUrl) { + const urlKey = normalizeUrlPathKey(url); + const folderKey = normalizeUrlPathKey(folderUrl); + if (!urlKey || !folderKey) return false; + + return urlKey === folderKey || urlKey.startsWith(`${folderKey}/`); +} + +function appendUrlPathSuffix(url, suffix) { + if (!suffix) return url; + const { url: parsedUrl, query } = Url.parse(url); + if (parsedUrl.endsWith("/") && suffix.startsWith("/")) { + return parsedUrl.slice(0, -1) + suffix + query; + } + return parsedUrl + suffix + query; +} + +function preserveTrailingSlashShape(url, sourceUrl) { + const { url: sourcePath } = Url.parse(sourceUrl); + if (!sourcePath.endsWith("/")) return url; + + const { url: targetPath, query } = Url.parse(url); + if (targetPath.endsWith("/")) return url; + + return `${targetPath}/${query}`; +} + +function getListStateEntries(listState) { + if (!listState) return []; + if (listState instanceof Map) return Array.from(listState.entries()); + return Object.entries(listState); +} + +function setListStateEntry(listState, key, value) { + if (listState instanceof Map) { + listState.set(key, value); + return; + } + + listState[key] = value; +} + +function deleteListStateEntry(listState, key) { + if (listState instanceof Map) { + listState.delete(key); + return; + } + + delete listState[key]; +} + +/** + * Move saved expanded-state keys after a folder rename. + * @param {string} oldUrl + * @param {string} newUrl + */ +function migrateOpenFolderStateUrls(oldUrl, newUrl) { + if (!oldUrl || !newUrl || areSameOpenFolderUrl(oldUrl, newUrl)) return; + + const oldKey = normalizeUrlPathKey(oldUrl); + + addedFolder.forEach(({ listState }) => { + const matchingEntries = getListStateEntries(listState).filter( + ([folderUrl]) => { + return isInsideOpenFolder(folderUrl, oldUrl); + }, + ); + + matchingEntries.forEach(([folderUrl, isExpanded]) => { + const suffix = normalizeUrlPathKey(folderUrl).slice(oldKey.length); + const migratedUrl = preserveTrailingSlashShape( + appendUrlPathSuffix(newUrl, suffix), + folderUrl, + ); + deleteListStateEntry(listState, folderUrl); + setListStateEntry(listState, migratedUrl, isExpanded); + }); + }); +} + +function getParentUrl(url) { + return Url.dirname(url); +} + +/** + * Remove matching rendered entries from expanded folder views. + * This keeps FileTree's in-memory state aligned with the rendered tree. + * @param {string} entryUrl + */ +function removeEntryFromOpenFolder(entryUrl) { + const filesApp = sidebarApps.get("files"); + const $els = Array.from( + filesApp.getAll(`[data-url="${CSS.escape(entryUrl)}"]`), + ); + + $els.forEach(($el) => { + const ownerTree = + $el?.parentElement?._fileTree || + $el?.parentElement?.parentElement?._fileTree; + + if (ownerTree) { + ownerTree.removeEntry(entryUrl); + return; + } + + const type = $el.dataset.type; + if (helpers.isFile(type)) { + $el.remove(); + } else { + $el.parentElement?.remove(); + } + }); +} + +/** + * Update matching expanded folder views with a new entry. + * @param {string} parentUrl + * @param {string} entryUrl + * @param {"file"|"folder"} type + */ +function appendEntryToOpenFolder(parentUrl, entryUrl, type) { + const filesApp = sidebarApps.get("files"); + const $els = filesApp.getAll(`[data-url="${parentUrl}"]`); + const isDirectory = type === "folder"; + const name = Url.basename(entryUrl); + + Array.from($els).forEach(($el) => { + if (!(helpers.isDir($el.dataset.type) || $el.dataset.type === "root")) { + return; + } + + if (!$el.unclasped) return; + + const fileTree = getLoadedFileTree($el); + if (fileTree) { + fileTree.appendEntry(name, entryUrl, isDirectory); + return; + } + + if (isDirectory) { + appendList($el, createFolderTile(name, entryUrl)); + } else { + appendTile($el, createFileTile(name, entryUrl)); + } + }); +} + +/** + * Refresh matching expanded folder views. + * @param {string} folderUrl + */ +async function refreshOpenFolder(folderUrl) { + const folder = openFolder.find(folderUrl); + if (!folder) return; + + const fileTree = getLoadedFileTree(folder.$node.$title); + if (!fileTree) return; + + await fileTree.refreshFolder(folderUrl, areSameOpenFolderUrl); +} + +/** + * Refresh affected folder trees after a rename/move. + * @param {string} oldUrl + * @param {string} newUrl + */ +async function refreshRenamedEntryInOpenFolders( + oldUrl, + newUrl, + oldParentUrl = getParentUrl(oldUrl), + newParentUrl = getParentUrl(newUrl), +) { + if (!oldUrl || !newUrl || areSameOpenFolderUrl(oldUrl, newUrl)) return; + + migrateOpenFolderStateUrls(oldUrl, newUrl); + + const parentUrls = [oldParentUrl, newParentUrl].filter(Boolean); + const refreshUrls = parentUrls.filter((parentUrl, index) => { + return !parentUrls.some((otherUrl, otherIndex) => { + return otherIndex < index && areSameOpenFolderUrl(otherUrl, parentUrl); + }); + }); + + await Promise.all(refreshUrls.map(refreshOpenFolder)); +} + /** * Create a folder tile * @param {string} name @@ -806,16 +1579,38 @@ function appendList($target, $list) { */ function createFolderTile(name, url) { const $list = collapsableList(name, "folder", { - ontoggle: () => expandList($list), + ontoggle: () => { + setFolderLeadIcon($list, name); + expandList($list); + }, }); const { $title } = $list; $title.dataset.url = url; $title.dataset.name = name; $title.dataset.type = "dir"; + setFolderLeadIcon($list, name); return $list; } +function setFolderLeadIcon($list, name, options = {}) { + const $icon = $list.$title?.firstElementChild; + if (!$icon) return; + $icon.className = helpers.getIconForFolder(name, { + expanded: $list.unclasped, + isRoot: options.isRoot, + }); +} + +fileIcons.onChange(() => { + for (const folder of addedFolder) { + const $list = folder.$node; + const name = $list?.$title?.dataset?.name; + if (!$list || !name) continue; + setFolderLeadIcon($list, name, { isRoot: true }); + } +}); + /** * Create a file tile * @param {string} name @@ -824,7 +1619,7 @@ function createFolderTile(name, url) { */ function createFileTile(name, url) { const $tile = tile({ - lead: , + lead: tag("span", { className: helpers.getIconForFile(name) }), text: name, }); $tile.dataset.url = url; @@ -842,43 +1637,14 @@ function createFileTile(name, url) { openFolder.add = async (url, type) => { const { url: parent } = await fsOperation(Url.dirname(url)).stat(); FileList.append(parent, url); - - const filesApp = sidebarApps.get("files"); - const $els = filesApp.getAll(`[data-url="${parent}"]`); - Array.from($els).forEach(($el) => { - if ($el.dataset.type !== "dir") return; - - if (type === "file") { - appendTile($el, createFileTile(Url.basename(url), url)); - } else { - appendList($el, createFolderTile(Url.basename(url), url)); - } - }); + appendEntryToOpenFolder(parent, url, type); }; -openFolder.renameItem = (oldFile, newFile, newFilename) => { +openFolder.renameItem = (oldFile, newFile) => { FileList.rename(oldFile, newFile); helpers.updateUriOfAllActiveFiles(oldFile, newFile); - - const filesApp = sidebarApps.get("files"); - const $els = filesApp.getAll(`[data-url="${oldFile}"]`); - Array.from($els).forEach(($el) => { - if ($el.dataset.type === "dir") { - $el = $el.$title; - setTimeout(() => { - $el.collapse(); - $el.expand(); - }, 0); - } else { - $el.querySelector(":scope>span").className = - helpers.getIconForFile(newFilename); - } - - $el.dataset.url = newFile; - $el.dataset.name = newFilename; - $el.querySelector(":scope>.text").textContent = newFilename; - }); + refreshRenamedEntryInOpenFolders(oldFile, newFile).catch(helpers.error); }; openFolder.removeItem = (url) => { @@ -890,23 +1656,15 @@ openFolder.removeItem = (url) => { return; } - const filesApp = sidebarApps.get("files"); - const $el = filesApp.getAll(`[data-url="${url}"]`); - Array.from($el).forEach(($el) => { - const type = $el.dataset.type; - if (helpers.isFile(type)) { - $el.remove(); - } else { - $el.parentElement.remove(); - } - }); + removeEntryFromOpenFolder(url); }; openFolder.removeFolders = (url) => { ({ url } = Url.parse(url)); - const regex = new RegExp("^" + escapeStringRegexp(url)); - addedFolder.forEach((folder) => { - if (regex.test(folder.url)) { + // remove() mutates addedFolder, so iterate over a snapshot to avoid skipping + // adjacent folders that belong to the same remote storage. + [...addedFolder].forEach((folder) => { + if (Url.isSameOrDescendant(folder.url, url)) { folder.remove(); } }); @@ -918,13 +1676,11 @@ openFolder.removeFolders = (url) => { * @returns {Folder} */ openFolder.find = (url) => { - const found = addedFolder.find((folder) => folder.url === url); + const found = addedFolder.find((folder) => + areSameOpenFolderUrl(folder.url, url), + ); if (found) return found; - return addedFolder.find((folder) => { - const { url: furl } = Url.parse(folder.url); - const regex = new RegExp("^" + escapeStringRegexp(furl)); - return regex.test(url); - }); + return addedFolder.find((folder) => isInsideOpenFolder(url, folder.url)); }; export default openFolder; diff --git a/src/lib/orientation.js b/src/lib/orientation.js new file mode 100644 index 0000000000..a83336ed56 --- /dev/null +++ b/src/lib/orientation.js @@ -0,0 +1,30 @@ +/** Temporary orientation requests for the main WebView's fullscreen session. */ +export default { + /** + * @param {"landscape" | "portrait"} mode + * @returns {Promise} Resolves when the native request is accepted. + */ + async lock(mode) { + if (mode !== "landscape" && mode !== "portrait") { + throw new TypeError("Orientation must be landscape or portrait."); + } + await setOrientation(mode); + }, + + /** @returns {Promise} Restores the previous policy, if overridden. */ + async unlock() { + await setOrientation(null); + }, +}; + +function setOrientation(mode) { + return new Promise((resolve, reject) => { + cordova.exec( + resolve, + (message) => reject(new Error(message)), + "System", + "set-fullscreen-orientation", + [mode], + ); + }); +} diff --git a/src/lib/pluginContext.js b/src/lib/pluginContext.js new file mode 100644 index 0000000000..f1087a8e17 --- /dev/null +++ b/src/lib/pluginContext.js @@ -0,0 +1,165 @@ +// `cordova.exec` is mapped asynchronously while Cordova starts. Importing this +// module can happen before that mapping completes, so use Cordova's internal +// module loader, which is available as soon as cordova.js has been evaluated. +const cordovaExec = cordova.require("cordova/exec"); + +const exec = (resolve, reject, action, args) => + cordovaExec(resolve, reject, "Tee", action, args); + +let bridgeHardened = false; + +function hardenBridge() { + if (bridgeHardened) return; + bridgeHardened = true; + + for (const prop of [ + "exec", + "callbackFromNative", + "callbackSuccess", + "callbackError", + "callbacks", + ]) { + const value = cordova[prop]; + if (value === undefined) continue; + try { + Object.defineProperty(cordova, prop, { + writable: false, + configurable: false, + }); + } catch { + // ignore + } + } +} + +class PluginContext { + #token; + + constructor(token) { + this.#token = token; + this.date = Date.now(); + Object.freeze(this); + } + + toString() { + return this.#token; + } + + [Symbol.toPrimitive](hint) { + if (hint === "number") { + return Number.NaN; // prevent numeric coercion + } + return this.#token; + } + + grantedPermission(permission) { + return new Promise((resolve, reject) => { + exec(resolve, reject, "grantedPermission", [this.#token, permission]); + }); + } + + listAllPermissions() { + return new Promise((resolve, reject) => { + exec(resolve, reject, "listAllPermissions", [this.#token]); + }); + } + + getSecret(key, defaultValue = "") { + return new Promise((resolve, reject) => { + exec(resolve, reject, "get_secret", [this.#token, key, defaultValue]); + }); + } + + setSecret(key, value) { + return new Promise((resolve, reject) => { + exec(resolve, reject, "set_secret", [this.#token, key, value]); + }); + } + + deleteSecret(key) { + return new Promise((resolve, reject) => { + exec(resolve, reject, "delete_secret", [this.#token, key]); + }); + } + + clearAllSecrets() { + return new Promise((resolve, reject) => { + exec(resolve, reject, "clear_all_secrets", [this.#token]); + }); + } + + //plugins dont need to call this + invalidate() { + return new Promise((resolve, reject) => { + exec(resolve, reject, "invalidate", [this.#token]); + }); + } +} + +Object.freeze(PluginContext.prototype); + +// Encapsulates the trusted native session. +class TrustedSession { + #session = null; + #sessionPromise = null; + + // Establishes the connection (once) and resolves to a boolean. The session + // secret is deliberately never returned to callers. + connectInternal() { + hardenBridge(); + + if (!this.#sessionPromise) { + this.#sessionPromise = new Promise((resolve) => { + cordovaExec( + (session) => { + this.#session = session; + resolve(true); + }, + () => resolve(false), + "Tee", + "establishConnection", + [], + ); + }); + } + return this.#sessionPromise; + } + + async generateInternal(pluginId, pluginJson) { + try { + const connected = await this.connectInternal(); + if (!connected || !this.#session) { + console.warn( + `PluginContext creation failed for pluginId ${pluginId}: no trusted session`, + ); + return null; + } + + //requesting a token with our session since we are in a privileged context + const uuid = await new Promise((resolve, reject) => { + cordovaExec(resolve, reject, "Tee", "requestToken", [ + this.#session, + pluginId, + pluginJson, + ]); + }); + return new PluginContext(uuid); + } catch (err) { + console.warn( + `PluginContext creation failed for pluginId ${pluginId}:`, + err, + ); + return null; + } + } +} + +const trustedSession = new TrustedSession(); + +export function connect() { + return trustedSession.connectInternal(); +} + +export default function generate(pluginId, pluginJson) { + return trustedSession.generateInternal(pluginId, pluginJson); +} diff --git a/src/lib/polyfill.js b/src/lib/polyfill.js index 9a853d5bcf..d8cab0bbb4 100644 --- a/src/lib/polyfill.js +++ b/src/lib/polyfill.js @@ -1,3 +1,14 @@ +// automatically include credentials for acode.app API requests +(function () { + const _fetch = window.fetch; + window.fetch = function (url, options) { + if (typeof url === "string" && url.includes("acode.app/api")) { + options = { ...options, credentials: "include" }; + } + return _fetch.call(this, url, options); + }; +})(); + // polyfill for prepend (function (arr) { @@ -91,6 +102,36 @@ }); })([Element.prototype, CharacterData.prototype, DocumentType.prototype]); +// polyfill for replaceChildren + +(function (arr) { + arr.forEach(function (item) { + if (item.hasOwnProperty("replaceChildren")) { + return; + } + Object.defineProperty(item, "replaceChildren", { + configurable: true, + enumerable: false, + writable: true, + value: function replaceChildren() { + while (this.firstChild) { + this.removeChild(this.firstChild); + } + // biome-ignore lint/style/useForOf: ES5 polyfill cannot use for...of + for (var i = 0; i < arguments.length; i++) { + var node = arguments[i]; + if (typeof node !== "object") { + node = this.ownerDocument.createTextNode(String(node)); + } else if (node.parentNode) { + node.parentNode.removeChild(node); + } + this.appendChild(node); + } + }, + }); + }); +})([Element.prototype, Document.prototype, DocumentFragment.prototype]); + // polyfill for toggleAttribute (function (arr) { diff --git a/src/lib/prettierFormatter.js b/src/lib/prettierFormatter.js new file mode 100644 index 0000000000..e95014c0cf --- /dev/null +++ b/src/lib/prettierFormatter.js @@ -0,0 +1,481 @@ +import fsOperation from "fileSystem"; +import { parse } from "acorn"; +import { getDocText } from "cm/editorUtils"; +import { getFormatAsMode } from "cm/modelist"; +import toast from "components/toast"; +import appSettings from "lib/settings"; +import prettierPluginBabel from "prettier/plugins/babel"; +import prettierPluginEstree from "prettier/plugins/estree"; +import prettierPluginGraphql from "prettier/plugins/graphql"; +import prettierPluginHtml from "prettier/plugins/html"; +import prettierPluginMarkdown from "prettier/plugins/markdown"; +import prettierPluginPostcss from "prettier/plugins/postcss"; +import prettierPluginTypescript from "prettier/plugins/typescript"; +import prettierPluginYaml from "prettier/plugins/yaml"; +import prettier from "prettier/standalone"; +import helpers from "utils/helpers"; +import Url from "utils/Url"; + +const CONFIG_FILENAMES = [ + ".prettierrc", + ".prettierrc.json", + ".prettierrc.json5", + ".prettierrc.js", + ".prettierrc.cjs", + ".prettierrc.mjs", + ".prettierrc.config.cjs", + ".prettierrc.config.mjs", + ".prettier.config.js", + ".prettier.config.cjs", + ".prettier.config.mjs", + "prettier.config.json", + "prettier.config.js", + "prettier.config.cjs", + "prettier.config.mjs", +]; +const PRETTIER_PLUGINS = [ + prettierPluginEstree, + prettierPluginBabel, + prettierPluginHtml, + prettierPluginMarkdown, + prettierPluginPostcss, + prettierPluginTypescript, + prettierPluginYaml, + prettierPluginGraphql, +]; + +/** + * Supported parser mapping keyed by CodeMirror mode name + * @type {Record} + */ +const MODE_TO_PARSER = { + angular: "angular", + gfm: "markdown", + css: "css", + graphql: "graphql", + html: "html", + json: "json", + json5: "json", + jsx: "babel", + less: "less", + markdown: "markdown", + md: "markdown", + mdx: "mdx", + scss: "scss", + styled_jsx: "babel", + typescript: "typescript", + tsx: "typescript", + jsonc: "json", + yaml: "yaml", + yml: "yaml", + vue: "vue", + javascript: "babel", +}; + +export async function formatActiveFileWithPrettier() { + const file = editorManager?.activeFile; + const editor = editorManager?.editor; + if (!file || file.type !== "editor" || !editor) return false; + + const modeName = (file.currentMode || "text").toLowerCase(); + const formatAs = getFormatAsMode(modeName); + const parser = + getParserForMode(modeName) || (formatAs && getParserForMode(formatAs)); + if (!parser) { + toast("Prettier does not support this file type yet"); + return false; + } + + const doc = editor.state.doc; + const source = getDocText(doc); + const filepath = file.uri || file.filename || ""; + try { + const config = await resolvePrettierConfig(file); + const formatted = await prettier.format(source, { + ...config, + parser, + plugins: PRETTIER_PLUGINS, + filepath, + overrideEditorconfig: true, + }); + + if (formatted === source) return true; + + editor.dispatch({ + changes: { + from: 0, + to: doc.length, + insert: formatted, + }, + }); + return true; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + toast(message); + return false; + } +} + +function getParserForMode(modeName) { + if (MODE_TO_PARSER[modeName]) return MODE_TO_PARSER[modeName]; + if (modeName.includes("javascript")) return "babel"; + if (modeName.includes("typescript")) return "typescript"; + return null; +} + +async function resolvePrettierConfig(file) { + const overrides = appSettings?.value?.prettier || {}; + const projectConfig = await loadProjectConfig(file); + const result = { ...overrides, ...(projectConfig || {}) }; + if (file?.eol && result.endOfLine == null) { + result.endOfLine = file.eol === "windows" ? "crlf" : "lf"; + } + if (result.useTabs == null) { + result.useTabs = !appSettings?.value?.softTab; + } + if ( + result.tabWidth == null && + typeof appSettings?.value?.tabSize === "number" + ) { + result.tabWidth = appSettings.value.tabSize; + } + return result; +} + +async function loadProjectConfig(file) { + const uri = file?.uri; + if (!uri) return null; + + const projectRoot = findProjectRoot(uri); + const directories = collectCandidateDirectories(uri, projectRoot); + + for (const directory of directories) { + const config = await readConfigFromDirectory(directory); + if (config) return config; + } + + return null; +} + +function findProjectRoot(uri) { + const folders = Array.isArray(globalThis.addedFolder) + ? globalThis.addedFolder + : []; + const target = normalizePath(uri); + let match = null; + let matchLength = -1; + + for (const folder of folders) { + const folderUrl = folder?.url; + if (!folderUrl) continue; + const normalized = normalizePath(folderUrl); + if (!normalized) continue; + if (target === normalized || target.startsWith(`${normalized}/`)) { + if (normalized.length > matchLength) { + match = folderUrl; + matchLength = normalized.length; + } + } + } + + return match; +} + +function collectCandidateDirectories(fileUri, projectRoot) { + const directories = []; + const visited = new Set(); + let currentDir = safeDirname(fileUri); + + while (currentDir) { + const normalized = normalizePath(currentDir); + if (visited.has(normalized)) break; + directories.push(currentDir); + visited.add(normalized); + if (projectRoot && pathsAreSame(currentDir, projectRoot)) break; + const parent = safeDirname(currentDir); + if (!parent || parent === currentDir) break; + currentDir = parent; + } + + if ( + projectRoot && + !directories.some((dir) => pathsAreSame(dir, projectRoot)) + ) { + directories.push(projectRoot); + } + + return directories; +} + +function safeDirname(path) { + try { + return Url.dirname(path); + } catch (_) { + return null; + } +} + +async function readConfigFromDirectory(directory) { + if (!directory) return null; + + for (const name of CONFIG_FILENAMES) { + const config = await loadConfigFile(directory, name); + if (config) return config; + } + + return loadPrettierFromPackageJson(directory); +} + +async function loadConfigFile(directory, basename) { + try { + const filePath = Url.join(directory, basename); + const fs = fsOperation(filePath); + if (!(await fs.exists())) return null; + const text = await fs.readFile("utf8"); + + switch (basename) { + case ".prettierrc": + case ".prettierrc.json": + case ".prettierrc.json5": + case "prettier.config.json": + return parseJsonLike(text); + case ".prettierrc.js": + case ".prettier.config.js": + case "prettier.config.js": + return parseJsConfig(directory, text, filePath); + case ".prettierrc.mjs": + case ".prettierrc.config.mjs": + case ".prettier.config.mjs": + case "prettier.config.mjs": + return parseJsConfig(directory, text, filePath); + case ".prettierrc.cjs": + case ".prettierrc.config.cjs": + case ".prettier.config.cjs": + case "prettier.config.cjs": + return parseJsConfig(directory, text, filePath); + default: + return null; + } + } catch (_) { + return null; + } +} + +async function loadPrettierFromPackageJson(directory) { + try { + const pkgPath = Url.join(directory, "package.json"); + const fs = fsOperation(pkgPath); + if (!(await fs.exists())) return null; + const pkg = await fs.readFile("json"); + const config = pkg?.prettier; + if (config && typeof config === "object") return config; + } catch (_) { + return null; + } + return null; +} + +function parseJsonLike(text) { + const trimmed = text?.trim(); + if (!trimmed) return null; + const parsed = helpers.parseJSON(trimmed); + if (parsed) return parsed; + try { + return parseSafeExpression(trimmed); + } catch (_) { + return null; + } +} + +function parseJsConfig(directory, source, absolutePath) { + if (!source) return null; + void directory; + void absolutePath; + try { + return extractConfigFromProgram(source); + } catch (_) { + return null; + } +} + +function parseProgram(source) { + try { + return parse(source, { + ecmaVersion: "latest", + sourceType: "module", + allowHashBang: true, + }); + } catch (_) { + return parse(source, { + ecmaVersion: "latest", + sourceType: "script", + allowHashBang: true, + }); + } +} + +function extractConfigFromProgram(source) { + const ast = parseProgram(source); + const scope = new Map(); + + for (const statement of ast.body) { + const declared = readVariableDeclaration(statement, scope); + if (declared) { + for (const [name, value] of declared) { + scope.set(name, value); + } + continue; + } + + const exported = readCommonJsExport(statement, scope); + if (exported !== undefined) return exported; + + const esmExported = readEsmExport(statement, scope); + if (esmExported !== undefined) return esmExported; + } + + return null; +} + +function parseSafeExpression(text) { + const wrapped = `(${text})`; + const ast = parse(wrapped, { + ecmaVersion: "latest", + sourceType: "module", + allowHashBang: true, + }); + const statement = ast.body[0]; + if (statement?.type !== "ExpressionStatement") return null; + return evaluateNode(statement.expression, new Map()); +} + +function readVariableDeclaration(statement, scope) { + if (statement?.type !== "VariableDeclaration") return null; + const values = new Map(); + const lookupScope = new Map(scope); + + for (const decl of statement.declarations || []) { + if (!decl || decl.type !== "VariableDeclarator") continue; + if (decl.id?.type !== "Identifier") continue; + if (!decl.init) continue; + try { + const value = evaluateNode(decl.init, lookupScope); + values.set(decl.id.name, value); + lookupScope.set(decl.id.name, value); + } catch (_) { + // Ignore unsupported declarations + } + } + + return values.size ? values : null; +} + +function readCommonJsExport(statement, scope) { + if (statement?.type !== "ExpressionStatement") return undefined; + const expr = statement.expression; + if (expr?.type !== "AssignmentExpression" || expr.operator !== "=") { + return undefined; + } + + if (!isModuleExports(expr.left)) return undefined; + return evaluateNode(expr.right, scope); +} + +function readEsmExport(statement, scope) { + if (statement?.type !== "ExportDefaultDeclaration") return undefined; + return evaluateNode(statement.declaration, scope); +} + +function isModuleExports(node) { + return ( + node?.type === "MemberExpression" && + !node.computed && + node.object?.type === "Identifier" && + node.object.name === "module" && + node.property?.type === "Identifier" && + node.property.name === "exports" + ); +} + +function evaluateNode(node, scope) { + if (!node) return null; + + switch (node.type) { + case "ObjectExpression": + return evaluateObjectExpression(node, scope); + case "ArrayExpression": + return node.elements.map((entry) => evaluateNode(entry, scope)); + case "Literal": + return node.value; + case "TemplateLiteral": + if (node.expressions.length) { + throw new Error("Template expressions are not supported"); + } + return node.quasis.map((part) => part.value.cooked ?? "").join(""); + case "Identifier": + if (scope.has(node.name)) return scope.get(node.name); + if (node.name === "undefined") return undefined; + throw new Error(`Unsupported identifier: ${node.name}`); + case "UnaryExpression": + return evaluateUnaryExpression(node, scope); + default: + throw new Error(`Unsupported node type: ${node.type}`); + } +} + +function evaluateObjectExpression(node, scope) { + const output = {}; + for (const property of node.properties || []) { + if (!property || property.type !== "Property") { + throw new Error("Unsupported object property"); + } + if (property.kind !== "init" || property.method || property.shorthand) { + throw new Error("Unsupported object property kind"); + } + const key = property.computed + ? evaluateNode(property.key, scope) + : getPropertyKey(property.key); + const normalizedKey = + typeof key === "string" || typeof key === "number" ? String(key) : null; + if (!normalizedKey) { + throw new Error("Unsupported object key"); + } + output[normalizedKey] = evaluateNode(property.value, scope); + } + return output; +} + +function getPropertyKey(node) { + if (node?.type === "Identifier") return node.name; + if (node?.type === "Literal") return node.value; + throw new Error("Unsupported property key"); +} + +function evaluateUnaryExpression(node, scope) { + const value = evaluateNode(node.argument, scope); + switch (node.operator) { + case "+": + return +value; + case "-": + return -value; + case "!": + return !value; + default: + throw new Error(`Unsupported unary operator: ${node.operator}`); + } +} + +function normalizePath(path) { + let result = String(path || "").replace(/\\/g, "/"); + while (result.length > 1 && result.endsWith("/")) { + const prefix = result.slice(0, -1); + if (/^[a-z]+:\/{0,2}$/i.test(prefix)) break; + result = prefix; + } + return result; +} + +function pathsAreSame(a, b) { + if (!a || !b) return false; + return normalizePath(a) === normalizePath(b); +} diff --git a/src/lib/privacyChoicesController.mjs b/src/lib/privacyChoicesController.mjs new file mode 100644 index 0000000000..9fb3cf9470 --- /dev/null +++ b/src/lib/privacyChoicesController.mjs @@ -0,0 +1,38 @@ +export const PRIVACY_CHOICES_KEY = "privacyChoices"; + +/** + * Keeps the Privacy Choices setting synchronized with the latest UMP state. + * + * @param {{ + * page: { + * setItemVisibility:(key:string, visible:boolean)=>boolean, + * onClose:(callback:()=>void)=>()=>void + * }, + * subscribe:(listener:(state:{privacyOptionsRequired:boolean})=>void)=>()=>void, + * key?:string + * }} options + */ +export function bindPrivacyChoices({ + page, + subscribe, + key = PRIVACY_CHOICES_KEY, +}) { + let active = true; + let unsubscribeState = () => {}; + let unsubscribeClose = () => {}; + + const dispose = () => { + if (!active) return; + active = false; + unsubscribeState(); + unsubscribeClose(); + }; + + unsubscribeState = subscribe((state) => { + if (!active) return; + page.setItemVisibility(key, state?.privacyOptionsRequired === true); + }); + unsubscribeClose = page.onClose(dispose); + + return dispose; +} diff --git a/src/lib/quickToolsAdapter.js b/src/lib/quickToolsAdapter.js new file mode 100644 index 0000000000..03c6bf7b08 --- /dev/null +++ b/src/lib/quickToolsAdapter.js @@ -0,0 +1,205 @@ +import { hasQuickToolsOverlay } from "./quickToolsOverlays"; + +/** + * Per-tab input routing for custom editors. No editor engine or UI dependencies. + * An adapter owns all editing actions on its tab: unsupported actions never fall + * through to the code editor, including while an asynchronous action is pending. + */ +export function createQuickToolsAdapterRegistry( + getActiveTab, + resolveAction = async (action) => action, + isBlocked = () => false, +) { + const entries = new Map(); + const listeners = new Set(); + let activeTab, + blocked = false; + const notify = (change) => listeners.forEach((listener) => listener(change)); + const current = () => entries.get(getActiveTab()); + function cancel(entry) { + if (!entry || entry.cancelling) return; + entry.cancelling = true; + try { + entry.controller.abort(); + entry.controller = new AbortController(); + entry.queue = Promise.resolve(); + entry.pending = 0; + entry.selection = undefined; + entry.adapter.cancel?.(); + } finally { + entry.cancelling = false; + } + } + const valid = (entry, signal) => + !signal.aborted && + !blocked && + !isBlocked() && + current() === entry && + entry.adapter.getState().enabled && + !entry.adapter.getState().busy; + return { + subscribe(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + register(tab, adapter) { + if ( + !tab || + !adapter?.getState || + !adapter?.canHandle || + !adapter?.execute || + !adapter?.subscribe + ) + throw new TypeError( + "A quicktools adapter needs a tab, state, availability and execution handlers.", + ); + if (entries.has(tab)) + throw new Error("This tab already has a quicktools adapter."); + const entry = { + tab, + adapter, + controller: new AbortController(), + queue: Promise.resolve(), + pending: 0, + selection: undefined, + cancelling: false, + }; + entries.set(tab, entry); + const unsubscribe = adapter.subscribe(() => { + const state = adapter.getState(); + const cancelled = !state.enabled || state.busy; + if (cancelled) cancel(entry); + notify({ tab, cancelled }); + }); + const dispose = () => { + if (entries.get(tab) !== entry) return; + entries.delete(tab); + unsubscribe?.(); + tab.off?.("close", dispose); + cancel(entry); + notify({ tab, cancelled: true }); + }; + tab.on?.("close", dispose); + notify(); + return dispose; + }, + sync() { + const next = getActiveTab(); + if (next !== activeTab) { + cancel(entries.get(activeTab)); + activeTab = next; + } + notify(); + }, + setBlocked(value) { + if (blocked === value) return; + blocked = value; + if (value) cancel(current()); + notify(); + }, + has(tab = getActiveTab()) { + return entries.has(tab); + }, + visible(tab = getActiveTab()) { + const entry = entries.get(tab); + return entry ? !!entry.adapter.getState().enabled : !tab?.hideQuickTools; + }, + available(action) { + const entry = current(); + return ( + !!entry && + !blocked && + !isBlocked() && + entry.adapter.getState().enabled && + !entry.adapter.getState().busy && + entry.adapter.canHandle(action) + ); + }, + capture() { + const entry = current(); + if (!entry || blocked || isBlocked() || entry.selection) return; + // Repeated input must capture the selection produced by the preceding + // action, rather than restoring an older caret when the queue catches up. + entry.selection = entry.pending + ? entry.queue.then(() => entry.adapter.captureSelection?.()) + : Promise.resolve(entry.adapter.captureSelection?.()); + // Capture failures are reported by dispatch, without an unhandled rejection. + entry.selection.catch(() => {}); + }, + discardCapture() { + // Dispatched actions already own their snapshots. Leave their queue intact. + const entry = current(); + if (entry) entry.selection = undefined; + }, + dispatch(action) { + const entry = current(); + if (!entry) return false; + if (!this.available(action)) { + this.discardCapture(); + return true; + } + const signal = entry.controller.signal, + selection = entry.selection; + entry.selection = undefined; + entry.pending++; + entry.queue = entry.queue + .then(async () => { + if (!valid(entry, signal) || !this.available(action)) return; + if (selection) { + const snapshot = await selection; + if (!valid(entry, signal)) return; + await entry.adapter.restoreSelection?.(snapshot); + } + if (!valid(entry, signal) || !this.available(action)) return; + const resolved = await resolveAction(action); + if (valid(entry, signal) && this.available(action)) + await entry.adapter.execute(resolved, { signal }); + }) + .catch((error) => { + if (valid(entry, signal)) entry.adapter.onError?.(error); + }) + .finally(() => { + if (signal === entry.controller.signal) entry.pending--; + }); + return true; + }, + focus() { + const entry = current(); + if (entry && !blocked && entry.adapter.getState().enabled) { + const signal = entry.controller.signal; + Promise.resolve() + .then(() => { + if (valid(entry, signal)) return entry.adapter.focus?.(); + }) + .catch((error) => { + if (valid(entry, signal)) entry.adapter.onError?.(error); + }); + } + }, + cancel() { + cancel(current()); + }, + }; +} + +export default createQuickToolsAdapterRegistry( + () => globalThis.editorManager?.activeFile, + async (action) => { + const paste = + (action.type === "command" && action.command === "paste") || + (action.type === "key" && + (action.ctrlKey || action.metaKey) && + action.key.toLowerCase() === "v"); + if (!paste) return action; + const text = await new Promise((resolve, reject) => { + const clipboard = globalThis.cordova?.plugins?.clipboard; + if (!clipboard) { + reject(new Error("Clipboard is unavailable.")); + return; + } + clipboard.paste(resolve, reject); + }); + return { type: "text", text: String(text || "") }; + }, + hasQuickToolsOverlay, +); diff --git a/src/lib/quickToolsOverlays.js b/src/lib/quickToolsOverlays.js new file mode 100644 index 0000000000..ac812a35c9 --- /dev/null +++ b/src/lib/quickToolsOverlays.js @@ -0,0 +1,53 @@ +// Native dialogs and menus are direct children of body or the app container. +// Never observe editor content (including an adapter's ShadowRoot/iframe). +const containers = () => + [globalThis.document?.body, globalThis.app].filter( + (node, index, nodes) => + node?.nodeType === 1 && nodes.indexOf(node) === index, + ); +export function hasQuickToolsOverlay() { + return containers().some((root) => + [...root.children].some((node) => + node.matches(".prompt, #palette, .context-menu, .mask"), + ), + ); +} + +export function watchQuickToolsOverlays(registry, cancelInput) { + let watching = false, + wasBlocked = false; + const update = () => { + const blocked = hasQuickToolsOverlay(); + if (blocked && !wasBlocked) cancelInput(); + wasBlocked = blocked; + registry.setBlocked(blocked); + }; + const observer = new MutationObserver(update); + const sync = () => { + const active = registry.has(); + if (active === watching) return; + watching = active; + if (active) { + for (const node of containers()) + observer.observe(node, { childList: true }); + document.addEventListener("focusin", update, true); + document.addEventListener("pointerdown", update, true); + update(); + } else { + wasBlocked = false; + observer.disconnect(); + document.removeEventListener("focusin", update, true); + document.removeEventListener("pointerdown", update, true); + registry.setBlocked(false); + } + }; + const unsubscribe = registry.subscribe(sync); + sync(); + return () => { + unsubscribe(); + observer.disconnect(); + document.removeEventListener("focusin", update, true); + document.removeEventListener("pointerdown", update, true); + registry.setBlocked(false); + }; +} diff --git a/src/lib/recents.js b/src/lib/recents.js index 9eb3bad844..eda542edcf 100644 --- a/src/lib/recents.js +++ b/src/lib/recents.js @@ -1,6 +1,7 @@ import select from "dialogs/select"; import escapeStringRegexp from "escape-string-regexp"; import helpers from "utils/helpers"; +import Uri from "utils/Uri"; import Url from "utils/Url"; const recents = { @@ -8,13 +9,15 @@ const recents = { * @returns {Array} */ get files() { - return JSON.parse(localStorage.recentFiles || "[]"); + const files = helpers.parseJSON(localStorage.recentFiles); + return Array.isArray(files) ? files : []; }, /** * @returns {{url: String, opts: Map}[]} */ get folders() { - return JSON.parse(localStorage.recentFolders || "[]"); + const folders = helpers.parseJSON(localStorage.recentFolders); + return Array.isArray(folders) ? folders : []; }, set files(list) { if (Array.isArray(list)) localStorage.recentFiles = JSON.stringify(list); @@ -52,7 +55,7 @@ const recents = { removeFolder(url) { ({ url } = Url.parse(url)); this.folders = this.folders.filter((folder) => { - return !new RegExp("^" + escapeStringRegexp(folder.url)).test(url); + return !Url.isSameOrDescendant(folder.url, url); }); }, @@ -76,20 +79,28 @@ const recents = { */ select(extra, type = "all", title = strings["open recent"]) { const all = []; - const MAX = 20; - const shortName = (name) => { - name = helpers.getVirtualPath(name); - - if (name.length > MAX) { - return "..." + name.substr(-MAX - 3); - } - return name; + const pathDetails = (url) => { + url = Url.parse(url).url; + const isSafUri = /^content:/.test(url); + const displayPath = isSafUri + ? Uri.getDisplayPath(url) + : helpers.getVirtualPath(url); + const documentPath = isSafUri ? Uri.getDisplayPath(url, []) : displayPath; + const name = Url.basename(displayPath) || Url.basename(documentPath); + const location = + Url.dirname(isSafUri ? documentPath : displayPath)?.replace( + /\/$/, + "", + ) || "/"; + + return { name, location, path: documentPath }; }; if (type === "dir" || type === "all") { let dirs = this.folders; for (let dir of dirs) { const { url } = dir; + const { name, location, path } = pathDetails(url); const dirValue = { type: "dir", @@ -105,8 +116,11 @@ const recents = { all.push({ value: dirValue, - text: shortName(url), - icon: "folder", + text: name, + subText: location, + title: path, + fileIcon: { name, kind: "folder" }, + className: "recent-entry", tailElement: tailElement, ontailclick: (e) => { const $item = e.currentTarget.closest(".tile"); @@ -121,7 +135,7 @@ const recents = { let files = this.files; for (let file of files) { if (!file) continue; - const name = shortName(Url.parse(file).url); + const { name, location, path } = pathDetails(Url.parse(file).url); const fileValue = { type: "file", @@ -137,7 +151,10 @@ const recents = { all.push({ value: fileValue, text: name, - icon: helpers.getIconForFile(name), + subText: location, + title: path, + fileIcon: { name, kind: "file" }, + className: "recent-entry", tailElement: tailElement, ontailclick: (e) => { const $item = e.currentTarget.closest(".tile"); @@ -148,19 +165,22 @@ const recents = { } } - if (type === "all") all.push(["clear", strings.clear, "icon clearclose"]); - - if (extra) { - extra = extra.map((item) => { - item[1] = shortName(item[1]); - return item; + if (type === "all") { + all.push({ + value: "clear", + text: strings.clear, + icon: "clearclose", + className: "recent-clear", }); + } + if (extra) { all.push(...extra); } return select(title, all, { textTransform: false, + className: "recent-select", }); }, }; diff --git a/src/lib/registerPrettierFormatter.js b/src/lib/registerPrettierFormatter.js new file mode 100644 index 0000000000..b89fb1d1c2 --- /dev/null +++ b/src/lib/registerPrettierFormatter.js @@ -0,0 +1,46 @@ +const PRETTIER_ID = "prettier"; +const PRETTIER_NAME = "Prettier"; + +const SUPPORTED_EXTENSIONS = [ + "js", + "cjs", + "mjs", + "jsx", + "ts", + "tsx", + "json", + "json5", + "css", + "scss", + "less", + "html", + "htm", + "vue", + "md", + "markdown", + "mdx", + "yaml", + "yml", + "graphql", + "gql", +]; + +export function registerPrettierFormatter() { + if (!window?.acode) return; + const alreadyRegistered = acode.formatters.some( + ({ id }) => id === PRETTIER_ID, + ); + if (alreadyRegistered) return; + + acode.registerFormatter( + PRETTIER_ID, + SUPPORTED_EXTENSIONS, + async () => { + const { formatActiveFileWithPrettier } = await import( + /* webpackChunkName: "prettierFormatter" */ "lib/prettierFormatter" + ); + return formatActiveFileWithPrettier(); + }, + PRETTIER_NAME, + ); +} diff --git a/src/lib/remoteStorage.js b/src/lib/remoteStorage.js index 96dee270a5..967f5fcb5d 100644 --- a/src/lib/remoteStorage.js +++ b/src/lib/remoteStorage.js @@ -1,4 +1,3 @@ -import fsOperation from "fileSystem"; import Ftp from "fileSystem/ftp"; import Sftp from "fileSystem/sftp"; import loader from "dialogs/loader"; @@ -6,6 +5,13 @@ import multiPrompt from "dialogs/multiPrompt"; import URLParse from "url-parse"; import helpers from "utils/helpers"; import Url from "utils/Url"; +import { + createSftpProfileUrl, + editSftpProfile, + getSftpProfileId, + getSftpProfileInfo, +} from "./sftpProfiles"; +import { interstitialAd } from "./startAd"; export default { /** @@ -29,7 +35,7 @@ export default { try { loader.create(strings["add ftp"], strings["connecting..."], { timeout: 10000, - callback() { + oncancel() { stopConnection = true; }, }); @@ -65,9 +71,7 @@ export default { res.home = home; } loader.destroy(); - if (IS_FREE_VERSION && (await window.iad?.isLoaded())) { - window.iad.show(); - } + await helpers.showInterstitialIfReady(); return res; } catch (err) { if (stopConnection) { @@ -162,79 +166,107 @@ export default { ]); } }, - /** - * @param {...any} args [hostname, username, keyFile, password, passphrase, port, name] - */ - async addSftp(...args) { + /** Persist credentials natively and retain only an opaque profile URL. */ + async addSftp({ + hostname = "", + username = "", + port = 22, + alias: initialAlias = "", + authType = "password", + existingProfile = null, + } = {}) { let stopConnection = false; + let connection; + const connectionRequestID = `add-sftp-${helpers.uuid()}`; + if (existingProfile?.profileId) { + try { + const saved = await getSftpProfileInfo(existingProfile.profileId); + hostname = saved.hostname; + username = saved.username; + port = saved.port; + authType = saved.authType; + } catch (error) { + await helpers.error(error); + return null; + } + } - const { - hostname, - username, - keyFile, - password, - passPhrase, - port, - alias, - usePassword, - } = await prompt(...args); - const authType = usePassword ? "password" : "keyFile"; + let values; + try { + values = await prompt({ + hostname, + username, + port, + alias: initialAlias || existingProfile?.name || "", + authType: authType === "keyFile" ? "key" : authType, + hasSavedKey: existingProfile?.profileId && authType === "key", + }); + } catch { + return null; + } + + const retryDetails = { + hostname: values.hostname, + username: values.username, + port: values.port, + alias: values.alias, + authType: values.usePassword ? "password" : "key", + existingProfile, + }; + let profile; + let saveError; + try { + profile = await editSftpProfile({ + profileId: existingProfile?.profileId, + hostname: values.hostname, + username: values.username, + port: values.port, + authType: values.usePassword ? "password" : "key", + password: values.password, + keyFile: values.keyFile, + passPhrase: values.passPhrase, + }); + } catch (error) { + saveError = error; + } finally { + // Drop all WebView references as soon as the native store has consumed them. + values.password = ""; + values.keyFile = ""; + values.passPhrase = ""; + } + if (saveError) { + values = null; + await helpers.error(saveError); + return this.addSftp(retryDetails); + } + const alias = values.alias; + values = null; + const url = createSftpProfileUrl(profile.profileId); loader.create(strings["add sftp"], strings["connecting..."], { - timeout: 10000, - callback() { + timeout: 0, + oncancel() { stopConnection = true; + connection?.cancelConnection(connectionRequestID); }, }); - const connection = Sftp(hostname, Number.parseInt(port), username, { - password, - keyFile, - passPhrase, + connection = Sftp(null, 22, null, { + profileID: profile.profileId, }); try { - const [home] = await Promise.all([connection.pwd(), loadAd()]); + const [home] = await Promise.all([ + connection.testConnection(connectionRequestID), + loadAd(), + ]); if (stopConnection) { stopConnection = false; return; } - let localKeyFile = ""; - if (keyFile) { - let fs = fsOperation(keyFile); - const text = await fs.readFile("utf8"); - - //Original key file sometimes gives permission error - //To solve permission error - const filename = keyFile.hashCode(); - localKeyFile = Url.join(DATA_STORAGE, filename); - fs = fsOperation(localKeyFile); - const exists = await fs.exists(); - if (exists) { - await fs.writeFile(text); - } else { - let fs = fsOperation(DATA_STORAGE); - await fs.createFile(filename, text); - } - } - - const url = Url.formate({ - protocol: "sftp:", - hostname, - username, - password, - port, - path: "/", - query: { - keyFile: localKeyFile, - passPhrase, - }, - }); loader.destroy(); - if (IS_FREE_VERSION && (await window.iad?.isLoaded())) { - window.iad.show(); - } + await helpers.showInterstitialIfReady(); return { alias, name: alias, @@ -249,52 +281,51 @@ export default { } loader.destroy(); - await helpers.error(err); - return await this.addSftp( - hostname, - username, - keyFile, - password, - passPhrase, - port, + if (!err?.reported) await helpers.error(err); + return await this.addSftp({ + hostname: profile.hostname, + username: profile.username, + port: profile.port, alias, - authType, - ); + authType: profile.authType, + existingProfile: { + ...profile, + url, + home: existingProfile?.home, + }, + }); } - function prompt( + function prompt({ hostname, username, - keyFile, - password, - passPhrase, port, alias, - authType = "password", - ) { - port = port || 22; - - const MODE_PASS = authType === "password"; - const inputs = [ + authType, + hasSavedKey, + }) { + const usePassword = authType !== "key"; + return multiPrompt(strings["add sftp"], [ { id: "alias", placeholder: strings.name, type: "text", - value: alias ? alias : "", + value: alias, required: true, }, { id: "username", - placeholder: `${strings.username} (${strings.optional})`, + placeholder: strings.username, type: "text", value: username, + required: true, }, { id: "hostname", placeholder: strings.hostname, type: "text", - required: true, value: hostname, + required: true, }, [ "Authentication type: ", @@ -303,13 +334,12 @@ export default { placeholder: strings.password, name: "authType", type: "radio", - value: MODE_PASS, + value: usePassword, onchange() { - if (!!this.value) { - this.prompt.$body.get("#password").hidden = false; - this.prompt.$body.get("#keyFile").hidden = true; - this.prompt.$body.get("#passPhrase").hidden = true; - } + if (!this.checked) return; + this.prompt.$body.get("#password").hidden = false; + this.prompt.$body.get("#keyFile").hidden = true; + this.prompt.$body.get("#passPhrase").hidden = true; }, }, { @@ -317,59 +347,75 @@ export default { placeholder: strings["key file"], name: "authType", type: "radio", - value: !MODE_PASS, + value: !usePassword, onchange() { - if (!!this.value) { - const $password = this.prompt.$body.get("#password"); - $password.hidden = true; - $password.value = ""; - this.prompt.$body.get("#keyFile").hidden = false; - this.prompt.$body.get("#passPhrase").hidden = false; - } + if (!this.checked) return; + const password = this.prompt.$body.get("#password"); + password.hidden = true; + password.value = ""; + this.prompt.$body.get("#keyFile").hidden = false; + this.prompt.$body.get("#passPhrase").hidden = false; }, }, ], { id: "password", - placeholder: strings.password, - name: "password", + placeholder: existingProfile?.profileId + ? `${strings.password} (leave blank to keep saved)` + : strings.password, type: "password", - value: password, - hidden: !MODE_PASS, + hidden: !usePassword, }, { id: "keyFile", - placeholder: strings["select key file"], - name: "keyFile", - hidden: MODE_PASS, - value: keyFile, + placeholder: hasSavedKey + ? `${strings["select key file"]} (leave blank to keep saved)` + : strings["select key file"], type: "text", + readOnly: true, + sensitive: true, + hidden: usePassword, onclick() { - sdcard.openDocumentFile((res) => { - this.value = res.uri; + sdcard.openDocumentFile((result) => { + this.value = result.uri; }); }, }, { id: "passPhrase", placeholder: `${strings.passphrase} (${strings.optional})`, - name: "passPhrase", type: "password", - hidden: MODE_PASS, - value: passPhrase, + hidden: usePassword, }, { id: "port", - placeholder: `${strings.port} (${strings.optional})`, + placeholder: strings.port, type: "number", - value: port, + value: port || 22, + required: true, }, - ]; - - return multiPrompt(strings["add sftp"], inputs); + ]); } }, - edit({ name, storageType, url }) { + async edit({ name, storageType, url, home }) { + const profileId = getSftpProfileId(url); + if (storageType === "sftp" && profileId) { + return this.addSftp({ + alias: name, + existingProfile: { profileId, url, home, name }, + }); + } + if (storageType === "sftp") { + const { username, hostname, port, query } = URLParse(url, true); + return this.addSftp({ + hostname, + username: username ? decodeURIComponent(username) : "", + port: port || 22, + alias: name, + authType: query?.keyFile ? "key" : "password", + }); + } + let { username, password, hostname, port, query } = URLParse(url, true); if (username) { @@ -401,38 +447,18 @@ export default { ); } - if (storageType === "sftp") { - let { passPhrase, keyFile } = query; - if (passPhrase) { - passPhrase = decodeURIComponent(passPhrase); - } - - if (keyFile) { - keyFile = decodeURIComponent(keyFile); - } - - return this.addSftp( - hostname, - username, - keyFile, - password, - passPhrase, - port, - name, - password ? "password" : "key", - ); - } - return null; }, }; async function loadAd() { - if (!IS_FREE_VERSION) return; + if (!helpers.canShowAds()) return; try { - if (!(await window.iad?.isLoaded())) { + if (!(await interstitialAd?.isLoaded())) { toast(strings.loading); - await window.iad.load(); + await interstitialAd?.load(); } - } catch (error) {} + } catch (error) { + console.warn("Failed to load interstitial ad.", error); + } } diff --git a/src/lib/removeAds.js b/src/lib/removeAds.js index 2188e810e3..fcb0bcb3b9 100644 --- a/src/lib/removeAds.js +++ b/src/lib/removeAds.js @@ -1,34 +1,138 @@ +import toast from "components/toast"; +import confirm from "dialogs/confirm"; +import loader from "dialogs/loader"; import purchaseListener from "handlers/purchase"; import helpers from "utils/helpers"; +import auth from "./auth"; +import config from "./config"; +import customTab from "./customTab"; +import { BANNER_SUPPRESSION_REASON, setBannerSuppressed } from "./startAd"; -/** - * Remove ads after purchase - * @returns {Promise} - */ -export default function removeAds() { - return new Promise((resolve, reject) => { - iap.getProducts(["acode_pro_new"], (products) => { - const [product] = products; +let activePurchase = null; +let activeRequest = null; - iap.setPurchaseUpdatedListener(...purchaseListener(onpurchase, reject)); +function enablePro() { + config.HAS_PRO = true; + setBannerSuppressed(BANNER_SUPPRESSION_REASON.PRO, true); +} - iap.purchase( - product.productId, - (code) => { - // ignore - }, - (err) => { - alert(strings.error, err); +/** Purchase Pro through Play billing. Resolves only after purchase confirmation. */ +export default function removeAds({ signal } = {}) { + if (signal?.aborted) return Promise.reject(strings.canceled); + if (activePurchase) return activePurchase; + activePurchase = new Promise((resolve, reject) => { + let settled = false; + let launched = false; + let purchased = false; + function cancel() { + if (!launched) fail(strings.canceled); + } + function fail(error) { + if (settled) return; + settled = true; + signal?.removeEventListener("abort", cancel); + reject(error); + } + function onpurchase() { + // A pending purchase can be confirmed after the caller has settled. + if (purchased) return; + purchased = true; + settled = true; + signal?.removeEventListener("abort", cancel); + enablePro(); + // The cache is reverified by the existing startup purchase checks. + try { + localStorage.setItem("acode_pro", "true"); + } catch (error) { + console.warn("Unable to cache Pro purchase", error); + } + toast(strings["thank you :)"]); + resolve(); + } + signal?.addEventListener("abort", cancel, { once: true }); + try { + iap.getProducts( + ["acode_pro_new"], + (products) => { + if (settled) return; + try { + const product = products?.find( + ({ productId }) => productId === "acode_pro_new", + ); + if (!product) return fail(strings["no-product-info"]); + iap.setPurchaseUpdatedListener( + ...purchaseListener(onpurchase, fail), + ); + launched = true; + iap.purchase(product.productId, () => {}, fail); + } catch (error) { + fail(error); + } }, + fail, ); - }); + } catch (error) { + fail(error); + } + }).finally(() => { + activePurchase = null; + }); + return activePurchase; +} - function onpurchase() { - resolve(null); - helpers.hideAd(true); - localStorage.setItem("acode_pro", "true"); - window.IS_FREE_VERSION = false; - toast(strings["thank you :)"]); +/** Reuse the Remove ads entry point; external checkout completes via its intent. */ +export function requestProPurchase({ signal } = {}) { + if (signal?.aborted) return Promise.resolve(false); + if (config.HAS_PRO) return Promise.resolve(true); + if (activeRequest) return activeRequest; + activeRequest = (async () => { + if (!helpers.shouldAllowExternalPurchase()) { + try { + await removeAds({ signal }); + return config.HAS_PRO; + } catch (error) { + if ( + error === strings.canceled || + error === globalThis.iap?.USER_CANCELED + ) + return false; + throw error; + } + } + + loader.create(strings.login, strings["loading..."]); + try { + let user = await auth.getLoggedInUser(); + if (signal?.aborted) return false; + if (!user) { + // Dismiss the modal loader so Android Back can cancel confirmation. + loader.destroy(); + const confirmed = await confirm( + strings.confirm, + strings["confirm-login"], + false, + { signal }, + ); + if (!confirmed || signal?.aborted) return false; + loader.create(strings.login, strings["loading..."]); + await auth.login(); + if (signal?.aborted) return false; + user = await auth.getLoggedInUser(); + } + if (signal?.aborted) return false; + if (!user) throw new Error(strings.failed); + if (user.acode_pro) { + enablePro(); + return true; + } + } finally { + loader.destroy(); } + if (signal?.aborted) return false; + await customTab(`${config.BASE_URL}/pro?redirect=app`); + return config.HAS_PRO; + })().finally(() => { + activeRequest = null; }); + return activeRequest; } diff --git a/src/lib/restoreFiles.js b/src/lib/restoreFiles.js index 345d2280cc..fa50829105 100644 --- a/src/lib/restoreFiles.js +++ b/src/lib/restoreFiles.js @@ -3,26 +3,35 @@ import EditorFile from "./editorFile"; /** * * @param {import('./editorFile').FileOptions[]} files - * @param {(count: number)=>void} callback */ export default async function restoreFiles(files) { - let rendered = false; + const hasRenderedFile = files.some((file) => file.render); + const localLoads = []; - await Promise.all( - files.map(async (file, i) => { - rendered = file.render; + files.forEach((file, index) => { + const render = + file.render || (!hasRenderedFile && index === files.length - 1); + const options = { + ...file, + render, + emitUpdate: false, + }; + const restoredFile = new EditorFile(file.filename, options); + const load = Promise.resolve(restoredFile.load?.()); - if (i === files.length - 1 && !rendered) { - file.render = true; - } + if (file.uri && !/^(?:file|content):/i.test(file.uri)) { + void load.catch((error) => { + console.warn(`Failed to preload restored file: ${file.uri}`, error); + }); + return; + } - const { filename, render = false } = file; - const options = { - ...file, - render, - emitUpdate: false, - }; - new EditorFile(filename, options); - }), - ); + localLoads.push(load); + }); + + // Finish restoring local documents before startup persistence is enabled. + // Otherwise the temporary empty sessions can overwrite saved cursor state, + // and the first visit to an inactive local tab visibly flashes a loading editor. + // Remote and plugin tabs must not block the plugin startup they depend on. + await Promise.all(localLoads); } diff --git a/src/lib/restoreTheme.js b/src/lib/restoreTheme.js index 8c88650a62..e389cfb5ba 100644 --- a/src/lib/restoreTheme.js +++ b/src/lib/restoreTheme.js @@ -1,5 +1,6 @@ import themes from "theme/list"; import Color from "utils/color"; +import config from "./config"; import appSettings from "./settings"; let count = 0; @@ -19,7 +20,7 @@ export default function restoreTheme(darken = false) { let themeName = DOES_SUPPORT_THEME ? appSettings.value.appTheme : "default"; let theme = themes.get(themeName); - if (theme?.version !== "free" && IS_FREE_VERSION) { + if (theme?.version !== "free" && !config.HAS_PRO) { themeName = "default"; theme = themes.get(themeName); appSettings.value.appTheme = themeName; diff --git a/src/lib/rewardedAd.js b/src/lib/rewardedAd.js new file mode 100644 index 0000000000..fcb375b6e5 --- /dev/null +++ b/src/lib/rewardedAd.js @@ -0,0 +1,120 @@ +import config from "./config"; +import startAd, { + adUnitIdRewarded, + getPrivacyState, + initialized, +} from "./startAd"; + +const RESULT_TIMEOUT_MS = 90_000; +let active = false; +let nextId = 0; + +export function isRewardedAdSupported() { + return Boolean( + !config.HAS_PRO && + typeof admob !== "undefined" && + admob.RewardedAd && + window.ANDROID_SDK_INT >= 29 && + adUnitIdRewarded, + ); +} + +export function isWatchingRewardedAd() { + return active; +} + +/** Show one reward, without granting an ad-free pass or applying its reward. */ +export default function showRewardedAd({ + serverSideVerification, + signal, +} = {}) { + if (signal?.aborted) return Promise.resolve(false); + if (active || !isRewardedAdSupported()) { + return Promise.reject(new Error(strings["rewarded ad unavailable"])); + } + active = true; + return new Promise((resolve, reject) => { + let earned = false; + let settled = false; + let presenting = false; + let cleaned = false; + const unsubscribe = []; + const timeout = setTimeout( + () => finish(new Error(strings["rewarded ad failed"])), + RESULT_TIMEOUT_MS, + ); + + function cleanup() { + // A cancelled/timed-out caller must not allow another full-screen ad + // until the native ad actually dismisses (show() resolves on opening). + if (presenting || cleaned) return; + cleaned = true; + for (const off of unsubscribe.splice(0)) off(); + active = false; + } + + function finish(error, result = false) { + if (!settled) { + settled = true; + clearTimeout(timeout); + signal?.removeEventListener("abort", cancel); + if (error) reject(error); + else resolve(result); + } + cleanup(); + } + + function cancel() { + finish(null); + } + + signal?.addEventListener("abort", cancel, { once: true }); + void (async () => { + await startAd(); + if (settled) return; + if ( + !isRewardedAdSupported() || + !initialized || + !getPrivacyState().canRequestAds + ) { + throw new Error(strings["rewarded ad unavailable"]); + } + const ad = new admob.RewardedAd({ + id: `acode-reward-${++nextId}`, + adUnitId: adUnitIdRewarded, + ...(serverSideVerification ? { serverSideVerification } : {}), + }); + unsubscribe.push( + ad.on("reward", () => { + if (!settled) earned = true; + }), + ad.on("dismiss", () => { + presenting = false; + finish(null, earned && !signal?.aborted); + }), + ad.on("showfail", () => { + presenting = false; + finish(new Error(strings["rewarded ad failed"])); + }), + ad.on("loadfail", () => + finish(new Error(strings["rewarded ad failed"])), + ), + () => { + void ad.destroy().catch((error) => { + console.warn("Failed to destroy rewarded ad", error); + }); + }, + ); + await ad.load(); + if (settled) return; + presenting = true; + if ((await ad.show()) === false) { + presenting = false; + finish(new Error(strings["rewarded ad failed"])); + } + })().catch(() => { + presenting = false; + finish(new Error(strings["rewarded ad failed"])); + }); + }); +} diff --git a/src/lib/run.js b/src/lib/run.js index 7092175311..beb5346433 100644 --- a/src/lib/run.js +++ b/src/lib/run.js @@ -1,27 +1,30 @@ import fsOperation from "fileSystem"; +import { getDocText } from "cm/editorUtils"; import tutorial from "components/tutorial"; import alert from "dialogs/alert"; -import box from "dialogs/box"; +import dialog from "dialogs/dialog"; import markdownIt from "markdown-it"; import anchor from "markdown-it-anchor"; -import markdownItFootnote from "markdown-it-footnote"; import MarkdownItGitHubAlerts from "markdown-it-github-alerts"; -import markdownItTaskLists from "markdown-it-task-lists"; import mimeType from "mime-types"; import mustache from "mustache"; +import openMarkdownPreview from "pages/markdownPreview"; import browser from "plugins/browser"; import helpers from "utils/helpers"; import Url from "utils/Url"; import $_console from "views/console.hbs"; import $_markdown from "views/markdown.hbs"; -import constants from "./constants"; +import config from "./config"; import EditorFile from "./editorFile"; -import openFolder, { addedFolder } from "./openFolder"; +import openFolder from "./openFolder"; import appSettings from "./settings"; /**@type {Server} */ let webServer; +// An open console may outlive the server instance that created it. +const CONSOLE_THEME_STATE = "__acode_console_theme.json"; + /** * Starts the server and run the active file in browser * @param {Boolean} isConsole @@ -33,6 +36,15 @@ async function run( target = appSettings.value.previewMode, runFile = false, ) { + /** @type {EditorFile} */ + const activeFile = isConsole ? null : editorManager.activeFile; + + if (!isConsole && Url.extname(activeFile?.filename || "") === ".md") { + if (!(await activeFile?.canRun())) return; + await openMarkdownPreview(activeFile); + return; + } + if (!isConsole && !runFile) { const { serverPort, previewPort, previewMode, disableCache, host } = appSettings.value; @@ -48,8 +60,6 @@ async function run( } } - /** @type {EditorFile} */ - const activeFile = isConsole ? null : editorManager.activeFile; if (!isConsole && !(await activeFile?.canRun())) return; if (!isConsole && !localStorage.__init_runPreview) { @@ -60,12 +70,16 @@ async function run( const uuid = helpers.uuid(); let isLoading = false; - let isFallback = false; let filename, pathName, extension; let port = appSettings.value.serverPort; - let EXECUTING_SCRIPT = uuid + "_script.js"; + let shouldExecuteScript = false; const MIMETYPE_HTML = mimeType.lookup("html"); const CONSOLE_SCRIPT = uuid + "_console.js"; + const CONSOLE_WORKER_SCRIPT = uuid + "_console_worker.js"; + // Keep this route independent of the filename because characters such as + // "#" and "?" change how browsers parse a URL. + const EXECUTING_SCRIPT = uuid + "_script.js"; + const CONSOLE_THEME_STYLE = uuid + "_console_theme.css"; const MARKDOWN_STYLE = uuid + "_md.css"; const queue = []; @@ -83,21 +97,11 @@ async function run( try { const fs = fsOperation(activeFile.uri); const res = await fs.readFile(); - let text = new TextDecoder().decode(res); - - if (!/^<\?xml/.test(text)) { - text = `\n` + text; - } - - const blob = new Blob([text], { type: mimeType.lookup(extension) }); - const url = URL.createObjectURL(blob); + const blob = new Blob([new Uint8Array(res)], { + type: mimeType.lookup(extension), + }); - box( - filename, - `
- ${filename} -
`, - ); + dialog(filename, ``); } catch (err) { helpers.error(err); } @@ -137,17 +141,17 @@ async function run( } function startConsole() { - if (!isConsole) EXECUTING_SCRIPT = activeFile.filename; + runConsole(); + start(); + } + + function runConsole() { + if (!isConsole) shouldExecuteScript = true; isConsole = true; target = "inapp"; filename = "console.html"; - - //this extra www is incorrect because asset_directory itself has www - //but keeping it in case something depends on it pathName = `${ASSETS_DIRECTORY}www/`; - port = constants.CONSOLE_PORT; - - start(); + port = config.CONSOLE_PORT; } function start() { @@ -165,7 +169,6 @@ async function run( } function startServer() { - //isFallback = true; webServer?.stop(); webServer = CreateServer(port, openBrowser, onError); webServer.setOnRequestHandler(handleRequest); @@ -186,19 +189,14 @@ async function run( * @param {string} req.requestId * @param {string} req.path */ - async function handleRequest(req) { + function handleRequest(req) { const reqId = req.requestId; let reqPath = req.path.substring(1); - console.log(`XREQPATH ${reqPath}`); - console.log(req); - - if (!reqPath || (reqPath.endsWith("/") && reqPath.length === 1)) { - reqPath = getRelativePath(); + if (!reqPath || reqPath.endsWith("/")) { + reqPath += "index.html"; } - console.log(`XREQPATH1 ${reqPath}`); - const ext = Url.extname(reqPath); let url = null; @@ -215,8 +213,25 @@ async function run( sendFileContent(url, reqId, "application/javascript"); break; + case CONSOLE_WORKER_SCRIPT: + url = `${ASSETS_DIRECTORY}/build/consoleWorker.js`; + sendFileContent(url, reqId, "application/javascript"); + break; + + case CONSOLE_THEME_STYLE: + sendText(getConsoleThemeSnapshot().css, reqId, "text/css"); + break; + + case CONSOLE_THEME_STATE: + sendText( + JSON.stringify(getConsoleThemeSnapshot()), + reqId, + "application/json", + ); + break; + case EXECUTING_SCRIPT: { - const text = activeFile?.session.getValue() || ""; + const text = getDocText(activeFile?.session?.doc); sendText(text, reqId, "application/javascript"); break; } @@ -238,7 +253,11 @@ async function run( sendText( mustache.render($_console, { CONSOLE_SCRIPT, - EXECUTING_SCRIPT, + CONSOLE_WORKER_SCRIPT, + CONSOLE_THEME_STYLE, + CONSOLE_THEME_STATE, + EXECUTING_SCRIPT: shouldExecuteScript ? EXECUTING_SCRIPT : null, + APP_THEME_TYPE: getConsoleThemeSnapshot().type, }), reqId, MIMETYPE_HTML, @@ -252,10 +271,10 @@ async function run( } } - if (activeFile.mode === "single") { + if (activeFile.SAFMode === "single") { if (filename === reqPath) { sendText( - activeFile.session.getValue(), + getDocText(activeFile.session?.doc), reqId, mimeType.lookup(filename), ); @@ -266,121 +285,60 @@ async function run( } let url = activeFile.uri; - let file = activeFile.SAFMode === "single" ? activeFile : null; if (pathName) { - const projectFolder = addedFolder[0]; - const query = url.split("?")[1]; - let rootFolder = ""; - - if ( - projectFolder !== undefined && - pathName.includes(projectFolder.url) - ) { - rootFolder = projectFolder.url; - } else { - rootFolder = pathName; - } - - if ( - (rootFolder.startsWith("ftp:") || rootFolder.startsWith("sftp:")) && - rootFolder.includes("?") - ) { - rootFolder = rootFolder.split("?")[0]; - } - - rootFolder = rootFolder.replace(/\/+$/, ""); // remove trailing slash - reqPath = reqPath.replace(/^\/+/, ""); // remove leading slash - - const rootParts = rootFolder.split("/"); - const pathParts = reqPath.split("/"); + url = Url.join(pathName, reqPath); + file = editorManager.getFile(url, "uri"); + } else if (!activeFile.uri && filename === reqPath) { + file = activeFile; + } - if (pathParts[0] === rootParts[rootParts.length - 1]) { - pathParts.shift(); - } + if (!url && !file) { + error(reqId); + return; + } - function removePrefix(str, prefix) { - if (str.startsWith(prefix)) { - return str.slice(prefix.length); - } - return str; + // Handle extensionless URLs (e.g., "about" -> "about.html" or "about/index.html") + if (!ext && pathName) { + // Try exact match first for extensionless files (LICENSE, README, etc.) + const exactUrl = Url.join(pathName, reqPath); + const exactFs = fsOperation(exactUrl); + if (await exactFs.exists()) { + sendFile(exactUrl, reqId); + return; } - function findOverlap(a, b) { - // Start with the smallest possible overlap (1 character) and increase - let maxOverlap = ""; - - // Check all possible overlapping lengths - for (let i = 1; i <= Math.min(a.length, b.length); i++) { - // Get the ending substring of a with length i - const endOfA = a.slice(-i); - // Get the starting substring of b with length i - const startOfB = b.slice(0, i); - - // If they match, we have a potential overlap - if (endOfA === startOfB) { - maxOverlap = endOfA; - } - } - - return maxOverlap; + // Try path.html + const htmlUrl = Url.join(pathName, reqPath + ".html"); + const htmlFile = editorManager.getFile(htmlUrl, "uri"); + if (htmlFile?.loaded && htmlFile.isUnsaved) { + sendHTML(getDocText(htmlFile.session?.doc), reqId); + return; } - - console.log(`RootFolder ${rootFolder}`); - console.log(`PARTS ${pathParts.join("/")}`); - - let fullPath; - // Skip overlap detection for GitHub URIs as it causes path corruption - if (rootFolder.startsWith("gh://")) { - fullPath = Url.join(rootFolder, pathParts.join("/")); - } else { - const overlap = findOverlap(rootFolder, pathParts.join("/")); - if (overlap !== "") { - fullPath = Url.join( - rootFolder, - removePrefix(pathParts.join("/"), overlap), - ); - } else { - fullPath = Url.join(rootFolder, pathParts.join("/")); - } + const htmlFs = fsOperation(htmlUrl); + if (await htmlFs.exists()) { + sendFileContent(htmlUrl, reqId, MIMETYPE_HTML); + return; } - console.log(`Full PATH ${fullPath}`); - - const urlFile = fsOperation(fullPath); - - // Skip stat check for GitHub URIs as they are handled differently - if (!fullPath.startsWith("gh://")) { - const stats = await urlFile.stat(); - - if (!stats.exists) { - error(reqId); - return; - } - - if (!stats.isFile) { - if (fullPath.endsWith("/")) { - fullPath += "index.html"; - } else { - fullPath += "/index.html"; - } - } + // Try path/index.html + const indexUrl = Url.join(pathName, reqPath, "index.html"); + const indexFs = fsOperation(indexUrl); + if (await indexFs.exists()) { + sendFileContent(indexUrl, reqId, MIMETYPE_HTML); + return; } - // Add back the query if present - url = query ? `${fullPath}?${query}` : fullPath; - - file = editorManager.getFile(url, "uri"); - } else if (!activeFile.uri) { - file = activeFile; + error(reqId); + return; } switch (ext) { case ".htm": case ".html": - if (file && file.loaded && file.isUnsaved) { - sendHTML(file.session.getValue(), reqId); + if (!url || (file && file.loaded && file.isUnsaved)) { + sendHTML(getDocText(file.session?.doc), reqId); } else { sendFileContent(url, reqId, MIMETYPE_HTML); } @@ -397,9 +355,7 @@ async function run( .toLowerCase() .replace(/[^a-z0-9]+/g, "-"), }) - .use(markdownItTaskLists) - .use(markdownItFootnote) - .render(file.session.getValue()); + .render(getDocText(file.session?.doc)); const doc = mustache.render($_markdown, { html, filename, @@ -410,16 +366,12 @@ async function run( break; default: - if (file && file.loaded && file.isUnsaved) { - if (file.filename.endsWith(".html")) { - sendHTML(file.session.getValue(), reqId); - } else { - sendText( - file.session.getValue(), - reqId, - mimeType.lookup(file.filename), - ); - } + if (!url || (file && file.loaded && file.isUnsaved)) { + sendText( + getDocText(file.session?.doc), + reqId, + mimeType.lookup(file.filename), + ); } else if (url) { if (reqPath === "favicon.ico") { sendIco(ASSETS_DIRECTORY, reqId); @@ -434,6 +386,13 @@ async function run( } } + function getConsoleThemeSnapshot() { + return { + css: document.head.querySelector("style#app-theme")?.textContent || "", + type: document.body.getAttribute("theme-type") || "dark", + }; + } + /** * Sends 404 error * @param {string} id @@ -451,7 +410,7 @@ async function run( * @param {string} reqId */ function sendIco(assets, reqId) { - const ico = Url.join(assets, "favicon.ico"); + const ico = Url.join(assets, "res/logo/favicon.ico"); sendFile(ico, reqId); } @@ -461,7 +420,8 @@ async function run( * @param {string} id */ function sendHTML(text, id) { - const js = ` + const js = ` + + + ${ + opts.npa + ? "" + : "" + } + + + `; + const div = document.createElement("div"); + div.innerHTML = html; + document.head.appendChild(div); + this.nodeScriptReplace(div); + this._loaded = true; + } else { + console.error("WebView does not appear to be setup correctly"); + } + + document.addEventListener("pause", () => { + this._historyCurrentHref = this.historyCurrentHref(); + this.historyRestoreOriginalHref(); + }); + + document.addEventListener("resume", () => { + if (this._historyCurrentHref) { + this.historyReplaceState(this._historyCurrentHref); + } + }); + } + + public addAd(options: { + element: HTMLElement; + slot: string; + format?: string; + fullWidth?: boolean; + html?: string; + }) { + const opts = { + format: "auto", + fullWidth: true, + ...options, + }; + if (this._loaded) { + let html = opts.html || ""; + if (!opts.html) { + html = ` + + + + `; + } + if (opts.element) { + opts.element.innerHTML = html; + this.nodeScriptReplace(opts.element); + return true; + } + } + return false; + } + + private nodeScriptReplace(node: any) { + if (this.isNodeScript(node) === true) { + node.parentNode.replaceChild(this.nodeScriptClone(node), node); + } else { + const children = node.childNodes; + for (let i = 0, len = children.length; i < len; i++) { + this.nodeScriptReplace(children[i]); + } + } + return node; + } + + private nodeScriptClone(node: any) { + const script = document.createElement("script"); + script.text = node.innerHTML; + const attrs = node.attributes; + for (let i = 0, len = attrs.length; i < len; i++) { + script.setAttribute(attrs[i].name, attrs[i].value); + } + return script; + } + + private isNodeScript(node: any) { + return node.tagName === "SCRIPT"; + } + + private historyReplaceState(url: string) { + if (!this._originalHref) { + this._originalHref = window.location.href; + } + if (this._loaded) { + window.history.replaceState(null, "", url); + } + } + + private historySetPage(page: string, parameters: Record = {}) { + const _parameters: string[] = []; + for (const name in parameters) { + _parameters.push(`${name}=${encodeURI(parameters[name])}`); + } + const url = `${page}${ + _parameters.length > 0 ? `?${_parameters.join("&")}` : "" + }`; + this.historyReplaceState(url); + return url; + } + + private historyOriginalHref() { + return this._originalHref || window.location.href; + } + + private historyCurrentHref() { + return window.location.href; + } + + private historyRestoreOriginalHref() { + this.historyReplaceState(this.historyOriginalHref()); + } + + public async show() { + if (!this._loaded) { + await this.load(); + } + + return super.show(); + } +} diff --git a/src/plugins/admob/src/www/common.ts b/src/plugins/admob/src/www/common.ts new file mode 100644 index 0000000000..a3c0f0e133 --- /dev/null +++ b/src/plugins/admob/src/www/common.ts @@ -0,0 +1,87 @@ +export const CordovaService = "AdMob"; + +export type CordovaAction = + | "adCreate" + | "adDestroy" + | "adHide" + | "adIsLoaded" + | "adLoad" + | "adShow" + | "bannerConfig" + | "configure" + | "privacyGatherConsent" + | "privacyGetState" + | "privacyResetForTesting" + | "privacyShowOptions" + | "ready" + | "start" + | "webviewGoto"; + +export enum Events { + adClick = "admob.ad.click", + adDismiss = "admob.ad.dismiss", + adImpression = "admob.ad.impression", + adLoad = "admob.ad.load", + adLoadFail = "admob.ad.loadfail", + adPaid = "admob.ad.paid", + adReward = "admob.ad.reward", + adShow = "admob.ad.show", + adShowFail = "admob.ad.showfail", + bannerSize = "admob.banner.size", + ready = "admob.ready", +} + +export type AdPaidEvent = { + adId: string; + adUnitId: string; + adFormat: string; + valueMicros: number; + currencyCode: string; + precision: number; + adSourceName?: string; + adSourceId?: string; + adSourceInstanceName?: string; + adSourceInstanceId?: string; + mediationGroupName?: string; + mediationABTestName?: string; + mediationABTestVariant?: string; +}; + +// biome-ignore lint/suspicious/noConstEnum: ignore +export const enum Platform { + android = "android", + ios = "ios", +} + +/** + * An enum that represents the maximum ad content rating for an app or ad request. + * @enum {string} + */ +type MaxAdContentRating = + | /** Content suitable for general audiences, including families. */ "G" + | /** Content suitable only for mature audiences. */ "MA" + | /** Content suitable for most audiences with parental guidance. */ "PG" + | /** Content suitable for teen and older audiences. */ "T" + | /** Content suitability is unspecified. */ ""; + +export interface RequestConfig { + maxAdContentRating?: MaxAdContentRating; + tagForChildDirectedTreatment?: boolean | null; + tagForUnderAgeOfConsent?: boolean | null; + testDeviceIds?: string[]; +} + +export interface AdMobConfig extends RequestConfig { + appMuted?: boolean; + appVolume?: number; + /** @deprecated Use publisherFirstPartyIDEnabled instead */ + sameAppKey?: boolean; + publisherFirstPartyIDEnabled?: boolean; +} + +/** @internal */ +export function execAsync(action: CordovaAction, args?: unknown[]) { + return new Promise((resolve, reject) => { + cordova.exec(resolve, reject, CordovaService, action, args); + }); +} diff --git a/src/plugins/admob/src/www/cordova.d.ts b/src/plugins/admob/src/www/cordova.d.ts new file mode 100644 index 0000000000..5d9ecc8f65 --- /dev/null +++ b/src/plugins/admob/src/www/cordova.d.ts @@ -0,0 +1,31 @@ +interface Cordova { + fireDocumentEvent(eventName: string, data?: unknown): void; +} + +declare module "cordova/channel" { + interface CordovaChannel { + createSticky(name: string): void; + initializationComplete(name: string): void; + onCordovaReady: { + subscribe(listener: () => void): void; + }; + waitForInitialization(name: string): void; + } + + const channel: CordovaChannel; + export default channel; +} + +declare module "cordova/exec" { + type Callback = (value: unknown) => unknown; + + function exec( + success: Callback, + fail: Callback, + service: string, + action: string, + args?: unknown[], + ): void; + + export default exec; +} diff --git a/src/plugins/admob/src/www/index.ts b/src/plugins/admob/src/www/index.ts new file mode 100644 index 0000000000..c30b9fb56e --- /dev/null +++ b/src/plugins/admob/src/www/index.ts @@ -0,0 +1,41 @@ +import * as ads from "./ads"; +import { type AdMobConfig, Events, execAsync } from "./common"; +import { Privacy } from "./privacy"; + +export * from "./ads"; +export * from "./common"; +export * from "./privacy"; + +export class AdMob { + public readonly AppOpenAd = ads.AppOpenAd; + public readonly BannerAd = ads.BannerAd; + public readonly InterstitialAd = ads.InterstitialAd; + public readonly NativeAd = ads.NativeAd; + public readonly RewardedAd = ads.RewardedAd; + public readonly RewardedInterstitialAd = ads.RewardedInterstitialAd; + public readonly WebViewAd = ads.WebViewAd; + + public readonly Events = Events; + public readonly privacy = new Privacy(); + + private _startPromise: ReturnType | undefined; + + configure(config: AdMobConfig) { + return execAsync("configure", [config]); + } + + public start() { + // biome-ignore lint/suspicious/noAssignInExpressions: ignore + return (this._startPromise ??= this._start()); + } + + private _start() { + return execAsync<{ version: string }>("start"); + } +} + +declare global { + const admob: AdMob; +} + +export default AdMob; diff --git a/src/plugins/admob/src/www/privacy.ts b/src/plugins/admob/src/www/privacy.ts new file mode 100644 index 0000000000..9c33e4357a --- /dev/null +++ b/src/plugins/admob/src/www/privacy.ts @@ -0,0 +1,45 @@ +import { execAsync } from "./common"; + +export type PrivacyConsentStatus = + | "unknown" + | "required" + | "notRequired" + | "obtained"; + +export type PrivacyConsentState = { + consentStatus: PrivacyConsentStatus; + canRequestAds: boolean; + privacyOptionsRequired: boolean; +}; + +export type ConsentDebugGeography = "disabled" | "eea" | "notEea"; + +export type GatherConsentOptions = { + /** + * Debug controls are rejected by native code in non-debuggable builds. + */ + debugGeography?: ConsentDebugGeography; + testDeviceIds?: string[]; +}; + +export class Privacy { + public gatherConsent(options: GatherConsentOptions = {}) { + return execAsync("privacyGatherConsent", [options]); + } + + public getState() { + return execAsync("privacyGetState", [{}]); + } + + public showOptions() { + return execAsync("privacyShowOptions", [{}]); + } + + /** + * Clears UMP state for first-install testing. Native code rejects this in + * non-debuggable builds. + */ + public resetForTesting() { + return execAsync("privacyResetForTesting", [{}]); + } +} diff --git a/src/plugins/admob/tsconfig.json b/src/plugins/admob/tsconfig.json new file mode 100644 index 0000000000..3aea297a18 --- /dev/null +++ b/src/plugins/admob/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "composite": true, + "outDir": "lib", + "rootDir": "src/www", + "target": "ES2015", + "module": "CommonJS", + "moduleResolution": "Node", + "lib": ["DOM", "ES2015"], + "strict": true, + "noImplicitAny": false, + "esModuleInterop": true, + "skipLibCheck": true + }, + "include": ["./src/www/cordova.d.ts", "./src/www/**/*"] +} diff --git a/src/plugins/admob/tsconfig.rollup.json b/src/plugins/admob/tsconfig.rollup.json new file mode 100644 index 0000000000..5437793319 --- /dev/null +++ b/src/plugins/admob/tsconfig.rollup.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "composite": false, + "declaration": false, + "module": "ESNext", + "outDir": "./node_modules/.cache/admob-rollup", + "sourceMap": false + } +} diff --git a/src/plugins/admob/www/admob.js b/src/plugins/admob/www/admob.js new file mode 100644 index 0000000000..3dc046dac2 --- /dev/null +++ b/src/plugins/admob/www/admob.js @@ -0,0 +1,564 @@ +'use strict'; + +var cordova$1 = require('cordova'); +var channel = require('cordova/channel'); +var exec = require('cordova/exec'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var cordova__namespace = /*#__PURE__*/_interopNamespaceDefault(cordova$1); + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +const CordovaService = "AdMob"; +var Events; +(function (Events) { + Events["adClick"] = "admob.ad.click"; + Events["adDismiss"] = "admob.ad.dismiss"; + Events["adImpression"] = "admob.ad.impression"; + Events["adLoad"] = "admob.ad.load"; + Events["adLoadFail"] = "admob.ad.loadfail"; + Events["adPaid"] = "admob.ad.paid"; + Events["adReward"] = "admob.ad.reward"; + Events["adShow"] = "admob.ad.show"; + Events["adShowFail"] = "admob.ad.showfail"; + Events["bannerSize"] = "admob.banner.size"; + Events["ready"] = "admob.ready"; +})(Events || (Events = {})); +/** @internal */ +function execAsync(action, args) { + return new Promise((resolve, reject) => { + cordova.exec(resolve, reject, CordovaService, action, args); + }); +} + +/** @internal */ +class MobileAd { + constructor(opts) { + var _a; + this._destroyed = false; + this.opts = opts; + this.id = (_a = opts.id) !== null && _a !== void 0 ? _a : opts.adUnitId; + MobileAd.allAds[this.id] = this; + } + static get allAds() { + const win = window; + if (typeof win.admobAds === "undefined") + win.admobAds = {}; + return win.admobAds; + } + static getAdById(id) { + return MobileAd.allAds[id]; + } + get adUnitId() { + return this.opts.adUnitId; + } + on(...args) { + const [eventName, cb, ...rest] = args; + const type = `admob.ad.${eventName.toLowerCase()}`; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + // biome-ignore lint/suspicious/noExplicitAny: + const listener = (evt) => { + if (evt.adId === this.id) { + cb(evt); + } + }; + document.addEventListener(type, listener, ...rest); + return () => { + document.removeEventListener(type, listener, ...rest); + }; + } + isLoaded() { + return __awaiter(this, void 0, void 0, function* () { + yield this.init(); + return execAsync("adIsLoaded", [{ id: this.id }]); + }); + } + load() { + return __awaiter(this, void 0, void 0, function* () { + yield this.init(); + // TODO read `opts` in native code? + yield execAsync("adLoad", [Object.assign(Object.assign({}, this.opts), { id: this.id })]); + }); + } + show(opts) { + return __awaiter(this, void 0, void 0, function* () { + yield this.init(); + return execAsync("adShow", [Object.assign(Object.assign({}, opts), { id: this.id })]); + }); + } + hide() { + return __awaiter(this, void 0, void 0, function* () { + yield this.init(); + return execAsync("adHide", [{ id: this.id }]); + }); + } + destroy() { + if (this._destroyPromise) + return this._destroyPromise; + this._destroyed = true; + if (MobileAd.allAds[this.id] === this) + delete MobileAd.allAds[this.id]; + this._destroyPromise = (() => __awaiter(this, void 0, void 0, function* () { + // Creation may already be in flight; dispose only after it settles. + if (this._initPromise) { + yield this._initPromise; + yield execAsync("adDestroy", [{ id: this.id }]); + } + }))(); + return this._destroyPromise; + } + init() { + return __awaiter(this, void 0, void 0, function* () { + var _a; + if (this._destroyed) + throw new Error("Ad is destroyed"); + // biome-ignore lint/suspicious/noAssignInExpressions: + yield ((_a = this._initPromise) !== null && _a !== void 0 ? _a : (this._initPromise = this._init())); + if (this._destroyed) + throw new Error("Ad is destroyed"); + }); + } + _init() { + return __awaiter(this, void 0, void 0, function* () { + var _a; + yield admob.start(); + if (this._destroyed) + return; + const cls = (_a = this.constructor.cls) !== null && _a !== void 0 ? _a : this.constructor.name; + return execAsync("adCreate", [Object.assign(Object.assign({}, this.opts), { id: this.id, cls })]); + }); + } +} + +class AppOpenAd extends MobileAd { + isLoaded() { + return super.isLoaded(); + } + load() { + return super.load(); + } + show() { + const _super = Object.create(null, { + show: { get: () => super.show } + }); + return __awaiter(this, void 0, void 0, function* () { + return _super.show.call(this); + }); + } +} +AppOpenAd.cls = "AppOpenAd"; + +var AdSizeType; +(function (AdSizeType) { + AdSizeType[AdSizeType["BANNER"] = 0] = "BANNER"; + AdSizeType[AdSizeType["LARGE_BANNER"] = 1] = "LARGE_BANNER"; + AdSizeType[AdSizeType["MEDIUM_RECTANGLE"] = 2] = "MEDIUM_RECTANGLE"; + AdSizeType[AdSizeType["FULL_BANNER"] = 3] = "FULL_BANNER"; + AdSizeType[AdSizeType["LEADERBOARD"] = 4] = "LEADERBOARD"; + /** @deprecated Use an adaptive BannerSize object instead. */ + AdSizeType[AdSizeType["SMART_BANNER"] = 5] = "SMART_BANNER"; +})(AdSizeType || (AdSizeType = {})); +const colorToRGBA = (() => { + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = 1; + const ctx = canvas.getContext("2d"); + if (!ctx) + return () => undefined; + return (col) => { + ctx.clearRect(0, 0, 1, 1); + // In order to detect invalid values, + // we can't rely on col being in the same format as what fillStyle is computed as, + // but we can ask it to implicitly compute a normalized value twice and compare. + ctx.fillStyle = "#000"; + ctx.fillStyle = col; + const computed = ctx.fillStyle; + ctx.fillStyle = "#fff"; + ctx.fillStyle = col; + if (computed !== ctx.fillStyle) { + return; // invalid color + } + ctx.fillRect(0, 0, 1, 1); + const { data } = ctx.getImageData(0, 0, 1, 1); + return { r: data[0], g: data[1], b: data[2], a: data[3] }; + }; +})(); +class BannerAd extends MobileAd { + constructor(opts) { + super(Object.assign({ position: "bottom", size: { adaptive: "anchored" } }, opts)); + } + static config(opts) { + if (cordova.platformId === "ios" /* Platform.ios */) { + const { backgroundColor: bgColor } = opts; + return execAsync("bannerConfig", [ + Object.assign(Object.assign({}, opts), { backgroundColor: bgColor ? colorToRGBA(bgColor) : bgColor }), + ]); + } + return false; + } + load() { + const _super = Object.create(null, { + load: { get: () => super.load } + }); + return __awaiter(this, void 0, void 0, function* () { + yield _super.load.call(this); + }); + } + show() { + const _super = Object.create(null, { + show: { get: () => super.show } + }); + return __awaiter(this, void 0, void 0, function* () { + yield this.load(); + return _super.show.call(this); + }); + } + hide() { + const _super = Object.create(null, { + hide: { get: () => super.hide } + }); + return __awaiter(this, void 0, void 0, function* () { + return _super.hide.call(this); + }); + } +} +BannerAd.cls = "BannerAd"; + +class InterstitialAd extends MobileAd { + isLoaded() { + return super.isLoaded(); + } + load() { + return super.load(); + } + show() { + return super.show(); + } +} +InterstitialAd.cls = "InterstitialAd"; + +class NativeAd extends MobileAd { + isLoaded() { + return super.isLoaded(); + } + hide() { + const _super = Object.create(null, { + hide: { get: () => super.hide } + }); + return __awaiter(this, void 0, void 0, function* () { + return _super.hide.call(this); + }); + } + load() { + return super.load(); + } + show(opts) { + const _super = Object.create(null, { + show: { get: () => super.show } + }); + return __awaiter(this, void 0, void 0, function* () { + return _super.show.call(this, Object.assign({ x: 0, y: 0, width: 0, height: 0 }, opts)); + }); + } + showWith(elm) { + return __awaiter(this, void 0, void 0, function* () { + const update = () => __awaiter(this, void 0, void 0, function* () { + const r = elm.getBoundingClientRect(); + yield this.show({ + x: r.x, + y: r.y, + width: r.width, + height: r.height, + }); + }); + const observer = new MutationObserver(update); + observer.observe(document.body, { + attributes: true, + childList: true, + subtree: true, + }); + document.addEventListener("scroll", update); + window.addEventListener("resize", update); + yield update(); + }); + } +} +NativeAd.cls = "NativeAd"; + +class RewardedAd extends MobileAd { + isLoaded() { + return super.isLoaded(); + } + load() { + return super.load(); + } + show() { + return super.show(); + } + /** Release an Android rewarded ad after dismissal or before presentation. */ + destroy() { + return super.destroy(); + } +} +RewardedAd.cls = "RewardedAd"; + +class RewardedInterstitialAd extends MobileAd { + isLoaded() { + return super.isLoaded(); + } + load() { + return super.load(); + } + show() { + return super.show(); + } +} +RewardedInterstitialAd.cls = "RewardedInterstitialAd"; + +class WebViewAd extends MobileAd { + static checkIntegration() { + return __awaiter(this, void 0, void 0, function* () { + yield execAsync("webviewGoto", [ + "https://webview-api-for-ads-test.glitch.me/", + ]); + }); + } + constructor(opts) { + var _a, _b, _c, _d, _e, _f, _g; + opts.adUnitId = ""; + super(opts); + this._loaded = false; + this._src = ""; + this._adsense = ""; + this._originalHref = window.location.href || ""; + this._historyCurrentHref = ""; + this._adsense = opts.adsense; + this._src = + opts.src || + "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"; + // biome-ignore lint/suspicious/noExplicitAny: + const win = window; + if (typeof ((_a = win.gmaSdk) === null || _a === void 0 ? void 0 : _a.getQueryInfo) === "function" || + typeof ((_d = (_c = (_b = win.webkit) === null || _b === void 0 ? void 0 : _b.messageHandlers) === null || _c === void 0 ? void 0 : _c.getGmaQueryInfo) === null || _d === void 0 ? void 0 : _d.postMessage) === + "function" || + typeof ((_g = (_f = (_e = win.webkit) === null || _e === void 0 ? void 0 : _e.messageHandlers) === null || _f === void 0 ? void 0 : _f.getGmaSig) === null || _g === void 0 ? void 0 : _g.postMessage) === "function") { + const html = ` + + ${opts.npa + ? "" + : ""} + + + `; + const div = document.createElement("div"); + div.innerHTML = html; + document.head.appendChild(div); + this.nodeScriptReplace(div); + this._loaded = true; + } + else { + console.error("WebView does not appear to be setup correctly"); + } + document.addEventListener("pause", () => { + this._historyCurrentHref = this.historyCurrentHref(); + this.historyRestoreOriginalHref(); + }); + document.addEventListener("resume", () => { + if (this._historyCurrentHref) { + this.historyReplaceState(this._historyCurrentHref); + } + }); + } + addAd(options) { + const opts = Object.assign({ format: "auto", fullWidth: true }, options); + if (this._loaded) { + let html = opts.html || ""; + if (!opts.html) { + html = ` + + + + `; + } + if (opts.element) { + opts.element.innerHTML = html; + this.nodeScriptReplace(opts.element); + return true; + } + } + return false; + } + nodeScriptReplace(node) { + if (this.isNodeScript(node) === true) { + node.parentNode.replaceChild(this.nodeScriptClone(node), node); + } + else { + const children = node.childNodes; + for (let i = 0, len = children.length; i < len; i++) { + this.nodeScriptReplace(children[i]); + } + } + return node; + } + nodeScriptClone(node) { + const script = document.createElement("script"); + script.text = node.innerHTML; + const attrs = node.attributes; + for (let i = 0, len = attrs.length; i < len; i++) { + script.setAttribute(attrs[i].name, attrs[i].value); + } + return script; + } + isNodeScript(node) { + return node.tagName === "SCRIPT"; + } + historyReplaceState(url) { + if (!this._originalHref) { + this._originalHref = window.location.href; + } + if (this._loaded) { + window.history.replaceState(null, "", url); + } + } + historySetPage(page, parameters = {}) { + const _parameters = []; + for (const name in parameters) { + _parameters.push(`${name}=${encodeURI(parameters[name])}`); + } + const url = `${page}${_parameters.length > 0 ? `?${_parameters.join("&")}` : ""}`; + this.historyReplaceState(url); + return url; + } + historyOriginalHref() { + return this._originalHref || window.location.href; + } + historyCurrentHref() { + return window.location.href; + } + historyRestoreOriginalHref() { + this.historyReplaceState(this.historyOriginalHref()); + } + show() { + const _super = Object.create(null, { + show: { get: () => super.show } + }); + return __awaiter(this, void 0, void 0, function* () { + if (!this._loaded) { + yield this.load(); + } + return _super.show.call(this); + }); + } +} +WebViewAd.cls = "WebViewAd"; + +class Privacy { + gatherConsent(options = {}) { + return execAsync("privacyGatherConsent", [options]); + } + getState() { + return execAsync("privacyGetState", [{}]); + } + showOptions() { + return execAsync("privacyShowOptions", [{}]); + } + /** + * Clears UMP state for first-install testing. Native code rejects this in + * non-debuggable builds. + */ + resetForTesting() { + return execAsync("privacyResetForTesting", [{}]); + } +} + +class AdMob { + constructor() { + this.AppOpenAd = AppOpenAd; + this.BannerAd = BannerAd; + this.InterstitialAd = InterstitialAd; + this.NativeAd = NativeAd; + this.RewardedAd = RewardedAd; + this.RewardedInterstitialAd = RewardedInterstitialAd; + this.WebViewAd = WebViewAd; + this.Events = Events; + this.privacy = new Privacy(); + } + configure(config) { + return execAsync("configure", [config]); + } + start() { + var _a; + // biome-ignore lint/suspicious/noAssignInExpressions: ignore + return ((_a = this._startPromise) !== null && _a !== void 0 ? _a : (this._startPromise = this._start())); + } + _start() { + return execAsync("start"); + } +} + +const admob$1 = new AdMob(); +// biome-ignore lint/suspicious/noExplicitAny: ignore +function onMessageFromNative(event) { + const { data } = event; + if (data === null || data === void 0 ? void 0 : data.adId) { + data.ad = MobileAd.getAdById(data.adId); + } + cordova__namespace.fireDocumentEvent(event.type, data); +} +const feature = "onAdMobPlusReady"; +channel.createSticky(feature); +channel.waitForInitialization(feature); +channel.onCordovaReady.subscribe(() => { + const action = "ready"; + exec(onMessageFromNative, console.error, CordovaService, action, []); + channel.initializationComplete(feature); +}); + +module.exports = admob$1; diff --git a/src/plugins/auth/package.json b/src/plugins/auth/package.json new file mode 100644 index 0000000000..584bc37c9c --- /dev/null +++ b/src/plugins/auth/package.json @@ -0,0 +1,17 @@ +{ + "name": "com.foxdebug.acode.rk.auth", + "version": "1.0.0", + "description": "Authentication plugin", + "cordova": { + "id": "com.foxdebug.acode.rk.auth", + "platforms": [ + "android" + ] + }, + "keywords": [ + "ecosystem:cordova", + "cordova-android" + ], + "author": "@RohitKushvaha01", + "license": "MIT" +} \ No newline at end of file diff --git a/src/plugins/auth/plugin.xml b/src/plugins/auth/plugin.xml new file mode 100644 index 0000000000..f8ed0e675e --- /dev/null +++ b/src/plugins/auth/plugin.xml @@ -0,0 +1,22 @@ + + + Authentication + + + + + + + + + + + + + + + + + + + diff --git a/src/plugins/auth/src/android/Authenticator.java b/src/plugins/auth/src/android/Authenticator.java new file mode 100644 index 0000000000..54f754415f --- /dev/null +++ b/src/plugins/auth/src/android/Authenticator.java @@ -0,0 +1,311 @@ +package com.foxdebug.acode.rk.auth; + +import android.content.Intent; +import android.net.Uri; +import android.util.Log; +import android.webkit.CookieManager; +import android.webkit.WebView; +import androidx.browser.customtabs.CustomTabsIntent; +import com.foxdebug.acode.rk.auth.EncryptedPreferenceManager; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import org.apache.cordova.*; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class Authenticator extends CordovaPlugin { + private static final String TAG = "AcodeAuth"; + private static final String PREFS_FILENAME = "acode_auth_secure"; + private static final String KEY_TOKEN = "auth_token"; + private static final String PRO_PURCHASED = "pro_purchased"; + private static final String KEY_MIGRATED_V2 = "migrated_host_to_domain_cookies"; + private static final String KEY_PENDING_STATE = "pending_login_state"; + private static final String KEY_PENDING_VERIFIER = "pending_login_verifier"; + private static final String KEY_PENDING_BASE_URL = "pending_login_base_url"; + private static final int AUTH_CONNECT_TIMEOUT_MS = 15_000; + private static final int AUTH_READ_TIMEOUT_MS = 30_000; + private static final String[] API_ORIGINS = { + "https://acode.app" + }; + private static final String[] LEGACY_ORIGINS = { + "https://acode.app", + "https://dev.acode.app" + }; + private EncryptedPreferenceManager prefManager; + private final Object loginCallbackLock = new Object(); + private volatile CallbackContext loginCallback; + + @Override + protected void pluginInitialize() { + Log.d(TAG, "Initializing Authenticator Plugin..."); + this.prefManager = new EncryptedPreferenceManager(this.cordova.getContext(), PREFS_FILENAME); + + WebView androidWebView = (WebView) webView.getView(); + CookieManager.getInstance().setAcceptThirdPartyCookies(androidWebView, true); + + if (!prefManager.getBoolean(KEY_MIGRATED_V2, false)) { + Log.d(TAG, "Migrating: clearing legacy host-scoped cookies"); + clearLegacyCookies(); + prefManager.setBoolean(KEY_MIGRATED_V2, true); + } + + String token = prefManager.getString(KEY_TOKEN, ""); + if (!token.isEmpty()) { + setTokenCookie(token); + } + + handleAuthCallback(cordova.getActivity().getIntent()); + } + + @Override + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + Log.i(TAG, "Native Action Called: " + action); + + switch (action) { + case "logout": + prefManager.remove(KEY_TOKEN); + cordova.getActivity().runOnUiThread(() -> clearTokenCookie()); + if (callbackContext != null) callbackContext.success(); + return true; + case "saveToken": + String token = args.getString(0); + Log.d(TAG, "Saving new token..."); + prefManager.setString(KEY_TOKEN, token); + cordova.getActivity().runOnUiThread(() -> setTokenCookie(token)); + callbackContext.success(); + return true; + case "login": + JSONObject options = args.optJSONObject(0); + startLogin(options != null ? options : new JSONObject(), callbackContext); + return true; + default: + Log.w(TAG, "Attempted to call unknown action: " + action); + return false; + } + } + + @Override + public void onNewIntent(Intent intent) { + if (!handleAuthCallback(intent)) { + super.onNewIntent(intent); + } + } + + private void startLogin(JSONObject options, CallbackContext callbackContext) { + String baseUrl = options.optString("baseUrl", "https://acode.app"); + int appVersionCode = options.optInt("appVersionCode", 0); + String state = randomHex(24); + String verifier = randomHex(32); + String challenge = sha256Hex(verifier); + + prefManager.setString(KEY_PENDING_STATE, state); + prefManager.setString(KEY_PENDING_VERIFIER, verifier); + prefManager.setString(KEY_PENDING_BASE_URL, baseUrl); + setLoginCallback(callbackContext); + + Uri loginUri = Uri.parse(baseUrl) + .buildUpon() + .appendEncodedPath("login") + .appendQueryParameter("redirect", "app") + .appendQueryParameter("authFlow", "app-code") + .appendQueryParameter("state", state) + .appendQueryParameter("challenge", challenge) + .appendQueryParameter("appVersionCode", String.valueOf(appVersionCode)) + .build(); + + cordova.getActivity().runOnUiThread(() -> { + try { + CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build(); + customTabsIntent.intent.putExtra(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE, CustomTabsIntent.SHOW_PAGE_TITLE); + customTabsIntent.launchUrl(cordova.getActivity(), loginUri); + + PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); + result.setKeepCallback(true); + callbackContext.sendPluginResult(result); + } catch (Exception error) { + Intent fallback = new Intent(Intent.ACTION_VIEW, loginUri); + try { + cordova.getActivity().startActivity(fallback); + PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); + result.setKeepCallback(true); + callbackContext.sendPluginResult(result); + } catch (Exception fallbackError) { + failLogin(fallbackError.getMessage()); + } + } + }); + } + + private boolean handleAuthCallback(Intent intent) { + Uri data = intent != null ? intent.getData() : null; + if (data == null || !"acode".equals(data.getScheme()) || !"auth".equals(data.getHost()) || !"/callback".equals(data.getPath())) { + return false; + } + + String code = data.getQueryParameter("code"); + String state = data.getQueryParameter("state"); + String expectedState = prefManager.getString(KEY_PENDING_STATE, ""); + String verifier = prefManager.getString(KEY_PENDING_VERIFIER, ""); + String baseUrl = prefManager.getString(KEY_PENDING_BASE_URL, "https://acode.app"); + + if (code == null || state == null || expectedState.isEmpty() || verifier.isEmpty() || !expectedState.equals(state)) { + failLogin("Invalid login callback"); + return true; + } + + cordova.getThreadPool().execute(() -> { + try { + String token = exchangeCode(baseUrl, code, state, verifier); + prefManager.setString(KEY_TOKEN, token); + prefManager.remove(KEY_PENDING_STATE); + prefManager.remove(KEY_PENDING_VERIFIER); + prefManager.remove(KEY_PENDING_BASE_URL); + cordova.getActivity().runOnUiThread(() -> setTokenCookie(token)); + CallbackContext callback = takeLoginCallback(); + if (callback != null) { + callback.success(); + } + } catch (Exception error) { + Log.e(TAG, "Failed to exchange app auth code", error); + failLogin("Unable to complete login"); + } + }); + + return true; + } + + private String exchangeCode(String baseUrl, String code, String state, String verifier) throws Exception { + URL url = new URL(baseUrl + "/api/user/app-token/exchange"); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + try { + connection.setConnectTimeout(AUTH_CONNECT_TIMEOUT_MS); + connection.setReadTimeout(AUTH_READ_TIMEOUT_MS); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setDoOutput(true); + + JSONObject body = new JSONObject(); + body.put("code", code); + body.put("state", state); + body.put("verifier", verifier); + + try (OutputStream os = connection.getOutputStream()) { + os.write(body.toString().getBytes(StandardCharsets.UTF_8)); + } + + int status = connection.getResponseCode(); + InputStream stream = status >= 200 && status < 300 ? connection.getInputStream() : connection.getErrorStream(); + String response = readStream(stream); + + if (status < 200 || status >= 300) { + throw new IllegalStateException(response); + } + + JSONObject json = new JSONObject(response); + String token = json.optString("token", ""); + if (token.isEmpty()) { + throw new IllegalStateException("Missing token"); + } + + return token; + } finally { + connection.disconnect(); + } + } + + private String readStream(InputStream stream) throws Exception { + if (stream == null) return ""; + StringBuilder builder = new StringBuilder(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + builder.append(line); + } + } + return builder.toString(); + } + + private void failLogin(String message) { + prefManager.remove(KEY_PENDING_STATE); + prefManager.remove(KEY_PENDING_VERIFIER); + prefManager.remove(KEY_PENDING_BASE_URL); + CallbackContext callback = takeLoginCallback(); + if (callback != null) { + callback.error(message); + } + } + + private void setLoginCallback(CallbackContext callbackContext) { + CallbackContext previousCallback = null; + synchronized (loginCallbackLock) { + previousCallback = loginCallback; + loginCallback = callbackContext; + } + if (previousCallback != null) { + previousCallback.error("Login cancelled"); + } + } + + private CallbackContext takeLoginCallback() { + synchronized (loginCallbackLock) { + CallbackContext callback = loginCallback; + loginCallback = null; + return callback; + } + } + + private String randomHex(int byteCount) { + byte[] bytes = new byte[byteCount]; + new SecureRandom().nextBytes(bytes); + StringBuilder builder = new StringBuilder(byteCount * 2); + for (byte b : bytes) { + builder.append(String.format("%02x", b)); + } + return builder.toString(); + } + + private String sha256Hex(String value) { + try { + byte[] hash = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); + StringBuilder builder = new StringBuilder(hash.length * 2); + for (byte b : hash) { + builder.append(String.format("%02x", b)); + } + return builder.toString(); + } catch (Exception error) { + throw new IllegalStateException("Unable to create auth challenge", error); + } + } + + private void setTokenCookie(String token) { + CookieManager cm = CookieManager.getInstance(); + for (String origin : API_ORIGINS) { + cm.setCookie(origin, "token=" + token + "; Domain=.acode.app; Path=/; Secure; HttpOnly; SameSite=None"); + } + cm.flush(); + } + + private void clearTokenCookie() { + CookieManager cm = CookieManager.getInstance(); + for (String origin : API_ORIGINS) { + cm.setCookie(origin, "token=; Domain=.acode.app; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=None"); + } + cm.flush(); + } + + private void clearLegacyCookies() { + CookieManager cm = CookieManager.getInstance(); + for (String origin : LEGACY_ORIGINS) { + cm.setCookie(origin, "token=; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=None"); + } + cm.flush(); + } +} diff --git a/src/plugins/auth/src/android/EncryptedPreferenceManager.java b/src/plugins/auth/src/android/EncryptedPreferenceManager.java new file mode 100644 index 0000000000..51a32a19ff --- /dev/null +++ b/src/plugins/auth/src/android/EncryptedPreferenceManager.java @@ -0,0 +1,100 @@ +package com.foxdebug.acode.rk.auth; + +import android.content.Context; +import android.content.SharedPreferences; +import androidx.security.crypto.EncryptedSharedPreferences; +import androidx.security.crypto.MasterKeys; +import java.io.IOException; +import java.security.GeneralSecurityException; + +public class EncryptedPreferenceManager { + private final SharedPreferences sharedPreferences; + + /** + * @param context The Android Context + * @param prefName The custom name for your preference file (e.g., "user_session") + */ + public EncryptedPreferenceManager(Context context, String prefName) { + this(context, prefName, true); + } + + /** + * @param context The Android Context + * @param prefName The custom name for your preference file + * @param allowPlaintextFallback Whether storage may fall back to ordinary + * SharedPreferences when encryption is unavailable + */ + public EncryptedPreferenceManager( + Context context, + String prefName, + boolean allowPlaintextFallback + ) { + SharedPreferences preferences; + try { + String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC); + + // EncryptedSharedPreferences handles encryption of both Keys and Values + preferences = EncryptedSharedPreferences.create( + prefName, + masterKeyAlias, + context, + EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, + EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM + ); + } catch (GeneralSecurityException | IOException e) { + if (!allowPlaintextFallback) { + throw new IllegalStateException("Encrypted preferences are unavailable", e); + } + + // Preserve the existing behavior for legacy callers unless strict mode is requested. + preferences = context.getSharedPreferences(prefName, Context.MODE_PRIVATE); + } + sharedPreferences = preferences; + } + + // --- Reusable Methods --- + + public void setString(String key, String value) { + sharedPreferences.edit().putString(key, value).apply(); + } + + public boolean setStringSync(String key, String value) { + return sharedPreferences.edit().putString(key, value).commit(); + } + + public String getString(String key, String defaultValue) { + return sharedPreferences.getString(key, defaultValue); + } + + public void setInt(String key, int value) { + sharedPreferences.edit().putInt(key, value).apply(); + } + + public int getInt(String key, int defaultValue) { + return sharedPreferences.getInt(key, defaultValue); + } + + public void setBoolean(String key, boolean value) { + sharedPreferences.edit().putBoolean(key, value).apply(); + } + + public boolean getBoolean(String key, boolean defaultValue) { + return sharedPreferences.getBoolean(key, defaultValue); + } + + public void remove(String key) { + sharedPreferences.edit().remove(key).apply(); + } + + public boolean removeSync(String key) { + return sharedPreferences.edit().remove(key).commit(); + } + + public boolean exists(String key) { + return sharedPreferences.contains(key); + } + + public void clear() { + sharedPreferences.edit().clear().apply(); + } +} diff --git a/src/plugins/browser/android/com/foxdebug/browser/Browser.java b/src/plugins/browser/android/com/foxdebug/browser/Browser.java index f12597159b..bd0d4ab93d 100644 --- a/src/plugins/browser/android/com/foxdebug/browser/Browser.java +++ b/src/plugins/browser/android/com/foxdebug/browser/Browser.java @@ -227,6 +227,7 @@ public void onDownloadStart(String url, String userAgent, createMenu(); addView(titleLayout); addView(webViewContainer); + restoreEmulator(); } private void createMenu() { @@ -236,6 +237,10 @@ private void createMenu() { menu.addItem(Ui.Icons.DEVICES, "Devices", false); menu.addItem(Ui.Icons.NO_CACHE, "Disable Cache", false); menu.addItem(Ui.Icons.TERMINAL, "Console", false); + menu.addItem(Ui.Icons.TUNE, "Set as Default"); + menu.addItem(Ui.Icons.REFRESH, "Clear Default"); + menu.setVisible("Set as Default", false); + menu.setVisible("Clear Default", false); menu.addItem(Ui.Icons.OPEN_IN_BROWSER, "Open in Browser"); menu.addItem(Ui.Icons.EXIT, "Exit"); @@ -250,6 +255,7 @@ public void onSelect(String action, Boolean checked) { } emulator = checked; + updateDefaultItems(checked); if (checked) { setDesktopMode(true); setConsoleVisible(false); @@ -284,6 +290,26 @@ public void onGlobalLayout() { case "Console": setConsoleVisible(checked); break; + case "Set as Default": + if (deviceEmulator != null) { + deviceEmulator.saveAsDefault(); + updateDefaultItems(emulator); + Toast + .makeText( + context, + "Saved as default preview", + Toast.LENGTH_SHORT + ) + .show(); + } + break; + case "Clear Default": + Emulator.clearDefault(context); + updateDefaultItems(emulator); + Toast + .makeText(context, "Default cleared", Toast.LENGTH_SHORT) + .show(); + break; case "Disable Cache": webView .getSettings() @@ -308,6 +334,75 @@ public void onGlobalLayout() { ); } + private void updateDefaultItems(boolean emulatorOn) { + menu.setVisible("Set as Default", emulatorOn); + menu.setVisible( + "Clear Default", + emulatorOn && Emulator.hasDefault(context) + ); + } + + private void reloadAfterLayout() { + // If no page was requested yet, the first load will already happen at + // the saved size, so there is nothing to reload. + if (url.isEmpty()) return; + + webView + .getViewTreeObserver() + .addOnGlobalLayoutListener( + new ViewTreeObserver.OnGlobalLayoutListener() { + @Override + public void onGlobalLayout() { + webView.getViewTreeObserver().removeOnGlobalLayoutListener(this); + webView.reload(); + } + } + ); + } + + private void restoreEmulator() { + if (onlyConsole) return; + if (!Emulator.hasDefault(context)) return; + + // Apply the saved mode before the first navigation so the page is not + // loaded with the wrong user agent and then reloaded. + setDesktopMode(true, false); + + webView + .getViewTreeObserver() + .addOnGlobalLayoutListener( + new ViewTreeObserver.OnGlobalLayoutListener() { + @Override + public void onGlobalLayout() { + if (webView.getMeasuredWidth() == 0) return; + webView.getViewTreeObserver().removeOnGlobalLayoutListener(this); + + if (deviceEmulator == null) { + createDeviceEmulatorLayout(); + deviceEmulator.setRestoredListener( + new Runnable() { + @Override + public void run() { + reloadAfterLayout(); + } + } + ); + } + + emulator = true; + menu.setChecked("Devices", true); + updateDefaultItems(true); + setConsoleVisible(false); + menu.setChecked("Console", false); + menu.setVisible("Console", false); + addView(deviceEmulator); + // The emulator sets up its sliders on a later layout pass and then + // applies the saved size itself, so the webview is not resized here. + } + } + ); + } + private void createDeviceEmulatorLayout() { Browser browser = this; deviceEmulator = new Emulator(context, theme); @@ -339,6 +434,10 @@ private void setTextViewProperties(TextView textView, int height) { } private void setDesktopMode(boolean enabled) { + setDesktopMode(enabled, true); + } + + private void setDesktopMode(boolean enabled, boolean reload) { int width = 0; int height = 0; WebSettings webSettings = webView.getSettings(); @@ -360,7 +459,9 @@ private void setDesktopMode(boolean enabled) { webSettings.setLoadWithOverviewMode(enabled); webSettings.setSupportZoom(enabled); webSettings.setBuiltInZoomControls(enabled); - webView.reload(); + if (reload) { + webView.reload(); + } } public void setDesktopMode() { diff --git a/src/plugins/browser/android/com/foxdebug/browser/BrowserActivity.java b/src/plugins/browser/android/com/foxdebug/browser/BrowserActivity.java index eaec867f13..ddca862409 100644 --- a/src/plugins/browser/android/com/foxdebug/browser/BrowserActivity.java +++ b/src/plugins/browser/android/com/foxdebug/browser/BrowserActivity.java @@ -3,12 +3,15 @@ import android.app.Activity; import android.content.Intent; import android.graphics.Color; +import android.graphics.Insets; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; +import android.view.WindowInsets; import android.view.WindowInsetsController; +import android.view.WindowManager; import android.webkit.WebChromeClient; import com.foxdebug.system.Ui; import org.json.JSONObject; @@ -37,6 +40,37 @@ public void onCreate(Bundle savedInstanceState) { browser = new Browser(this, theme, onlyConsole); browser.setUrl(url); setContentView(browser); + + // Match Acode's editor behavior: the console WebView itself is resized when + // the software keyboard opens, so DOM viewport units and resize events work. + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE + ); + + if (Build.VERSION.SDK_INT >= 30) { + if (onlyConsole) { + getWindow().setDecorFitsSystemWindows(true); + } else { + getWindow().setDecorFitsSystemWindows(false); + + browser.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() { + @Override + public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) { + Insets systemBarsInsets = insets.getInsets(WindowInsets.Type.systemBars()); + Insets imeInsets = insets.getInsets(WindowInsets.Type.ime()); + int bottomInset = Math.max(systemBarsInsets.bottom, imeInsets.bottom); + v.setPadding( + systemBarsInsets.left, + systemBarsInsets.top, + systemBarsInsets.right, + bottomInset + ); + return WindowInsets.CONSUMED; + } + }); + } + } + setSystemTheme(theme.get("primaryColor")); } @@ -85,8 +119,14 @@ private void setSystemTheme(int systemBarColor) { controller.setSystemBarsAppearance(0, appearance); } } - } catch (IllegalArgumentException ignore) {} catch (Exception ignore) {} - } catch (Exception e) {} + } catch (IllegalArgumentException error) { + Log.w("BrowserActivity", "Invalid system bar color or appearance input.", error); + } catch (Exception error) { + Log.w("BrowserActivity", "Failed applying system bar theme values.", error); + } + } catch (Exception e) { + Log.e("BrowserActivity", "Failed to apply system theme.", e); + } } private void setStatusBarStyle(final Window window) { diff --git a/src/plugins/browser/android/com/foxdebug/browser/Emulator.java b/src/plugins/browser/android/com/foxdebug/browser/Emulator.java index adb65f2b1f..25f0d70eae 100644 --- a/src/plugins/browser/android/com/foxdebug/browser/Emulator.java +++ b/src/plugins/browser/android/com/foxdebug/browser/Emulator.java @@ -163,6 +163,8 @@ public void onGlobalLayout() { if (listener != null) { listener.onChange(iWidth, correctedHeight, 1); } + + restoreDefaultDevice(); } } ); @@ -302,6 +304,108 @@ private void selectDevice(Device device) { listener.onChange(width, height, maxScale / 100f); } + public static boolean hasDefault(Context context) { + return context + .getSharedPreferences("acode_browser", Context.MODE_PRIVATE) + .getBoolean("default_set", false); + } + + public static void clearDefault(Context context) { + context + .getSharedPreferences("acode_browser", Context.MODE_PRIVATE) + .edit() + .putBoolean("default_set", false) + .apply(); + } + + public void saveAsDefault() { + context + .getSharedPreferences("acode_browser", Context.MODE_PRIVATE) + .edit() + .putBoolean("default_set", true) + .putInt("default_width", getWidthProgress()) + .putInt("default_height", getHeightProgress()) + .putInt("default_scale", seekBars.get("scale").getProgress()) + .putString( + "default_device", + selectedDevice != null ? selectedDevice.name : "Custom" + ) + .apply(); + } + + private Runnable restoredListener; + + public void setRestoredListener(Runnable listener) { + restoredListener = listener; + } + + private void restoreDefaultDevice() { + if (!hasDefault(context)) return; + + android.content.SharedPreferences prefs = context.getSharedPreferences( + "acode_browser", + Context.MODE_PRIVATE + ); + SeekBar widthSeekBar = seekBars.get("width"); + SeekBar heightSeekBar = seekBars.get("height"); + SeekBar scaleSeekBar = seekBars.get("scale"); + String name = prefs.getString("default_device", "Custom"); + + Device preset = null; + for (Device device : deviceListView.devices) { + if (device.id != customDevice.id && device.name.equals(name)) { + preset = device; + break; + } + } + + if (preset != null && listener != null) { + // A preset is re-fitted to the current screen, so it keeps its shape if + // the screen size changed since it was saved (rotation, split-screen, + // foldables). Only the scale is restored from the saved value. + if (deviceListView.selectedDeviceView != null) { + deviceListView.selectedDeviceView.deselect(); + } + deviceListView.select(preset); + selectDevice(preset); + + int scale = Math.min( + prefs.getInt("default_scale", scaleSeekBar.getMax()), + scaleSeekBar.getMax() + ); + scaleSeekBar.setProgress(scale); + listener.onChange(getWidthProgress(), getHeightProgress(), scale / 100f); + } else { + // Custom sizes are restored from the saved width/height. + int width = Math.min( + prefs.getInt("default_width", widthSeekBar.getMax()), + widthSeekBar.getMax() + ); + int height = Math.min( + prefs.getInt("default_height", heightSeekBar.getMax()), + heightSeekBar.getMax() + ); + + widthSeekBar.setProgress(width); + heightSeekBar.setProgress(height); + setMaxScale(width, height); + int scale = Math.min( + prefs.getInt("default_scale", 100), + scaleSeekBar.getMax() + ); + scaleSeekBar.setProgress(scale); + selectedDevice = customDevice; + + if (listener != null) { + listener.onChange(width, height, scale / 100f); + } + } + + if (restoredListener != null) { + restoredListener.run(); + } + } + private void setMaxScale(int width, int height) { SeekBar scaleSeekBar = seekBars.get("scale"); SeekBar widthSeekBar = seekBars.get("width"); @@ -367,6 +471,7 @@ public void deselect() { class DeviceListView extends ScrollView { DeviceView selectedDeviceView; + ArrayList devices = new ArrayList(); LinearLayout deviceListLayout; Callback callback; Context context; @@ -407,6 +512,7 @@ public void select(Device device) { } public void add(Device device) { + devices.add(device); DeviceView deviceView = new DeviceView(context, device, theme); deviceListLayout.addView(deviceView); diff --git a/src/plugins/browser/utils/updatePackage.js b/src/plugins/browser/utils/updatePackage.js index 2850414a75..eb2ade1644 100644 --- a/src/plugins/browser/utils/updatePackage.js +++ b/src/plugins/browser/utils/updatePackage.js @@ -1,30 +1,58 @@ -const fs = require('fs'); -const path = require('path'); +const fs = require("fs"); +const path = require("path"); const configXML = path.resolve(__dirname, "../../../config.xml"); -const menuJava = path.resolve(__dirname, "../../../platforms/android/app/src/main/java/com/foxdebug/browser/Menu.java"); -const repeatChar = (char, times) => { - let res = ""; - while (--times >= 0) res += char; - return res; -}; +const menuJava = path.resolve( + __dirname, + "../../../platforms/android/app/src/main/java/com/foxdebug/browser/Menu.java" +); +const docProvider = path.resolve( + __dirname, + "../../../platforms/android/app/src/main/java/com/foxdebug/acode/rk/exec/terminal/AlpineDocumentProvider.java" +); + +const repeatChar = (char, times) => char.repeat(times); + +function replaceImport(filePath, appName) { + if (!fs.existsSync(filePath)) { + console.warn(`⚠ File not found: ${filePath}`); + return; + } + + const data = fs.readFileSync(filePath, "utf8"); + + const updated = data.replace( + /(import\s+com\.foxdebug\.)(acode|acodefree)(\.R;)/, + `$1${appName}$3` + ); + + fs.writeFileSync(filePath, updated); +} try { + if (!fs.existsSync(configXML)) { + throw new Error("config.xml not found"); + } + const config = fs.readFileSync(configXML, "utf8"); - const fileData = fs.readFileSync(menuJava, "utf8"); - const appName = /widget id="([0-9a-zA-Z\.\-_]*)"/.exec(config)[1].split(".").pop(); - const newFileData = fileData.replace(/(import com\.foxdebug\.)(acode|acodefree)(.R;)/, `$1${appName}$3`); - fs.writeFileSync(menuJava, newFileData); + const match = /widget\s+id="([0-9a-zA-Z.\-_]+)"/.exec(config); + + if (!match) { + throw new Error("Could not extract widget id from config.xml"); + } + + const appName = match[1].split(".").pop(); + + replaceImport(docProvider, appName); + replaceImport(menuJava, appName); const msg = `==== Changed package to com.foxdebug.${appName} ====`; - console.log(""); - console.log(repeatChar("=", msg.length)); + console.log("\n" + repeatChar("=", msg.length)); console.log(msg); - console.log(repeatChar("=", msg.length)); - console.log(""); + console.log(repeatChar("=", msg.length) + "\n"); } catch (error) { - console.error(error); + console.error("❌ Error:", error.message); process.exit(1); } \ No newline at end of file diff --git a/src/plugins/cordova-plugin-advanced-http/package-lock.json b/src/plugins/cordova-plugin-advanced-http/package-lock.json new file mode 100644 index 0000000000..98346bf193 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/package-lock.json @@ -0,0 +1,4161 @@ +{ + "name": "cordova-plugin-advanced-http", + "version": "3.3.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "cordova-plugin-advanced-http", + "version": "3.3.1", + "engines": [ + { + "name": "cordova", + "version": ">=4.0.0" + } + ], + "license": "MIT", + "devDependencies": { + "chai": "4.3.6", + "colors": "1.4.0", + "cordova": "13.0.0", + "mocha": "9.2.2", + "umd-tough-cookie": "3.0.0", + "xml2js": "0.4.23" + } + }, + "node_modules/@gar/promise-retry": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@gar/promise-retry/-/promise-retry-1.0.3.tgz", + "integrity": "sha512-GmzA9ckNokPypTg10pgpeHNQe7ph+iIKKmhKu3Ob9ANkswreCx7R3cKmY781K8QK3AqVL3xVh9A42JvIAbkkSA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@isaacs/string-locale-compare": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/string-locale-compare/-/string-locale-compare-1.1.0.tgz", + "integrity": "sha512-SQ7Kzhh9+D+ZW9MA0zkYv3VXhIDNx+LzM6EJ+/65I3QY+enU6Itte7E5XX7EWrqLW2FN4n06GWzBnPoC3th2aQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/@netflix/nerror": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@netflix/nerror/-/nerror-1.1.3.tgz", + "integrity": "sha512-b+MGNyP9/LXkapreJzNUzcvuzZslj/RGgdVVJ16P2wSlYatfLycPObImqVJSmNAdyeShvNeM/pl3sVZsObFueg==", + "dev": true, + "license": "MIT", + "dependencies": { + "assert-plus": "^1.0.0", + "extsprintf": "^1.4.0", + "lodash": "^4.17.15" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@npmcli/agent": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-4.0.2.tgz", + "integrity": "sha512-EUEuWAxnL07Sp5/iC/1X6Xj+XThUvnbei9zfRWZdEXa7lss9RTHMhAHBeg+MZ5To9s/gGaSI+UwZTPdYMvKSeg==", + "dev": true, + "license": "ISC", + "dependencies": { + "agent-base": "^7.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.1", + "lru-cache": "^11.2.1", + "socks-proxy-agent": "^8.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/arborist": { + "version": "9.9.0", + "resolved": "https://registry.npmjs.org/@npmcli/arborist/-/arborist-9.9.0.tgz", + "integrity": "sha512-tzsb1R8mx0k0drlLDT/9ckEYaQHIaWnUti/ci2IaFoQqdqwfmYrc+90p1+QEZC/ocvqcxBep9P1xKw4FbAGofw==", + "dev": true, + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@isaacs/string-locale-compare": "^1.1.0", + "@npmcli/fs": "^5.0.0", + "@npmcli/installed-package-contents": "^4.0.0", + "@npmcli/map-workspaces": "^5.0.0", + "@npmcli/metavuln-calculator": "^9.0.2", + "@npmcli/name-from-folder": "^4.0.0", + "@npmcli/node-gyp": "^5.0.0", + "@npmcli/package-json": "^7.0.0", + "@npmcli/query": "^5.0.0", + "@npmcli/redact": "^4.0.0", + "@npmcli/run-script": "^10.0.0", + "bin-links": "^6.0.0", + "cacache": "^20.0.1", + "common-ancestor-path": "^2.0.0", + "hosted-git-info": "^9.0.0", + "json-stringify-nice": "^1.1.4", + "lru-cache": "^11.2.1", + "minimatch": "^10.0.3", + "nopt": "^9.0.0", + "npm-install-checks": "^8.0.0", + "npm-package-arg": "^13.0.0", + "npm-pick-manifest": "^11.0.1", + "npm-registry-fetch": "^19.0.0", + "pacote": "^21.0.2", + "parse-conflict-json": "^5.0.1", + "proc-log": "^6.0.0", + "proggy": "^4.0.0", + "promise-all-reject-late": "^1.0.0", + "promise-call-limit": "^3.0.1", + "semver": "^7.3.7", + "ssri": "^13.0.0", + "treeverse": "^3.0.0", + "walk-up-path": "^4.0.0" + }, + "bin": { + "arborist": "bin/index.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@npmcli/arborist/node_modules/brace-expansion": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz", + "integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@npmcli/arborist/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/fs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-5.0.0.tgz", + "integrity": "sha512-7OsC1gNORBEawOa5+j2pXN9vsicaIOH5cPXxoR6fJOmH6/EXpJB2CajXOu1fPRFun2m1lktEFX11+P89hqO/og==", + "dev": true, + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/git": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-7.0.2.tgz", + "integrity": "sha512-oeolHDjExNAJAnlYP2qzNjMX/Xi9bmu78C9dIGr4xjobrSKbuMYCph8lTzn4vnW3NjIqVmw/f8BCfouqyJXlRg==", + "dev": true, + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "ini": "^6.0.0", + "lru-cache": "^11.2.1", + "npm-pick-manifest": "^11.0.1", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "which": "^6.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/git/node_modules/isexe": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz", + "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=20" + } + }, + "node_modules/@npmcli/git/node_modules/which": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", + "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^4.0.0" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/installed-package-contents": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/installed-package-contents/-/installed-package-contents-4.0.0.tgz", + "integrity": "sha512-yNyAdkBxB72gtZ4GrwXCM0ZUedo9nIbOMKfGjt6Cu6DXf0p8y1PViZAKDC8q8kv/fufx0WTjRBdSlyrvnP7hmA==", + "dev": true, + "license": "ISC", + "dependencies": { + "npm-bundled": "^5.0.0", + "npm-normalize-package-bin": "^5.0.0" + }, + "bin": { + "installed-package-contents": "bin/index.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/map-workspaces": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@npmcli/map-workspaces/-/map-workspaces-5.0.3.tgz", + "integrity": "sha512-o2grssXo1e774E5OtEwwrgoszYRh0lqkJH+Pb9r78UcqdGJRDRfhpM8DvZPjzNLLNYeD/rNbjOKM3Ss5UABROw==", + "dev": true, + "license": "ISC", + "dependencies": { + "@npmcli/name-from-folder": "^4.0.0", + "@npmcli/package-json": "^7.0.0", + "glob": "^13.0.0", + "minimatch": "^10.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/map-workspaces/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@npmcli/map-workspaces/node_modules/brace-expansion": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz", + "integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@npmcli/map-workspaces/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/map-workspaces/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/metavuln-calculator": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/@npmcli/metavuln-calculator/-/metavuln-calculator-9.0.3.tgz", + "integrity": "sha512-94GLSYhLXF2t2LAC7pDwLaM4uCARzxShyAQKsirmlNcpidH89VA4/+K1LbJmRMgz5gy65E/QBBWQdUvGLe2Frg==", + "dev": true, + "license": "ISC", + "dependencies": { + "cacache": "^20.0.0", + "json-parse-even-better-errors": "^5.0.0", + "pacote": "^21.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/name-from-folder": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/name-from-folder/-/name-from-folder-4.0.0.tgz", + "integrity": "sha512-qfrhVlOSqmKM8i6rkNdZzABj8MKEITGFAY+4teqBziksCQAOLutiAxM1wY2BKEd8KjUSpWmWCYxvXr0y4VTlPg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/node-gyp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/node-gyp/-/node-gyp-5.0.0.tgz", + "integrity": "sha512-uuG5HZFXLfyFKqg8QypsmgLQW7smiRjVc45bqD/ofZZcR/uxEjgQU8qDPv0s9TEeMUiAAU/GC5bR6++UdTirIQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/package-json": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/@npmcli/package-json/-/package-json-7.0.5.tgz", + "integrity": "sha512-iVuTlG3ORq2iaVa1IWUxAO/jIp77tUKBhoMjuzYW2kL4MLN1bi/ofqkZ7D7OOwh8coAx1/S2ge0rMdGv8sLSOQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "@npmcli/git": "^7.0.0", + "glob": "^13.0.0", + "hosted-git-info": "^9.0.0", + "json-parse-even-better-errors": "^5.0.0", + "proc-log": "^6.0.0", + "semver": "^7.5.3", + "spdx-expression-parse": "^4.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/package-json/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@npmcli/package-json/node_modules/brace-expansion": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz", + "integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@npmcli/package-json/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/package-json/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/promise-spawn": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/@npmcli/promise-spawn/-/promise-spawn-9.0.1.tgz", + "integrity": "sha512-OLUaoqBuyxeTqUvjA3FZFiXUfYC1alp3Sa99gW3EUDz3tZ3CbXDdcZ7qWKBzicrJleIgucoWamWH1saAmH/l2Q==", + "dev": true, + "license": "ISC", + "dependencies": { + "which": "^6.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/promise-spawn/node_modules/isexe": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz", + "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=20" + } + }, + "node_modules/@npmcli/promise-spawn/node_modules/which": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", + "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^4.0.0" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/query": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/query/-/query-5.0.0.tgz", + "integrity": "sha512-8TZWfTQOsODpLqo9SVhVjHovmKXNpevHU0gO9e+y4V4fRIOneiXy0u0sMP9LmS71XivrEWfZWg50ReH4WRT4aQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "postcss-selector-parser": "^7.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/redact": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-4.0.0.tgz", + "integrity": "sha512-gOBg5YHMfZy+TfHArfVogwgfBeQnKbbGo3pSUyK/gSI0AVu+pEiDVcKlQb0D8Mg1LNRZILZ6XG8I5dJ4KuAd9Q==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/run-script": { + "version": "10.0.4", + "resolved": "https://registry.npmjs.org/@npmcli/run-script/-/run-script-10.0.4.tgz", + "integrity": "sha512-mGUWr1uMnf0le2TwfOZY4SFxZGXGfm4Jtay/nwAa2FLNAKXUoUwaGwBMNH36UHPtinWfTSJ3nqFQr0091CxVGg==", + "dev": true, + "license": "ISC", + "dependencies": { + "@npmcli/node-gyp": "^5.0.0", + "@npmcli/package-json": "^7.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "node-gyp": "^12.1.0", + "proc-log": "^6.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@sigstore/bundle": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sigstore/bundle/-/bundle-4.0.0.tgz", + "integrity": "sha512-NwCl5Y0V6Di0NexvkTqdoVfmjTaQwoLM236r89KEojGmq/jMls8S+zb7yOwAPdXvbwfKDlP+lmXgAL4vKSQT+A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.5.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@sigstore/core": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@sigstore/core/-/core-3.2.1.tgz", + "integrity": "sha512-qRsxPnCrbC/puegGxKuynfnxgLiHqWStrSjxkoB4YKqq3Z3s4cyZyj42ZdWFAEblNP65C+rBH8EuREHIXoi83g==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@sigstore/protobuf-specs": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/@sigstore/protobuf-specs/-/protobuf-specs-0.5.1.tgz", + "integrity": "sha512-/ScWUhhoFasJsSRGTVBwId1loQjjnjAfE4djL6ZhrXRpNCmPTnUKF5Jokd58ILseOMjzET3UrMOtJPS9sYeI0g==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@sigstore/sign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@sigstore/sign/-/sign-4.1.1.tgz", + "integrity": "sha512-Hf4xglukg0XXQ2RiD5vSoLjdPe8OBUPA8XeVjUObheuDcWdYWrnH/BNmxZCzkAy68MzmNCxXLeurJvs6hcP2OQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@gar/promise-retry": "^1.0.2", + "@sigstore/bundle": "^4.0.0", + "@sigstore/core": "^3.2.0", + "@sigstore/protobuf-specs": "^0.5.0", + "make-fetch-happen": "^15.0.4", + "proc-log": "^6.1.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@sigstore/tuf": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@sigstore/tuf/-/tuf-4.0.2.tgz", + "integrity": "sha512-TCAzTy0xzdP79EnxSjq9KQ3eaR7+FmudLC6eRKknVKZbV7ZNlGLClAAQb/HMNJ5n2OBNk2GT1tEmU0xuPr+SLQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.5.0", + "tuf-js": "^4.1.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@sigstore/verify": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@sigstore/verify/-/verify-3.1.1.tgz", + "integrity": "sha512-qv7+G3J2cc6wwFj3yKvXOamzqhMwSk1ogPGmhpS8iXllcPrJaIIBA+4HbttlHVu1pqWTdmaCH/WE7UOC51kdoA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^4.0.0", + "@sigstore/core": "^3.2.1", + "@sigstore/protobuf-specs": "^0.5.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@tufjs/canonical-json": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@tufjs/canonical-json/-/canonical-json-2.0.0.tgz", + "integrity": "sha512-yVtV8zsdo8qFHe+/3kw81dSLyF7D576A5cCFCi4X7B39tWT7SekaEFUnvnWJHz+9qO7qJTah1JbrDjWKqFtdWA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@tufjs/models": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@tufjs/models/-/models-4.1.0.tgz", + "integrity": "sha512-Y8cK9aggNRsqJVaKUlEYs4s7CvQ1b1ta2DVPyAimb0I2qhzjNk+A+mxvll/klL0RlfuIUei8BF7YWiua4kQqww==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tufjs/canonical-json": "2.0.0", + "minimatch": "^10.1.1" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@tufjs/models/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@tufjs/models/node_modules/brace-expansion": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz", + "integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@tufjs/models/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@ungap/promise-all-settled": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz", + "integrity": "sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q==", + "dev": true, + "license": "ISC" + }, + "node_modules/@xmldom/xmldom": { + "version": "0.9.10", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.10.tgz", + "integrity": "sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.6" + } + }, + "node_modules/abbrev": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz", + "integrity": "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ansi": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/ansi/-/ansi-0.3.1.tgz", + "integrity": "sha512-iFY7JCgHbepc0b82yLaw4IMortylNb6wG4kL+4R0C3iv6i+RHGHux/yUX5BTiRvSX/shMnngjR1YyNMnXEFh5A==", + "dev": true, + "license": "MIT" + }, + "node_modules/ansi-colors": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", + "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "dev": true, + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "dev": true, + "license": "Unlicense", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/bin-links": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/bin-links/-/bin-links-6.0.2.tgz", + "integrity": "sha512-frE1t78WOwJ45PKV2cF2tNPjTcs9L1J9s6VkrV59wanRP4GlaomuxYPVma7BwthMg8WnfSory4w5PTE6FZZ81w==", + "dev": true, + "license": "ISC", + "dependencies": { + "cmd-shim": "^8.0.0", + "npm-normalize-package-bin": "^5.0.0", + "proc-log": "^6.0.0", + "read-cmd-shim": "^6.0.0", + "write-file-atomic": "^7.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/bin-links/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/bin-links/node_modules/write-file-atomic": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-7.0.1.tgz", + "integrity": "sha512-OTIk8iR8/aCRWBqvxrzxR0hgxWpnYBblY1S5hDWBQfk/VFmJwzmJgQFN3WsoUKHISv2eAwe+PpbUzyL1CKTLXg==", + "dev": true, + "license": "ISC", + "dependencies": { + "signal-exit": "^4.0.1" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/bplist-parser": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.3.2.tgz", + "integrity": "sha512-apC2+fspHGI3mMKj+dGevkGo/tCqVB8jMb6i+OX+E29p0Iposz07fABkRIfVUPNd5A5VbuOz1bZbnmkKLYF+wQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "big-integer": "1.6.x" + }, + "engines": { + "node": ">= 5.10.0" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.15", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browser-stdout": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", + "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", + "dev": true, + "license": "ISC" + }, + "node_modules/cacache": { + "version": "20.0.4", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-20.0.4.tgz", + "integrity": "sha512-M3Lab8NPYlZU2exsL3bMVvMrMqgwCnMWfdZbK28bn3pK6APT/Te/I8hjRPNu1uwORY9a1eEQoifXbKPQMfMTOA==", + "dev": true, + "license": "ISC", + "dependencies": { + "@npmcli/fs": "^5.0.0", + "fs-minipass": "^3.0.0", + "glob": "^13.0.0", + "lru-cache": "^11.1.0", + "minipass": "^7.0.3", + "minipass-collect": "^2.0.1", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "p-map": "^7.0.2", + "ssri": "^13.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/cacache/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/cacache/node_modules/brace-expansion": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz", + "integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/cacache/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/cacache/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/chai": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.6.tgz", + "integrity": "sha512-bbcp3YfHCUzMOvKqsztczerVgBKSsEijCySNlHHbX3VG1nskvqjz5Rfso1gGwD6w6oOV3eI60pKuMOV5MV7p3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.2", + "deep-eql": "^3.0.1", + "get-func-name": "^2.0.0", + "loupe": "^2.3.1", + "pathval": "^1.1.1", + "type-detect": "^4.0.5" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/check-error": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", + "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-func-name": "^2.0.2" + }, + "engines": { + "node": "*" + } + }, + "node_modules/chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "node_modules/cliui/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cmd-shim": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/cmd-shim/-/cmd-shim-8.0.0.tgz", + "integrity": "sha512-Jk/BK6NCapZ58BKUxlSI+ouKRbjH1NLZCgJkYoab+vEHUY3f6OzpNBN9u7HFSv9J6TRDGs4PLOHezoKGaFRSCA==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/common-ancestor-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/common-ancestor-path/-/common-ancestor-path-2.0.0.tgz", + "integrity": "sha512-dnN3ibLeoRf2HNC+OlCiNc5d2zxbLJXOtiZUudNFSXZrNSydxcCsSpRzXwfu7BBWCIfHPw+xTayeBvJCP/D8Ng==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">= 18" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/configstore": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/configstore/-/configstore-5.0.1.tgz", + "integrity": "sha512-aMKprgk5YhBNyH25hj8wGt2+D52Sw1DRRIzqBwLp2Ya9mFmY8KPvvtvmna8SxVR9JMZ4kzMD68N22vlaRpkeFA==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "dot-prop": "^5.2.0", + "graceful-fs": "^4.1.2", + "make-dir": "^3.0.0", + "unique-string": "^2.0.0", + "write-file-atomic": "^3.0.0", + "xdg-basedir": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cordova": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/cordova/-/cordova-13.0.0.tgz", + "integrity": "sha512-QAIMwmYLL0jHo4vauWSnRd2fr9l+wajG+F5aUkrC6e4ZQGSTv0wAiRmpqQUkIc1ZdELisKDQws/BjHz5nP/sLw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "configstore": "^5.0.1", + "cordova-common": "^6.0.0", + "cordova-create": "^6.0.0", + "cordova-lib": "^13.0.0", + "editor": "^1.0.0", + "execa": "^5.1.1", + "nopt": "^9.0.0", + "semver": "^7.7.3", + "systeminformation": "^5.27.11" + }, + "bin": { + "cordova": "bin/cordova" + }, + "engines": { + "node": ">=20.17.0 || >=22.9.0" + } + }, + "node_modules/cordova-app-hello-world": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/cordova-app-hello-world/-/cordova-app-hello-world-7.0.0.tgz", + "integrity": "sha512-uDTncFkI73ko+wEf6IEO9bw8lQRMQGnfdi5pPMei4P8+plChNcRW5fxjKlhM/8ZrT8OAWiHsQRrP4pIAn3HQ4g==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/cordova-common": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cordova-common/-/cordova-common-6.0.0.tgz", + "integrity": "sha512-16WPC1DuxVdshV3RoQUXqhcJVdhxWGwiFysA4TkYuboqoev6mgt0JuIJFxmQbzR/DuyuONaVe0L0O0Hf1C08Mg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@netflix/nerror": "^1.1.3", + "ansi": "^0.3.1", + "bplist-parser": "^0.3.2", + "elementtree": "^0.1.7", + "endent": "^2.1.0", + "fast-glob": "^3.3.3", + "plist": "^3.1.0" + }, + "engines": { + "node": ">=20.9.0" + } + }, + "node_modules/cordova-create": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cordova-create/-/cordova-create-6.0.0.tgz", + "integrity": "sha512-LD41sLn2GsmAlj3576R3xlUM3BP0rt0CYd5LdbzU82WBI3ApMrrhM6xcHDYJfe1nfSL89O/nb/u/h7+7DhPQeA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "cordova-app-hello-world": "^7.0.0", + "cordova-common": "^6.0.0", + "cordova-fetch": "^5.0.0", + "globby": "^11.1.0", + "import-fresh": "^3.3.1", + "isobject": "^4.0.0", + "npm-package-arg": "^13.0.0", + "path-is-inside": "^1.0.2", + "tmp": "^0.2.5", + "valid-identifier": "0.0.2" + }, + "engines": { + "node": ">=20.17.0 || >=22.9.0" + } + }, + "node_modules/cordova-fetch": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cordova-fetch/-/cordova-fetch-5.0.0.tgz", + "integrity": "sha512-fsYnVfx32AOrFO6tw4EkzSig7WjNhze35dKIzdw20zTQetDKEfWA79PpCaoiSeahGi6O2MdnOFabLhEa8se6jg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@npmcli/arborist": "^9.1.3", + "cordova-common": "^6.0.0", + "execa": "^5.1.1", + "npm-package-arg": "^13.0.0", + "pacote": "^21.0.0", + "resolve": "^1.22.10", + "semver": "^7.7.2", + "which": "^5.0.0" + }, + "engines": { + "node": ">=20.9.0", + "npm": ">=8.1.0" + } + }, + "node_modules/cordova-fetch/node_modules/isexe": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", + "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/cordova-fetch/node_modules/which": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", + "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/cordova-lib": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/cordova-lib/-/cordova-lib-13.0.0.tgz", + "integrity": "sha512-y8WQ+J6JtiU9C72ujvI3p+ScFJkg0VJwNfaUCqk9nPAssw2C6HltHk+ik/WrLUn6uDmwAM6gmfGUIMU2iVrNxA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "cordova-common": "^6.0.0", + "cordova-fetch": "^5.0.0", + "detect-indent": "^6.1.0", + "detect-newline": "^3.1.0", + "execa": "^5.1.1", + "globby": "^11.1.0", + "semver": "^7.7.2", + "stringify-package": "^1.0.1", + "write-file-atomic": "^7.0.0" + }, + "engines": { + "node": ">=20.17.0 || >=22.9.0" + } + }, + "node_modules/cordova-lib/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/cordova-lib/node_modules/write-file-atomic": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-7.0.1.tgz", + "integrity": "sha512-OTIk8iR8/aCRWBqvxrzxR0hgxWpnYBblY1S5hDWBQfk/VFmJwzmJgQFN3WsoUKHISv2eAwe+PpbUzyL1CKTLXg==", + "dev": true, + "license": "ISC", + "dependencies": { + "signal-exit": "^4.0.1" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/crypto-random-string": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz", + "integrity": "sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decamelize": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz", + "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/dedent": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", + "integrity": "sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA==", + "dev": true, + "license": "MIT" + }, + "node_modules/deep-eql": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-3.0.1.tgz", + "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/detect-indent": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-6.1.0.tgz", + "integrity": "sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/detect-newline": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", + "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/diff": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", + "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/dot-prop": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-5.3.0.tgz", + "integrity": "sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-obj": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/editor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/editor/-/editor-1.0.0.tgz", + "integrity": "sha512-SoRmbGStwNYHgKfjOrX2L0mUvp9bUVv0uPppZSOMAntEbcFtoC3MKF5b3T6HQPXKIV+QGY3xPO3JK5it5lVkuw==", + "dev": true, + "license": "MIT" + }, + "node_modules/elementtree": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/elementtree/-/elementtree-0.1.7.tgz", + "integrity": "sha512-wkgGT6kugeQk/P6VZ/f4T+4HB41BVgNBq5CDIZVbQ02nvTVqAiVTbskxxu3eA/X96lMlfYOwnLQpN2v5E1zDEg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "sax": "1.1.4" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/endent": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/endent/-/endent-2.1.0.tgz", + "integrity": "sha512-r8VyPX7XL8U01Xgnb1CjZ3XV+z90cXIJ9JPE/R9SEC9vpw2P6CfsRPJmp20DppC5N7ZAMCmjYkJIa744Iyg96w==", + "dev": true, + "license": "MIT", + "dependencies": { + "dedent": "^0.7.0", + "fast-json-parse": "^1.0.3", + "objectorarray": "^1.0.5" + } + }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/exponential-backoff": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz", + "integrity": "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/extsprintf": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.4.1.tgz", + "integrity": "sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA==", + "dev": true, + "engines": [ + "node >=0.6.0" + ], + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-json-parse": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/fast-json-parse/-/fast-json-parse-1.0.3.tgz", + "integrity": "sha512-FRWsaZRWEJ1ESVNbDWmsAlqDk96gPQezzLghafp5J4GUKjbCz3OkAHuZs5TuPEtkbVQERysLp9xv6c24fBm8Aw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fastq": { + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", + "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz", + "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==", + "dev": true, + "license": "BSD-3-Clause", + "bin": { + "flat": "cli.js" + } + }, + "node_modules/fs-minipass": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz", + "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==", + "dev": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true, + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-func-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/globby": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/growl": { + "version": "1.10.5", + "resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz", + "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4.x" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "dev": true, + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/hosted-git-info": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz", + "integrity": "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==", + "dev": true, + "license": "ISC", + "dependencies": { + "lru-cache": "^11.1.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/http-cache-semantics": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz", + "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/ignore-walk": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/ignore-walk/-/ignore-walk-8.0.0.tgz", + "integrity": "sha512-FCeMZT4NiRQGh+YkeKMtWrOmBgWjHjMJ26WQWrRQyoyzqevdaGSakUaJW5xQYmjLlUVk2qUnCjYVBax9EKKg8A==", + "dev": true, + "license": "ISC", + "dependencies": { + "minimatch": "^10.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/ignore-walk/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/ignore-walk/node_modules/brace-expansion": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz", + "integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/ignore-walk/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dev": true, + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/ini": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-6.0.0.tgz", + "integrity": "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/ip-address": { + "version": "10.3.1", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.3.1.tgz", + "integrity": "sha512-1e9d3kb97NHJTIJDZW9rKqW2h6+dFa50Dy0fpPSMQp2ADje5gvKsXmdiK6dwY5t76TaTt5+P5N1Y/LoToIxP6g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz", + "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-obj": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", + "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-plain-obj": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz", + "integrity": "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "dev": true, + "license": "ISC" + }, + "node_modules/isobject": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-4.0.0.tgz", + "integrity": "sha512-S/2fF5wH8SJA/kmwr6HYhK/RI/OkhD84k8ntalo0iJjZikgq1XFvR5M8NPT1x5F7fBwCG3qHfnzeP/Vh/ZxCUA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-5.0.0.tgz", + "integrity": "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/json-stringify-nice": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/json-stringify-nice/-/json-stringify-nice-1.1.4.tgz", + "integrity": "sha512-5Z5RFW63yxReJ7vANgW6eZFGWaQvnPE3WNmZoOJrSkGju2etKA2L5rrOa1sm877TVTFt57A80BH1bArcmlLfPw==", + "dev": true, + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jsonparse": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", + "integrity": "sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==", + "dev": true, + "engines": [ + "node >= 0.2.0" + ], + "license": "MIT" + }, + "node_modules/just-diff": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/just-diff/-/just-diff-6.0.2.tgz", + "integrity": "sha512-S59eriX5u3/QhMNq3v/gm8Kd0w8OS6Tz2FS1NG4blv+z0MuQcBRJyFWjdovM0Rad4/P4aUPFtnkNjMjyMlMSYA==", + "dev": true, + "license": "MIT" + }, + "node_modules/just-diff-apply": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/just-diff-apply/-/just-diff-apply-5.5.0.tgz", + "integrity": "sha512-OYTthRfSh55WOItVqwpefPtNt2VdKsq5AnAK6apdtR6yCH8pr0CmSr710J0Mf+WdQy7K/OzMy7K2MgAfdQURDw==", + "dev": true, + "license": "MIT" + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/log-symbols": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-symbols/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/loupe": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", + "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-func-name": "^2.0.1" + } + }, + "node_modules/lru-cache": { + "version": "11.5.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", + "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/make-fetch-happen": { + "version": "15.0.6", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-15.0.6.tgz", + "integrity": "sha512-Je0fLJ0F5atA7F+eIlLzk+Wkcl57JDf4kf+EW8xiP5E31xOQxkIxTbgf1Oi1Lw9tRI9UEMRdI5Vz2xTzoNU1Jw==", + "dev": true, + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@npmcli/agent": "^4.0.0", + "@npmcli/redact": "^4.0.0", + "cacache": "^20.0.1", + "http-cache-semantics": "^4.1.1", + "minipass": "^7.0.2", + "minipass-fetch": "^5.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^1.0.0", + "proc-log": "^6.0.0", + "ssri": "^13.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minipass-collect": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-2.0.1.tgz", + "integrity": "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw==", + "dev": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minipass-fetch": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-5.0.2.tgz", + "integrity": "sha512-2d0q2a8eCi2IRg/IGubCNRJoYbA1+YPXAzQVRFmB45gdGZafyivnZ5YSEfo3JikbjGxOdntGFvBQGqaSMXlAFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.0.3", + "minipass-sized": "^2.0.0", + "minizlib": "^3.0.1" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + }, + "optionalDependencies": { + "iconv-lite": "^0.7.2" + } + }, + "node_modules/minipass-flush": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.7.tgz", + "integrity": "sha512-TbqTz9cUwWyHS2Dy89P3ocAGUGxKjjLuR9z8w4WUTGAVgEj17/4nhgo2Du56i0Fm3Pm30g4iA8Lcqctc76jCzA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minipass-flush/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-flush/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true, + "license": "ISC" + }, + "node_modules/minipass-pipeline": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", + "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", + "dev": true, + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-pipeline/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-pipeline/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true, + "license": "ISC" + }, + "node_modules/minipass-sized": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-2.0.0.tgz", + "integrity": "sha512-zSsHhto5BcUVM2m1LurnXY6M//cGhVaegT71OfOXoprxT6o780GZd792ea6FfrQkuU4usHZIUczAQMRUE2plzA==", + "dev": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/mocha": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.2.2.tgz", + "integrity": "sha512-L6XC3EdwT6YrIk0yXpavvLkn8h+EU+Y5UcCHKECyMbdUIxyMuZj4bX4U9e1nvnvUUvQVsV2VHQr5zLdcUkhW/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ungap/promise-all-settled": "1.1.2", + "ansi-colors": "4.1.1", + "browser-stdout": "1.3.1", + "chokidar": "3.5.3", + "debug": "4.3.3", + "diff": "5.0.0", + "escape-string-regexp": "4.0.0", + "find-up": "5.0.0", + "glob": "7.2.0", + "growl": "1.10.5", + "he": "1.2.0", + "js-yaml": "4.1.0", + "log-symbols": "4.1.0", + "minimatch": "4.2.1", + "ms": "2.1.3", + "nanoid": "3.3.1", + "serialize-javascript": "6.0.0", + "strip-json-comments": "3.1.1", + "supports-color": "8.1.1", + "which": "2.0.2", + "workerpool": "6.2.0", + "yargs": "16.2.0", + "yargs-parser": "20.2.4", + "yargs-unparser": "2.0.0" + }, + "bin": { + "_mocha": "bin/_mocha", + "mocha": "bin/mocha" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mochajs" + } + }, + "node_modules/mocha/node_modules/debug": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", + "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/mocha/node_modules/debug/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/mocha/node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mocha/node_modules/glob": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", + "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/mocha/node_modules/glob/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/mocha/node_modules/minimatch": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-4.2.1.tgz", + "integrity": "sha512-9Uq1ChtSZO+Mxa/CL1eGizn2vRn3MlLgzhT0Iz8zaY8NdvxvB0d5QdPFmCKf7JKA9Lerx5vRrnwO03jsSfGG9g==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mocha/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.1.tgz", + "integrity": "sha512-n6Vs/3KGyxPQd6uO0eH4Bv0ojGSUvuLlIHtC3Y0kEO23YRge8H9x1GCzLn28YX0H66pMkxuaeESFq4tKISKwdw==", + "dev": true, + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-gyp": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.4.0.tgz", + "integrity": "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.0", + "exponential-backoff": "^3.1.1", + "graceful-fs": "^4.2.6", + "nopt": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "tar": "^7.5.4", + "tinyglobby": "^0.2.12", + "undici": "^6.25.0", + "which": "^6.0.0" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/node-gyp/node_modules/isexe": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz", + "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=20" + } + }, + "node_modules/node-gyp/node_modules/which": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", + "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^4.0.0" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/nopt": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz", + "integrity": "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==", + "dev": true, + "license": "ISC", + "dependencies": { + "abbrev": "^4.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-bundled": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/npm-bundled/-/npm-bundled-5.0.0.tgz", + "integrity": "sha512-JLSpbzh6UUXIEoqPsYBvVNVmyrjVZ1fzEFbqxKkTJQkWBO3xFzFT+KDnSKQWwOQNbuWRwt5LSD6HOTLGIWzfrw==", + "dev": true, + "license": "ISC", + "dependencies": { + "npm-normalize-package-bin": "^5.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/npm-install-checks": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/npm-install-checks/-/npm-install-checks-8.0.0.tgz", + "integrity": "sha512-ScAUdMpyzkbpxoNekQ3tNRdFI8SJ86wgKZSQZdUxT+bj0wVFpsEMWnkXP0twVe1gJyNF5apBWDJhhIbgrIViRA==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "semver": "^7.1.1" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/npm-normalize-package-bin": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-5.0.0.tgz", + "integrity": "sha512-CJi3OS4JLsNMmr2u07OJlhcrPxCeOeP/4xq67aWNai6TNWWbTrlNDgl8NcFKVlcBKp18GPj+EzbNIgrBfZhsag==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/npm-package-arg": { + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-13.0.2.tgz", + "integrity": "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA==", + "dev": true, + "license": "ISC", + "dependencies": { + "hosted-git-info": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^7.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/npm-packlist": { + "version": "10.0.4", + "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-10.0.4.tgz", + "integrity": "sha512-uMW73iajD8hiH4ZBxEV3HC+eTnppIqwakjOYuvgddnalIw2lJguKviK1pcUJDlIWm1wSJkchpDZDSVVsZEYRng==", + "dev": true, + "license": "ISC", + "dependencies": { + "ignore-walk": "^8.0.0", + "proc-log": "^6.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/npm-pick-manifest": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/npm-pick-manifest/-/npm-pick-manifest-11.0.3.tgz", + "integrity": "sha512-buzyCfeoGY/PxKqmBqn1IUJrZnUi1VVJTdSSRPGI60tJdUhUoSQFhs0zycJokDdOznQentgrpf8LayEHyyYlqQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "npm-install-checks": "^8.0.0", + "npm-normalize-package-bin": "^5.0.0", + "npm-package-arg": "^13.0.0", + "semver": "^7.3.5" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/npm-registry-fetch": { + "version": "19.1.1", + "resolved": "https://registry.npmjs.org/npm-registry-fetch/-/npm-registry-fetch-19.1.1.tgz", + "integrity": "sha512-TakBap6OM1w0H73VZVDf44iFXsOS3h+L4wVMXmbWOQroZgFhMch0juN6XSzBNlD965yIKvWg2dfu7NSiaYLxtw==", + "dev": true, + "license": "ISC", + "dependencies": { + "@npmcli/redact": "^4.0.0", + "jsonparse": "^1.3.1", + "make-fetch-happen": "^15.0.0", + "minipass": "^7.0.2", + "minipass-fetch": "^5.0.0", + "minizlib": "^3.0.1", + "npm-package-arg": "^13.0.0", + "proc-log": "^6.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/objectorarray": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/objectorarray/-/objectorarray-1.0.5.tgz", + "integrity": "sha512-eJJDYkhJFFbBBAxeh8xW+weHlkI28n2ZdQV/J/DNfWfSKlGEf2xcfAbZTv3riEXHAhL9SVOTs2pRmXiSTf78xg==", + "dev": true, + "license": "ISC" + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-map": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.0.6.tgz", + "integrity": "sha512-I4Prw6ivkd6p8PiYR1tXASOAOBzIJwu0TB7fqaX0c/8c3QAehNYmX57EijyGGGBt3c/BIowGwV03RVBtXvHEVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/pacote": { + "version": "21.5.1", + "resolved": "https://registry.npmjs.org/pacote/-/pacote-21.5.1.tgz", + "integrity": "sha512-KvcJ9iy3crysCsgqc4+PknH/w6jkrp8JN36mpZBPwNaDRwTfMZD37YzRazNstiZUOhuF5pno9f78n9mEJBavwg==", + "dev": true, + "license": "ISC", + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@npmcli/git": "^7.0.0", + "@npmcli/installed-package-contents": "^4.0.0", + "@npmcli/package-json": "^7.0.0", + "@npmcli/promise-spawn": "^9.0.0", + "@npmcli/run-script": "^10.0.0", + "cacache": "^20.0.0", + "fs-minipass": "^3.0.0", + "minipass": "^7.0.2", + "npm-package-arg": "^13.0.0", + "npm-packlist": "^10.0.1", + "npm-pick-manifest": "^11.0.1", + "npm-registry-fetch": "^19.0.0", + "proc-log": "^6.0.0", + "sigstore": "^4.0.0", + "ssri": "^13.0.0", + "tar": "^7.4.3" + }, + "bin": { + "pacote": "bin/index.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-conflict-json": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/parse-conflict-json/-/parse-conflict-json-5.0.1.tgz", + "integrity": "sha512-ZHEmNKMq1wyJXNwLxyHnluPfRAFSIliBvbK/UiOceROt4Xh9Pz0fq49NytIaeaCUf5VR86hwQ/34FCcNU5/LKQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "json-parse-even-better-errors": "^5.0.0", + "just-diff": "^6.0.0", + "just-diff-apply": "^5.2.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-is-inside": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", + "integrity": "sha512-DUWJr3+ULp4zXmol/SZkFf3JGsS9/SIv+Y3Rt93/UjPpDpklB5f1er4O3POIbUuUJ3FXgqte2Q7SrU6zAqwk8w==", + "dev": true, + "license": "(WTFPL OR MIT)" + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/plist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz", + "integrity": "sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@xmldom/xmldom": "^0.9.10", + "base64-js": "^1.5.1", + "xmlbuilder": "^15.1.1" + }, + "engines": { + "node": ">=10.4.0" + } + }, + "node_modules/postcss-selector-parser": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.4.tgz", + "integrity": "sha512-HeP7D2wyhkR+XaK6v4W8oRF62Dsz4flyuczALJp61GckGm42u1saSSJ/0auvcBqxs3jMRFEcPK34At/0JBKdOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/proggy": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/proggy/-/proggy-4.0.0.tgz", + "integrity": "sha512-MbA4R+WQT76ZBm/5JUpV9yqcJt92175+Y0Bodg3HgiXzrmKu7Ggq+bpn6y6wHH+gN9NcyKn3yg1+d47VaKwNAQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/promise-all-reject-late": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/promise-all-reject-late/-/promise-all-reject-late-1.0.1.tgz", + "integrity": "sha512-vuf0Lf0lOxyQREH7GDIOUMLS7kz+gs8i6B+Yi8dC68a2sychGrHTJYghMBD6k7eUcH0H5P73EckCA48xijWqXw==", + "dev": true, + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/promise-call-limit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/promise-call-limit/-/promise-call-limit-3.0.2.tgz", + "integrity": "sha512-mRPQO2T1QQVw11E7+UdCJu7S61eJVWknzml9sC1heAdj1jxl0fWMBypIt9ZOcLFf8FkG995ZD7RnVk7HH72fZw==", + "dev": true, + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/read-cmd-shim": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/read-cmd-shim/-/read-cmd-shim-6.0.0.tgz", + "integrity": "sha512-1zM5HuOfagXCBWMN83fuFI/x+T/UhZ7k+KIzhrHXcQoeX5+7gmaDYjELQHmmzIodumBHeByBJT4QYS7ufAgs7A==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.12", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", + "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/sax": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.1.4.tgz", + "integrity": "sha512-5f3k2PbGGp+YtKJjOItpg3P99IMD84E4HOvcfleTb5joCHNXYLsR9yWFPOYGgaeMPDubQILTCMdsFb2OMeOjtg==", + "dev": true, + "license": "ISC" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/serialize-javascript": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz", + "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/sigstore": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/sigstore/-/sigstore-4.1.1.tgz", + "integrity": "sha512-endqECJkfhozrXMK5ngu/UAA0xVcVEFdnHJCElGaExypjW+HK5i6zu3NteLoaX/iFbRUbC3+DjttQs0GARr+5w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^4.0.0", + "@sigstore/core": "^3.2.1", + "@sigstore/protobuf-specs": "^0.5.0", + "@sigstore/sign": "^4.1.1", + "@sigstore/tuf": "^4.0.2", + "@sigstore/verify": "^3.1.1" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.9", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.9.tgz", + "integrity": "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw==", + "dev": true, + "license": "MIT", + "dependencies": { + "ip-address": "^10.1.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/spdx-exceptions": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.5.0.tgz", + "integrity": "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==", + "dev": true, + "license": "CC-BY-3.0" + }, + "node_modules/spdx-expression-parse": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-4.0.0.tgz", + "integrity": "sha512-Clya5JIij/7C6bRR22+tnGXbc4VKlibKSVj2iHvVeX5iMW7s1SIQlqu699JkODJJIhh/pUu8L0/VLh8xflD+LQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-license-ids": { + "version": "3.0.23", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.23.tgz", + "integrity": "sha512-CWLcCCH7VLu13TgOH+r8p1O/Znwhqv/dbb6lqWy67G+pT1kHmeD/+V36AVb/vq8QMIQwVShJ6Ssl5FPh0fuSdw==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/ssri": { + "version": "13.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-13.0.1.tgz", + "integrity": "sha512-QUiRf1+u9wPTL/76GTYlKttDEBWV1ga9ZXW8BG6kfdeyyM8LGPix9gROyg9V2+P0xNyF3X2Go526xKFdMZrHSQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/stringify-package": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/stringify-package/-/stringify-package-1.0.1.tgz", + "integrity": "sha512-sa4DUQsYciMP1xhKWGuFM04fB0LG/9DlluZoSVywUMRNvzid6XucHK0/90xGxRoHrAaROrcHK1aPKaijCtSrhg==", + "deprecated": "This module is not used anymore, and has been replaced by @npmcli/package-json", + "dev": true, + "license": "ISC" + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/systeminformation": { + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-5.33.1.tgz", + "integrity": "sha512-DEN6ICHk3Tk0Uf/hrAHh7xlt7iL5CJFBtPZinA0H62DrGG/KPKqq/Nzj6lCXPS4Ay/sf/14zNnk9LpqKzBIc+w==", + "dev": true, + "license": "MIT", + "os": [ + "darwin", + "linux", + "win32", + "freebsd", + "openbsd", + "netbsd", + "sunos", + "android" + ], + "bin": { + "systeminformation": "lib/cli.js" + }, + "engines": { + "node": ">=10.0.0" + }, + "funding": { + "type": "Buy me a coffee", + "url": "https://www.buymeacoffee.com/systeminfo" + } + }, + "node_modules/tar": { + "version": "7.5.22", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", + "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/tmp": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", + "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.14" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/treeverse": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/treeverse/-/treeverse-3.0.0.tgz", + "integrity": "sha512-gcANaAnd2QDZFmHFEOF4k7uc1J/6a6z3DJMd/QwEyxLoKGiptJRwid582r7QIsFlFMIZ3SnxfS52S4hm2DHkuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/tuf-js": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/tuf-js/-/tuf-js-4.1.0.tgz", + "integrity": "sha512-50QV99kCKH5P/Vs4E2Gzp7BopNV+KzTXqWeaxrfu5IQJBOULRsTIS9seSsOVT8ZnGXzCyx55nYWAi4qJzpZKEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tufjs/models": "4.1.0", + "debug": "^4.4.3", + "make-fetch-happen": "^15.0.1" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/type-detect": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.1.0.tgz", + "integrity": "sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-typedarray": "^1.0.0" + } + }, + "node_modules/umd-tough-cookie": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/umd-tough-cookie/-/umd-tough-cookie-3.0.0.tgz", + "integrity": "sha512-LgVV1jgzEPgC/zOj6T9OIDBTj7YCGEJkgoxV2gHYv1Crlst1X95lRIF48hFleGgv4v01Z86LxyyLyvl++M2Srg==", + "dev": true, + "license": "MIT" + }, + "node_modules/undici": { + "version": "6.28.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz", + "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, + "node_modules/unique-string": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz", + "integrity": "sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "crypto-random-string": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/valid-identifier": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/valid-identifier/-/valid-identifier-0.0.2.tgz", + "integrity": "sha512-zaSmOW6ykXwrkX0YTuFUSoALNEKGaQHpxBJQLb3TXspRNDpBwbfrIQCZqAQ0LKBlKuyn2YOq7NNd6415hvZ33g==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/validate-npm-package-name": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-7.0.2.tgz", + "integrity": "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/walk-up-path": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/walk-up-path/-/walk-up-path-4.0.0.tgz", + "integrity": "sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A==", + "dev": true, + "license": "ISC", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/which": { + "version": "2.0.2", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/workerpool": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.2.0.tgz", + "integrity": "sha512-Rsk5qQHJ9eowMH28Jwhe8HEbmdYDX4lwoMWshiCXugjtHqMD9ZbiqSDLxcsfdqsETPzVUtX5s1Z5kStiIM6l4A==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/write-file-atomic": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", + "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", + "dev": true, + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4", + "is-typedarray": "^1.0.0", + "signal-exit": "^3.0.2", + "typedarray-to-buffer": "^3.1.5" + } + }, + "node_modules/xdg-basedir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz", + "integrity": "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/xml2js": { + "version": "0.4.23", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.23.tgz", + "integrity": "sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug==", + "dev": true, + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/xml2js/node_modules/xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/xmlbuilder": { + "version": "15.1.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", + "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/yargs": { + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-parser": { + "version": "20.2.4", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz", + "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-unparser": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz", + "integrity": "sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "camelcase": "^6.0.0", + "decamelize": "^4.0.0", + "flat": "^5.0.2", + "is-plain-obj": "^2.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/package.json b/src/plugins/cordova-plugin-advanced-http/package.json new file mode 100644 index 0000000000..ed9f655644 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/package.json @@ -0,0 +1,71 @@ +{ + "name": "cordova-plugin-advanced-http", + "version": "3.3.1", + "description": "Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning", + "scripts": { + "update:cert": "node ./scripts/update-e2e-server-cert.js && node ./scripts/update-e2e-client-cert.js", + "build:browser": "./scripts/build-test-app.sh --browser", + "build:android": "./scripts/build-test-app.sh --android --emulator", + "build:ios": "./scripts/build-test-app.sh --ios --emulator", + "test:android": "npm run update:cert && npm run build:android && ./scripts/test-app.sh --android --emulator", + "test:ios": "npm run update:cert && npm run build:ios && ./scripts/test-app.sh --ios --emulator", + "test:app": "npm run test:android && npm run test:ios", + "test:js": "mocha ./test/js-specs.js", + "test": "npm run test:js && npm run test:app", + "release": "npm run test && ./scripts/release.sh" + }, + "cordova": { + "id": "cordova-plugin-advanced-http", + "platforms": [ + "ios", + "android" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/silkimen/cordova-plugin-advanced-http.git" + }, + "keywords": [ + "cordova", + "device", + "ecosystem:cordova", + "cordova-ios", + "cordova-android", + "ssl", + "tls" + ], + "engines": [ + { + "name": "cordova", + "version": ">=4.0.0" + } + ], + "author": "Wymsee", + "contributors": [ + "devgeeks", + "EddyVerbruggen", + "mbektchiev", + "denisbabineau", + "andrey-tsaplin", + "pvsaikrishna", + "cvillerm", + "hideov", + "silkimen" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/silkimen/cordova-plugin-advanced-http/issues" + }, + "homepage": "https://github.com/silkimen/cordova-plugin-advanced-http#readme", + "devDependencies": { + "chai": "4.3.6", + "colors": "1.4.0", + "cordova": "13.0.0", + "mocha": "9.2.2", + "umd-tough-cookie": "3.0.0", + "xml2js": "0.4.23" + }, + "overrides": { + "tar": "^7.5.22" + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/plugin.xml b/src/plugins/cordova-plugin-advanced-http/plugin.xml new file mode 100644 index 0000000000..fbc49cbca0 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/plugin.xml @@ -0,0 +1,56 @@ + + + Advanced HTTP plugin + + Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaClientAuth.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaClientAuth.java new file mode 100644 index 0000000000..b01ac936b8 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaClientAuth.java @@ -0,0 +1,113 @@ +package com.silkimen.cordovahttp; + +import android.app.Activity; +import android.content.Context; +import android.security.KeyChain; +import android.security.KeyChainAliasCallback; +import android.util.Log; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.URI; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; + +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; + +import org.apache.cordova.CallbackContext; + +import com.silkimen.http.KeyChainKeyManager; +import com.silkimen.http.TLSConfiguration; + +class CordovaClientAuth implements Runnable, KeyChainAliasCallback { + private static final String TAG = "Cordova-Plugin-HTTP"; + + private String mode; + private String aliasString; + private byte[] rawPkcs; + private String pkcsPassword; + private Activity activity; + private Context context; + private TLSConfiguration tlsConfiguration; + private CallbackContext callbackContext; + + public CordovaClientAuth(final String mode, final String aliasString, final byte[] rawPkcs, + final String pkcsPassword, final Activity activity, final Context context, final TLSConfiguration configContainer, + final CallbackContext callbackContext) { + + this.mode = mode; + this.aliasString = aliasString; + this.rawPkcs = rawPkcs; + this.pkcsPassword = pkcsPassword; + this.activity = activity; + this.tlsConfiguration = configContainer; + this.context = context; + this.callbackContext = callbackContext; + } + + @Override + public void run() { + if ("systemstore".equals(this.mode)) { + this.loadFromSystemStore(); + } else if ("buffer".equals(this.mode)) { + this.loadFromBuffer(); + } else { + this.disableClientAuth(); + } + } + + private void loadFromSystemStore() { + if (this.aliasString == null) { + KeyChain.choosePrivateKeyAlias(this.activity, this, null, null, null, -1, null); + } else { + this.alias(this.aliasString); + } + } + + private void loadFromBuffer() { + try { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm); + ByteArrayInputStream stream = new ByteArrayInputStream(this.rawPkcs); + + keyStore.load(stream, this.pkcsPassword.toCharArray()); + keyManagerFactory.init(keyStore, this.pkcsPassword.toCharArray()); + + this.tlsConfiguration.setKeyManagers(keyManagerFactory.getKeyManagers()); + this.callbackContext.success(); + } catch (Exception e) { + Log.e(TAG, "Couldn't load given PKCS12 container for authentication", e); + this.callbackContext.error("Couldn't load given PKCS12 container for authentication"); + } + } + + private void disableClientAuth() { + this.tlsConfiguration.setKeyManagers(null); + this.callbackContext.success(); + } + + @Override + public void alias(final String alias) { + try { + if (alias == null) { + throw new Exception("Couldn't get a consent for private key access"); + } + + PrivateKey key = KeyChain.getPrivateKey(this.context, alias); + X509Certificate[] chain = KeyChain.getCertificateChain(this.context, alias); + KeyManager keyManager = new KeyChainKeyManager(alias, key, chain); + + this.tlsConfiguration.setKeyManagers(new KeyManager[] { keyManager }); + + this.callbackContext.success(alias); + } catch (Exception e) { + Log.e(TAG, "Couldn't load private key and certificate pair with given alias \"" + alias + "\" for authentication", + e); + this.callbackContext.error( + "Couldn't load private key and certificate pair with given alias \"" + alias + "\" for authentication"); + } + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpBase.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpBase.java new file mode 100644 index 0000000000..aded97978d --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpBase.java @@ -0,0 +1,237 @@ +package com.silkimen.cordovahttp; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.IOException; + +import java.io.InterruptedIOException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; + +import java.nio.ByteBuffer; + +import javax.net.ssl.SSLException; + +import com.silkimen.http.HttpBodyDecoder; +import com.silkimen.http.HttpRequest; +import com.silkimen.http.HttpRequest.HttpRequestException; +import com.silkimen.http.JsonUtils; +import com.silkimen.http.TLSConfiguration; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import android.util.Base64; +import android.util.Log; + +abstract class CordovaHttpBase implements Runnable { + protected static final String TAG = "Cordova-Plugin-HTTP"; + + protected String method; + protected String url; + protected String serializer = "none"; + protected String responseType; + protected Object data; + protected JSONObject headers; + protected int connectTimeout; + protected int readTimeout; + protected boolean followRedirects; + protected TLSConfiguration tlsConfiguration; + protected CordovaObservableCallbackContext callbackContext; + + public CordovaHttpBase(String method, String url, String serializer, Object data, JSONObject headers, int connectTimeout, + int readTimeout, boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration, + CordovaObservableCallbackContext callbackContext) { + + this.method = method; + this.url = url; + this.serializer = serializer; + this.data = data; + this.headers = headers; + this.connectTimeout = connectTimeout; + this.readTimeout = readTimeout; + this.followRedirects = followRedirects; + this.responseType = responseType; + this.tlsConfiguration = tlsConfiguration; + this.callbackContext = callbackContext; + } + + public CordovaHttpBase(String method, String url, JSONObject headers, int connectTimeout, int readTimeout, boolean followRedirects, + String responseType, TLSConfiguration tlsConfiguration, CordovaObservableCallbackContext callbackContext) { + + this.method = method; + this.url = url; + this.headers = headers; + this.connectTimeout = connectTimeout; + this.readTimeout = readTimeout; + this.followRedirects = followRedirects; + this.responseType = responseType; + this.tlsConfiguration = tlsConfiguration; + this.callbackContext = callbackContext; + } + + @Override + public void run() { + CordovaHttpResponse response = new CordovaHttpResponse(); + HttpRequest request = null; + + try { + request = this.createRequest(); + this.prepareRequest(request); + this.sendBody(request); + this.processResponse(request, response); + request.disconnect(); + } catch (HttpRequestException e) { + Throwable cause = e.getCause(); + String message = cause.getMessage(); + + if (cause instanceof SSLException) { + response.setStatus(-2); + response.setErrorMessage("TLS connection could not be established: " + e.getMessage()); + Log.w(TAG, "TLS connection could not be established", e); + } else if (cause instanceof UnknownHostException) { + response.setStatus(-3); + response.setErrorMessage("Host could not be resolved: " + e.getMessage()); + Log.w(TAG, "Host could not be resolved", e); + } else if (cause instanceof SocketTimeoutException) { + response.setStatus(-4); + response.setErrorMessage("Request timed out: " + e.getMessage()); + Log.w(TAG, "Request timed out", e); + } else if (cause instanceof InterruptedIOException && "thread interrupted".equals(message.toLowerCase())) { + this.setAborted(request, response); + } else { + response.setStatus(-1); + response.setErrorMessage("There was an error with the request: " + message); + Log.w(TAG, "Generic request error", e); + } + } catch (InterruptedException ie) { + this.setAborted(request, response); + } catch (Exception e) { + response.setStatus(-1); + response.setErrorMessage(e.getMessage()); + Log.e(TAG, "An unexpected error occured", e); + } + + try { + if (response.hasFailed()) { + this.callbackContext.error(response.toJSON()); + } else { + this.callbackContext.success(response.toJSON()); + } + } catch (JSONException e) { + Log.e(TAG, "An unexpected error occured while creating HTTP response object", e); + } + } + + protected HttpRequest createRequest() throws JSONException { + return new HttpRequest(this.url, this.method); + } + + protected void prepareRequest(HttpRequest request) throws JSONException, IOException { + request.followRedirects(this.followRedirects); + request.connectTimeout(this.connectTimeout); + request.readTimeout(this.readTimeout); + request.acceptCharset("UTF-8"); + request.uncompress(true); + + if (this.tlsConfiguration.getHostnameVerifier() != null) { + request.setHostnameVerifier(this.tlsConfiguration.getHostnameVerifier()); + } + + request.setSSLSocketFactory(this.tlsConfiguration.getTLSSocketFactory()); + + // setup content type before applying headers, so user can override it + this.setContentType(request); + + request.headers(JsonUtils.getStringMap(this.headers)); + } + + protected void setContentType(HttpRequest request) { + if ("json".equals(this.serializer)) { + request.contentType("application/json", "UTF-8"); + } else if ("utf8".equals(this.serializer)) { + request.contentType("text/plain", "UTF-8"); + } else if ("raw".equals(this.serializer)) { + request.contentType("application/octet-stream"); + } else if ("urlencoded".equals(this.serializer)) { + // intentionally left blank, because content type is set in HttpRequest.form() + } else if ("multipart".equals(this.serializer)) { + // intentionally left blank, because content type is set in HttpRequest.part() + } + } + + protected void sendBody(HttpRequest request) throws Exception { + if (this.data == null) { + return; + } + + if ("json".equals(this.serializer)) { + request.send(this.data.toString()); + } else if ("utf8".equals(this.serializer)) { + request.send(((JSONObject) this.data).getString("text")); + } else if ("raw".equals(this.serializer)) { + request.send(Base64.decode((String)this.data, Base64.DEFAULT)); + } else if ("urlencoded".equals(this.serializer)) { + request.form(JsonUtils.getObjectMap((JSONObject) this.data)); + } else if ("multipart".equals(this.serializer)) { + JSONArray buffers = ((JSONObject) this.data).getJSONArray("buffers"); + JSONArray names = ((JSONObject) this.data).getJSONArray("names"); + JSONArray fileNames = ((JSONObject) this.data).getJSONArray("fileNames"); + JSONArray types = ((JSONObject) this.data).getJSONArray("types"); + + for (int i = 0; i < buffers.length(); ++i) { + byte[] bytes = Base64.decode(buffers.getString(i), Base64.DEFAULT); + String name = names.getString(i); + + if (fileNames.isNull(i)) { + request.part(name, new String(bytes, "UTF-8")); + } else { + request.part(name, fileNames.getString(i), types.getString(i), new ByteArrayInputStream(bytes)); + } + } + + // prevent sending malformed empty multipart requests (#372) + if (buffers.length() == 0) { + request.contentType("multipart/form-data; boundary=00content0boundary00"); + request.send("\r\n--00content0boundary00--\r\n"); + } + } + } + + protected void processResponse(HttpRequest request, CordovaHttpResponse response) throws Exception { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + request.receive(outputStream); + + response.setStatus(request.code()); + response.setUrl(request.url().toString()); + response.setHeaders(request.headers()); + + if (request.code() >= 200 && request.code() < 300) { + if ("text".equals(this.responseType) || "json".equals(this.responseType)) { + String decoded = HttpBodyDecoder.decodeBody(outputStream.toByteArray(), request.charset()); + response.setBody(decoded); + } else { + response.setData(outputStream.toByteArray()); + } + } else { + response.setErrorMessage(HttpBodyDecoder.decodeBody(outputStream.toByteArray(), request.charset())); + } + } + + protected void setAborted(HttpRequest request, CordovaHttpResponse response) { + response.setStatus(-8); + response.setErrorMessage("Request was aborted"); + + if (request != null) { + try { + request.disconnect(); + } catch(Exception any){ + Log.w(TAG, "Failed to close aborted request", any); + } + } + + Log.i(TAG, "Request was aborted"); + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpDownload.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpDownload.java new file mode 100644 index 0000000000..69b1fa5531 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpDownload.java @@ -0,0 +1,41 @@ +package com.silkimen.cordovahttp; + +import java.io.File; +import java.net.URI; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSocketFactory; + +import com.silkimen.http.HttpRequest; +import com.silkimen.http.TLSConfiguration; + +import org.apache.cordova.file.FileUtils; +import org.json.JSONObject; + +class CordovaHttpDownload extends CordovaHttpBase { + private String filePath; + + public CordovaHttpDownload(String url, JSONObject headers, String filePath, int connectTimeout, int readTimeout, + boolean followRedirects, TLSConfiguration tlsConfiguration, CordovaObservableCallbackContext callbackContext) { + + super("GET", url, headers, connectTimeout, readTimeout, followRedirects, "text", tlsConfiguration, callbackContext); + this.filePath = filePath; + } + + @Override + protected void processResponse(HttpRequest request, CordovaHttpResponse response) throws Exception { + response.setStatus(request.code()); + response.setUrl(request.url().toString()); + response.setHeaders(request.headers()); + + if (request.code() >= 200 && request.code() < 300) { + File file = new File(new URI(this.filePath)); + JSONObject fileEntry = FileUtils.getFilePlugin().getEntryForFile(file); + + request.receive(file); + response.setFileEntry(fileEntry); + } else { + response.setErrorMessage("There was an error downloading the file"); + } + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpOperation.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpOperation.java new file mode 100644 index 0000000000..d24ac8ee63 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpOperation.java @@ -0,0 +1,24 @@ +package com.silkimen.cordovahttp; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSocketFactory; + +import com.silkimen.http.TLSConfiguration; + +import org.json.JSONObject; + +class CordovaHttpOperation extends CordovaHttpBase { + public CordovaHttpOperation(String method, String url, String serializer, Object data, JSONObject headers, + int connectTimeout, int readTimeout, boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration, + CordovaObservableCallbackContext callbackContext) { + + super(method, url, serializer, data, headers, connectTimeout, readTimeout, followRedirects, responseType, tlsConfiguration, + callbackContext); + } + + public CordovaHttpOperation(String method, String url, JSONObject headers, int connectTimeout, int readTimeout, boolean followRedirects, + String responseType, TLSConfiguration tlsConfiguration, CordovaObservableCallbackContext callbackContext) { + + super(method, url, headers, connectTimeout, readTimeout, followRedirects, responseType, tlsConfiguration, callbackContext); + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpPlugin.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpPlugin.java new file mode 100644 index 0000000000..3823aef6ed --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpPlugin.java @@ -0,0 +1,299 @@ +package com.silkimen.cordovahttp; + +import java.security.KeyStore; +import java.util.HashMap; +import java.util.Observable; +import java.util.Observer; +import java.util.concurrent.Future; + +import com.silkimen.http.TLSConfiguration; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.CordovaWebView; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import android.content.Context; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.util.Log; +import android.util.Base64; + +import javax.net.ssl.TrustManagerFactory; + +public class CordovaHttpPlugin extends CordovaPlugin implements Observer { + private static final String TAG = "Cordova-Plugin-HTTP"; + + private TLSConfiguration tlsConfiguration; + + private HashMap> reqMap; + private final Object reqMapLock = new Object(); + + @Override + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); + + this.tlsConfiguration = new TLSConfiguration(); + + this.reqMap = new HashMap>(); + + try { + KeyStore store = KeyStore.getInstance("AndroidCAStore"); + String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); + + store.load(null); + tmf.init(store); + + this.tlsConfiguration.setHostnameVerifier(null); + this.tlsConfiguration.setTrustManagers(tmf.getTrustManagers()); + + if (this.preferences.contains("androidblacklistsecuresocketprotocols")) { + this.tlsConfiguration.setBlacklistedProtocols( + this.preferences.getString("androidblacklistsecuresocketprotocols", "").split(",") + ); + } + + } catch (Exception e) { + Log.e(TAG, "An error occured while loading system's CA certificates", e); + } + } + + @Override + public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) + throws JSONException { + + if (action == null) { + return false; + } + + if ("setServerTrustMode".equals(action)) { + return this.setServerTrustMode(args, callbackContext); + } else if ("setClientAuthMode".equals(action)) { + return this.setClientAuthMode(args, callbackContext); + } else if ("abort".equals(action)) { + return this.abort(args, callbackContext); + } + + boolean isLocal = false; + try { + if (args != null && args.length() > 0) { + String urlString = args.getString(0); + if (urlString != null) { + try { + java.net.URL url = new java.net.URL(urlString); + String host = url.getHost(); + if (host != null) { + host = host.toLowerCase().trim(); + if (host.equals("localhost") || host.equals("127.0.0.1") || host.equals("[::1]") || host.equals("::1") || host.startsWith("127.")) { + isLocal = true; + } + } + } catch (Exception e) { + String lower = urlString.toLowerCase(); + if (lower.contains("://localhost") || lower.contains("://127.0.0.1") || lower.contains("://[::1]") || lower.contains("://127.")) { + isLocal = true; + } + } + } + } + } catch (Exception e) { + // ignore + } + + if (!isLocal && !isNetworkAvailable()) { + CordovaHttpResponse response = new CordovaHttpResponse(); + response.setStatus(-6); + response.setErrorMessage("No network connection available"); + callbackContext.error(response.toJSON()); + + return true; + } + + if ("get".equals(action)) { + return this.executeHttpRequestWithoutData(action, args, callbackContext); + } else if ("head".equals(action)) { + return this.executeHttpRequestWithoutData(action, args, callbackContext); + } else if ("delete".equals(action)) { + return this.executeHttpRequestWithoutData(action, args, callbackContext); + } else if ("options".equals(action)) { + return this.executeHttpRequestWithoutData(action, args, callbackContext); + } else if ("post".equals(action)) { + return this.executeHttpRequestWithData(action, args, callbackContext); + } else if ("put".equals(action)) { + return this.executeHttpRequestWithData(action, args, callbackContext); + } else if ("patch".equals(action)) { + return this.executeHttpRequestWithData(action, args, callbackContext); + } else if ("uploadFiles".equals(action)) { + return this.uploadFiles(args, callbackContext); + } else if ("downloadFile".equals(action)) { + return this.downloadFile(args, callbackContext); + } else { + return false; + } + } + + private boolean executeHttpRequestWithoutData(final String method, final JSONArray args, + final CallbackContext callbackContext) throws JSONException { + + String url = args.getString(0); + JSONObject headers = args.getJSONObject(1); + int connectTimeout = args.getInt(2) * 1000; + int readTimeout = args.getInt(3) * 1000; + boolean followRedirect = args.getBoolean(4); + String responseType = args.getString(5); + Integer reqId = args.getInt(6); + + CordovaObservableCallbackContext observableCallbackContext = new CordovaObservableCallbackContext(callbackContext, reqId); + + CordovaHttpOperation request = new CordovaHttpOperation(method.toUpperCase(), url, headers, connectTimeout, readTimeout, + followRedirect, responseType, this.tlsConfiguration, observableCallbackContext); + + startRequest(reqId, observableCallbackContext, request); + + return true; + } + + private boolean executeHttpRequestWithData(final String method, final JSONArray args, + final CallbackContext callbackContext) throws JSONException { + + String url = args.getString(0); + Object data = args.get(1); + String serializer = args.getString(2); + JSONObject headers = args.getJSONObject(3); + int connectTimeout = args.getInt(4) * 1000; + int readTimeout = args.getInt(5) * 1000; + boolean followRedirect = args.getBoolean(6); + String responseType = args.getString(7); + Integer reqId = args.getInt(8); + + CordovaObservableCallbackContext observableCallbackContext = new CordovaObservableCallbackContext(callbackContext, reqId); + + CordovaHttpOperation request = new CordovaHttpOperation(method.toUpperCase(), url, serializer, data, headers, + connectTimeout, readTimeout, followRedirect, responseType, this.tlsConfiguration, observableCallbackContext); + + startRequest(reqId, observableCallbackContext, request); + + return true; + } + + private boolean uploadFiles(final JSONArray args, final CallbackContext callbackContext) throws JSONException { + String url = args.getString(0); + JSONObject headers = args.getJSONObject(1); + JSONArray filePaths = args.getJSONArray(2); + JSONArray uploadNames = args.getJSONArray(3); + int connectTimeout = args.getInt(4) * 1000; + int readTimeout = args.getInt(5) * 1000; + boolean followRedirect = args.getBoolean(6); + String responseType = args.getString(7); + Integer reqId = args.getInt(8); + + CordovaObservableCallbackContext observableCallbackContext = new CordovaObservableCallbackContext(callbackContext, reqId); + + CordovaHttpUpload upload = new CordovaHttpUpload(url, headers, filePaths, uploadNames, connectTimeout, readTimeout, followRedirect, + responseType, this.tlsConfiguration, this.cordova.getActivity().getApplicationContext(), observableCallbackContext); + + startRequest(reqId, observableCallbackContext, upload); + + return true; + } + + private boolean downloadFile(final JSONArray args, final CallbackContext callbackContext) throws JSONException { + String url = args.getString(0); + JSONObject headers = args.getJSONObject(1); + String filePath = args.getString(2); + int connectTimeout = args.getInt(3) * 1000; + int readTimeout = args.getInt(4) * 1000; + boolean followRedirect = args.getBoolean(5); + Integer reqId = args.getInt(6); + + CordovaObservableCallbackContext observableCallbackContext = new CordovaObservableCallbackContext(callbackContext, reqId); + + CordovaHttpDownload download = new CordovaHttpDownload(url, headers, filePath, connectTimeout, readTimeout, + followRedirect, this.tlsConfiguration, observableCallbackContext); + + startRequest(reqId, observableCallbackContext, download); + + return true; + } + + private void startRequest(Integer reqId, CordovaObservableCallbackContext observableCallbackContext, CordovaHttpBase request) { + synchronized (reqMapLock) { + observableCallbackContext.setObserver(this); + Future task = cordova.getThreadPool().submit(request); + this.addReq(reqId, task, observableCallbackContext); + } + } + + private boolean setServerTrustMode(final JSONArray args, final CallbackContext callbackContext) throws JSONException { + CordovaServerTrust runnable = new CordovaServerTrust(args.getString(0), this.cordova.getActivity(), + this.tlsConfiguration, callbackContext); + + cordova.getThreadPool().execute(runnable); + + return true; + } + + private boolean setClientAuthMode(final JSONArray args, final CallbackContext callbackContext) throws JSONException { + byte[] pkcs = args.isNull(2) ? null : Base64.decode(args.getString(2), Base64.DEFAULT); + + CordovaClientAuth runnable = new CordovaClientAuth(args.getString(0), args.isNull(1) ? null : args.getString(1), + pkcs, args.getString(3), this.cordova.getActivity(), this.cordova.getActivity().getApplicationContext(), + this.tlsConfiguration, callbackContext); + + cordova.getThreadPool().execute(runnable); + + return true; + } + + private boolean abort(final JSONArray args, final CallbackContext callbackContext) throws JSONException { + int reqId = args.getInt(0); + boolean result = false; + // NOTE no synchronized (reqMapLock), since even if the req was already removed from reqMap, + // the worst that would happen calling task.cancel(true) is a result of false + // (i.e. same result as locking & not finding the req in reqMap) + Future task = this.reqMap.get(reqId); + + if (task != null && !task.isDone()) { + result = task.cancel(true); + } + + callbackContext.success(new JSONObject().put("aborted", result)); + + return true; + } + + private void addReq(final Integer reqId, final Future task, final CordovaObservableCallbackContext observableCallbackContext) { + synchronized (reqMapLock) { + if (!task.isDone()){ + this.reqMap.put(reqId, task); + } + } + } + + private void removeReq(final Integer reqId) { + synchronized (reqMapLock) { + this.reqMap.remove(reqId); + } + } + + @Override + public void update(Observable o, Object arg) { + synchronized (reqMapLock) { + CordovaObservableCallbackContext c = (CordovaObservableCallbackContext) arg; + if (c.getCallbackContext().isFinished()) { + removeReq(c.getRequestId()); + } + } + } + + private boolean isNetworkAvailable() { + ConnectivityManager connectivityManager = (ConnectivityManager) cordova.getContext().getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); + + return activeNetworkInfo != null && activeNetworkInfo.isConnected(); + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpResponse.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpResponse.java new file mode 100644 index 0000000000..e6051bf30a --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpResponse.java @@ -0,0 +1,100 @@ +package com.silkimen.cordovahttp; + +import java.nio.ByteBuffer; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.json.JSONException; +import org.json.JSONObject; + +import android.text.TextUtils; +import android.util.Log; +import android.util.Base64; + +class CordovaHttpResponse { + private int status; + private String url; + private Map> headers; + private String body; + private byte[] rawData; + private JSONObject fileEntry; + private boolean hasFailed; + private boolean isFileOperation; + private boolean isRawResponse; + private String error; + + public void setStatus(int status) { + this.status = status; + } + + public void setUrl(String url) { + this.url = url; + } + + public void setHeaders(Map> headers) { + this.headers = headers; + } + + public void setBody(String body) { + this.body = body; + } + + public void setData(byte[] rawData) { + this.isRawResponse = true; + this.rawData = rawData; + } + + public void setFileEntry(JSONObject entry) { + this.isFileOperation = true; + this.fileEntry = entry; + } + + public void setErrorMessage(String message) { + this.hasFailed = true; + this.error = message; + } + + public boolean hasFailed() { + return this.hasFailed; + } + + public JSONObject toJSON() throws JSONException { + JSONObject json = new JSONObject(); + + json.put("status", this.status); + json.put("url", this.url); + + if (this.headers != null && !this.headers.isEmpty()) { + json.put("headers", new JSONObject(getFilteredHeaders())); + } + + if (this.hasFailed) { + json.put("error", this.error); + } else if (this.isFileOperation) { + json.put("file", this.fileEntry); + } else if (this.isRawResponse) { + json.put("data", Base64.encodeToString(this.rawData, Base64.DEFAULT)); + } else { + json.put("data", this.body); + } + + return json; + } + + private Map getFilteredHeaders() throws JSONException { + Map filteredHeaders = new HashMap(); + + for (Map.Entry> entry : this.headers.entrySet()) { + String key = entry.getKey(); + List value = entry.getValue(); + + if ((key != null) && (!value.isEmpty())) { + filteredHeaders.put(key.toLowerCase(), TextUtils.join(", ", value)); + } + } + + return filteredHeaders; + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpUpload.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpUpload.java new file mode 100644 index 0000000000..d37464d2b5 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpUpload.java @@ -0,0 +1,91 @@ +package com.silkimen.cordovahttp; + +import android.content.ContentResolver; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.provider.OpenableColumns; +import android.webkit.MimeTypeMap; + +import com.silkimen.http.HttpRequest; +import com.silkimen.http.TLSConfiguration; + +import java.io.File; +import java.io.InputStream; +import java.net.URI; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSocketFactory; + +import org.json.JSONArray; +import org.json.JSONObject; + +class CordovaHttpUpload extends CordovaHttpBase { + private JSONArray filePaths; + private JSONArray uploadNames; + private Context applicationContext; + + public CordovaHttpUpload(String url, JSONObject headers, JSONArray filePaths, JSONArray uploadNames, int connectTimeout, int readTimeout, + boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration, + Context applicationContext, CordovaObservableCallbackContext callbackContext) { + + super("POST", url, headers, connectTimeout, readTimeout, followRedirects, responseType, tlsConfiguration, callbackContext); + this.filePaths = filePaths; + this.uploadNames = uploadNames; + this.applicationContext = applicationContext; + } + + @Override + protected void sendBody(HttpRequest request) throws Exception { + for (int i = 0; i < this.filePaths.length(); ++i) { + String uploadName = this.uploadNames.getString(i); + String filePath = this.filePaths.getString(i); + + Uri fileUri = Uri.parse(filePath); + + // File Scheme + if (ContentResolver.SCHEME_FILE.equals(fileUri.getScheme())) { + File file = new File(new URI(filePath)); + String fileName = file.getName().trim(); + String mimeType = this.getMimeTypeFromFileName(fileName); + + request.part(uploadName, fileName, mimeType, file); + } + + // Content Scheme + if (ContentResolver.SCHEME_CONTENT.equals(fileUri.getScheme())) { + InputStream inputStream = this.applicationContext.getContentResolver().openInputStream(fileUri); + String fileName = this.getFileNameFromContentScheme(fileUri, this.applicationContext).trim(); + String mimeType = this.getMimeTypeFromFileName(fileName); + + request.part(uploadName, fileName, mimeType, inputStream); + } + } + } + + private String getFileNameFromContentScheme(Uri contentSchemeUri, Context applicationContext) { + Cursor returnCursor = applicationContext.getContentResolver().query(contentSchemeUri, null, null, null, null); + + if (returnCursor == null || !returnCursor.moveToFirst()) { + return null; + } + + int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); + String fileName = returnCursor.getString(nameIndex); + returnCursor.close(); + + return fileName; + } + + private String getMimeTypeFromFileName(String fileName) { + if (fileName == null || !fileName.contains(".")) { + return null; + } + + MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); + int extIndex = fileName.lastIndexOf('.') + 1; + String extension = fileName.substring(extIndex).toLowerCase(); + + return mimeTypeMap.getMimeTypeFromExtension(extension); + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaObservableCallbackContext.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaObservableCallbackContext.java new file mode 100644 index 0000000000..cff0583101 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaObservableCallbackContext.java @@ -0,0 +1,58 @@ +package com.silkimen.cordovahttp; + +import org.apache.cordova.CallbackContext; +import org.json.JSONObject; + +import java.util.Observer; + +public class CordovaObservableCallbackContext { + + private CallbackContext callbackContext; + private Integer requestId; + private Observer observer; + + public CordovaObservableCallbackContext(CallbackContext callbackContext, Integer requestId) { + this.callbackContext = callbackContext; + this.requestId = requestId; + } + + public void success(JSONObject message) { + this.callbackContext.success(message); + this.notifyObserver(); + } + + public void error(JSONObject message) { + this.callbackContext.error(message); + this.notifyObserver(); + } + + public Integer getRequestId() { + return this.requestId; + } + + public CallbackContext getCallbackContext() { + return callbackContext; + } + + public Observer getObserver() { + return observer; + } + + protected void notifyObserver() { + if(this.observer != null){ + this.observer.update(null, this); + } + } + + /** + * Set an observer that is notified, when {@link #success(JSONObject)} + * or {@link #error(JSONObject)} are called. + * + * NOTE the observer is notified with + *
observer.update(null, cordovaObservableCallbackContext)
+ * @param observer + */ + public void setObserver(Observer observer) { + this.observer = observer; + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaServerTrust.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaServerTrust.java new file mode 100644 index 0000000000..822079e353 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaServerTrust.java @@ -0,0 +1,124 @@ +package com.silkimen.cordovahttp; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +import com.silkimen.http.TLSConfiguration; + +import org.apache.cordova.CallbackContext; + +import android.app.Activity; +import android.util.Log; +import android.content.res.AssetManager; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +class CordovaServerTrust implements Runnable { + private static final String TAG = "Cordova-Plugin-HTTP"; + + private final TrustManager[] noOpTrustManagers; + private final HostnameVerifier noOpVerifier; + + private String mode; + private Activity activity; + private TLSConfiguration tlsConfiguration; + private CallbackContext callbackContext; + + public CordovaServerTrust(final String mode, final Activity activity, final TLSConfiguration configContainer, + final CallbackContext callbackContext) { + + this.mode = mode; + this.activity = activity; + this.tlsConfiguration = configContainer; + this.callbackContext = callbackContext; + + this.noOpTrustManagers = new TrustManager[] { new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + public void checkClientTrusted(X509Certificate[] chain, String authType) { + // intentionally left blank + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) { + // intentionally left blank + } + } }; + + this.noOpVerifier = new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + } + + @Override + public void run() { + try { + if ("legacy".equals(this.mode)) { + this.tlsConfiguration.setHostnameVerifier(null); + this.tlsConfiguration.setTrustManagers(null); + } else if ("nocheck".equals(this.mode)) { + this.tlsConfiguration.setHostnameVerifier(this.noOpVerifier); + this.tlsConfiguration.setTrustManagers(this.noOpTrustManagers); + } else if ("pinned".equals(this.mode)) { + this.tlsConfiguration.setHostnameVerifier(null); + this.tlsConfiguration.setTrustManagers(this.getTrustManagers(this.getCertsFromBundle("www/certificates"))); + } else { + this.tlsConfiguration.setHostnameVerifier(null); + this.tlsConfiguration.setTrustManagers(this.getTrustManagers(this.getCertsFromKeyStore("AndroidCAStore"))); + } + + callbackContext.success(); + } catch (Exception e) { + Log.e(TAG, "An error occured while configuring SSL cert mode", e); + callbackContext.error("An error occured while configuring SSL cert mode"); + } + } + + private TrustManager[] getTrustManagers(KeyStore store) throws GeneralSecurityException { + String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); + tmf.init(store); + + return tmf.getTrustManagers(); + } + + private KeyStore getCertsFromBundle(String path) throws GeneralSecurityException, IOException { + AssetManager assetManager = this.activity.getAssets(); + String[] files = assetManager.list(path); + + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + String keyStoreType = KeyStore.getDefaultType(); + KeyStore keyStore = KeyStore.getInstance(keyStoreType); + + keyStore.load(null, null); + + for (int i = 0; i < files.length; i++) { + int index = files[i].lastIndexOf('.'); + + if (index == -1 || !files[i].substring(index).equals(".cer")) { + continue; + } + + keyStore.setCertificateEntry("CA" + i, cf.generateCertificate(assetManager.open(path + "/" + files[i]))); + } + + return keyStore; + } + + private KeyStore getCertsFromKeyStore(String storeType) throws GeneralSecurityException, IOException { + KeyStore store = KeyStore.getInstance(storeType); + store.load(null); + + return store; + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpBodyDecoder.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpBodyDecoder.java new file mode 100644 index 0000000000..92d69e2c15 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpBodyDecoder.java @@ -0,0 +1,55 @@ +package com.silkimen.http; + +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.MalformedInputException; + +public class HttpBodyDecoder { + private static final String[] ACCEPTED_CHARSETS = new String[] { "UTF-8", "ISO-8859-1" }; + + public static String decodeBody(byte[] body, String charsetName) + throws CharacterCodingException, MalformedInputException { + + return decodeBody(ByteBuffer.wrap(body), charsetName); + } + + public static String decodeBody(ByteBuffer body, String charsetName) + throws CharacterCodingException, MalformedInputException { + + if (charsetName == null) { + return tryDecodeByteBuffer(body); + } else { + return decodeByteBuffer(body, charsetName); + } + } + + private static String tryDecodeByteBuffer(ByteBuffer buffer) + throws CharacterCodingException, MalformedInputException { + + for (int i = 0; i < ACCEPTED_CHARSETS.length - 1; i++) { + try { + return decodeByteBuffer(buffer, ACCEPTED_CHARSETS[i]); + } catch (MalformedInputException e) { + continue; + } catch (CharacterCodingException e) { + continue; + } + } + + return decodeBody(buffer, ACCEPTED_CHARSETS[ACCEPTED_CHARSETS.length - 1]); + } + + private static String decodeByteBuffer(ByteBuffer buffer, String charsetName) + throws CharacterCodingException, MalformedInputException { + + return createCharsetDecoder(charsetName).decode(buffer).toString(); + } + + private static CharsetDecoder createCharsetDecoder(String charsetName) { + return Charset.forName(charsetName).newDecoder().onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT); + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpRequest.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpRequest.java new file mode 100644 index 0000000000..7e638bb141 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpRequest.java @@ -0,0 +1,3095 @@ +/* + * Copyright (c) 2014 Kevin Sawicki + * modified by contributors of cordova-plugin-advanced-http + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.silkimen.http; + +import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; +import static java.net.HttpURLConnection.HTTP_CREATED; +import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; +import static java.net.HttpURLConnection.HTTP_NO_CONTENT; +import static java.net.HttpURLConnection.HTTP_NOT_FOUND; +import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED; +import static java.net.HttpURLConnection.HTTP_OK; +import static java.net.Proxy.Type.HTTP; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.Flushable; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintStream; +import java.io.Reader; +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.net.MalformedURLException; +import java.net.Proxy; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; +import java.security.AccessController; +import java.security.GeneralSecurityException; +import java.security.PrivilegedAction; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.zip.GZIPInputStream; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +/** + * A fluid interface for making HTTP requests using an underlying + * {@link HttpURLConnection} (or sub-class). + *

+ * Each instance supports making a single request and cannot be reused for + * further requests. + */ +public class HttpRequest { + + /** + * 'UTF-8' charset name + */ + public static final String CHARSET_UTF8 = "UTF-8"; + + /** + * 'application/x-www-form-urlencoded' content type header value + */ + public static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded"; + + /** + * 'application/json' content type header value + */ + public static final String CONTENT_TYPE_JSON = "application/json"; + + /** + * 'gzip' encoding header value + */ + public static final String ENCODING_GZIP = "gzip"; + + /** + * 'Accept' header name + */ + public static final String HEADER_ACCEPT = "Accept"; + + /** + * 'Accept-Charset' header name + */ + public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset"; + + /** + * 'Accept-Encoding' header name + */ + public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; + + /** + * 'Authorization' header name + */ + public static final String HEADER_AUTHORIZATION = "Authorization"; + + /** + * 'Cache-Control' header name + */ + public static final String HEADER_CACHE_CONTROL = "Cache-Control"; + + /** + * 'Content-Encoding' header name + */ + public static final String HEADER_CONTENT_ENCODING = "Content-Encoding"; + + /** + * 'Content-Length' header name + */ + public static final String HEADER_CONTENT_LENGTH = "Content-Length"; + + /** + * 'Content-Type' header name + */ + public static final String HEADER_CONTENT_TYPE = "Content-Type"; + + /** + * 'Date' header name + */ + public static final String HEADER_DATE = "Date"; + + /** + * 'ETag' header name + */ + public static final String HEADER_ETAG = "ETag"; + + /** + * 'Expires' header name + */ + public static final String HEADER_EXPIRES = "Expires"; + + /** + * 'If-None-Match' header name + */ + public static final String HEADER_IF_NONE_MATCH = "If-None-Match"; + + /** + * 'Last-Modified' header name + */ + public static final String HEADER_LAST_MODIFIED = "Last-Modified"; + + /** + * 'Location' header name + */ + public static final String HEADER_LOCATION = "Location"; + + /** + * 'Proxy-Authorization' header name + */ + public static final String HEADER_PROXY_AUTHORIZATION = "Proxy-Authorization"; + + /** + * 'Referer' header name + */ + public static final String HEADER_REFERER = "Referer"; + + /** + * 'Server' header name + */ + public static final String HEADER_SERVER = "Server"; + + /** + * 'User-Agent' header name + */ + public static final String HEADER_USER_AGENT = "User-Agent"; + + /** + * 'DELETE' request method + */ + public static final String METHOD_DELETE = "DELETE"; + + /** + * 'GET' request method + */ + public static final String METHOD_GET = "GET"; + + /** + * 'HEAD' request method + */ + public static final String METHOD_HEAD = "HEAD"; + + /** + * 'OPTIONS' options method + */ + public static final String METHOD_OPTIONS = "OPTIONS"; + + /** + * 'POST' request method + */ + public static final String METHOD_POST = "POST"; + + /** + * 'PUT' request method + */ + public static final String METHOD_PUT = "PUT"; + + /** + * 'TRACE' request method + */ + public static final String METHOD_TRACE = "TRACE"; + + /** + * 'charset' header value parameter + */ + public static final String PARAM_CHARSET = "charset"; + + private static final String BOUNDARY = "00content0boundary00"; + + private static final String CONTENT_TYPE_MULTIPART = "multipart/form-data; boundary=" + BOUNDARY; + + private static final String CRLF = "\r\n"; + + private static final String[] EMPTY_STRINGS = new String[0]; + + private static String getValidCharset(final String charset) { + if (charset != null && charset.length() > 0) + return charset; + else + return CHARSET_UTF8; + } + + private static StringBuilder addPathSeparator(final String baseUrl, final StringBuilder result) { + // Add trailing slash if the base URL doesn't have any path segments. + // + // The following test is checking for the last slash not being part of + // the protocol to host separator: '://'. + if (baseUrl.indexOf(':') + 2 == baseUrl.lastIndexOf('/')) + result.append('/'); + return result; + } + + private static StringBuilder addParamPrefix(final String baseUrl, final StringBuilder result) { + // Add '?' if missing and add '&' if params already exist in base url + final int queryStart = baseUrl.indexOf('?'); + final int lastChar = result.length() - 1; + if (queryStart == -1) + result.append('?'); + else if (queryStart < lastChar && baseUrl.charAt(lastChar) != '&') + result.append('&'); + return result; + } + + private static StringBuilder addParam(final Object key, Object value, final StringBuilder result) { + if (value != null && value.getClass().isArray()) + value = arrayToList(value); + + if (value instanceof Iterable) { + Iterator iterator = ((Iterable) value).iterator(); + while (iterator.hasNext()) { + result.append(key); + result.append("[]="); + Object element = iterator.next(); + if (element != null) + result.append(element); + if (iterator.hasNext()) + result.append("&"); + } + } else { + result.append(key); + result.append("="); + if (value != null) + result.append(value); + } + + return result; + } + + /** + * Creates {@link HttpURLConnection HTTP connections} for {@link URL urls}. + */ + public interface ConnectionFactory { + /** + * Open an {@link HttpURLConnection} for the specified {@link URL}. + * + * @throws IOException + */ + HttpURLConnection create(URL url) throws IOException; + + /** + * Open an {@link HttpURLConnection} for the specified {@link URL} and + * {@link Proxy}. + * + * @throws IOException + */ + HttpURLConnection create(URL url, Proxy proxy) throws IOException; + + /** + * A {@link ConnectionFactory} which uses the built-in + * {@link URL#openConnection()} + */ + ConnectionFactory DEFAULT = new ConnectionFactory() { + public HttpURLConnection create(URL url) throws IOException { + return (HttpURLConnection) url.openConnection(); + } + + public HttpURLConnection create(URL url, Proxy proxy) throws IOException { + return (HttpURLConnection) url.openConnection(proxy); + } + }; + } + + private static ConnectionFactory CONNECTION_FACTORY = ConnectionFactory.DEFAULT; + + /** + * Specify the {@link ConnectionFactory} used to create new requests. + */ + public static void setConnectionFactory(final ConnectionFactory connectionFactory) { + if (connectionFactory == null) + CONNECTION_FACTORY = ConnectionFactory.DEFAULT; + else + CONNECTION_FACTORY = connectionFactory; + } + + /** + * Callback interface for reporting upload progress for a request. + */ + public interface UploadProgress { + /** + * Callback invoked as data is uploaded by the request. + * + * @param uploaded The number of bytes already uploaded + * @param total The total number of bytes that will be uploaded or -1 if the + * length is unknown. + */ + void onUpload(long uploaded, long total); + + UploadProgress DEFAULT = new UploadProgress() { + public void onUpload(long uploaded, long total) { + } + }; + } + + /** + *

+ * Encodes and decodes to and from Base64 notation. + *

+ *

+ * I am placing this code in the Public Domain. Do with it as you will. This + * software comes with no guarantees or warranties but with plenty of + * well-wishing instead! Please visit + * http://iharder.net/base64 + * periodically to check for updates or to contribute improvements. + *

+ * + * @author Robert Harder + * @author rob@iharder.net + * @version 2.3.7 + */ + public static class Base64 { + + /** The equals sign (=) as a byte. */ + private final static byte EQUALS_SIGN = (byte) '='; + + /** Preferred encoding. */ + private final static String PREFERRED_ENCODING = "US-ASCII"; + + /** The 64 valid Base64 values. */ + private final static byte[] _STANDARD_ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', + (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', + (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', + (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', + (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', + (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', + (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', + (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' }; + + /** Defeats instantiation. */ + private Base64() { + } + + /** + *

+ * Encodes up to three bytes of the array source and writes the + * resulting four Base64 bytes to destination. The source and + * destination arrays can be manipulated anywhere along their length by + * specifying srcOffset and destOffset. This method does + * not check to make sure your arrays are large enough to accomodate + * srcOffset + 3 for the source array or + * destOffset + 4 for the destination array. The actual + * number of significant bytes in your array is given by numSigBytes. + *

+ *

+ * This is the lowest level of the encoding methods with all possible + * parameters. + *

+ * + * @param source the array to convert + * @param srcOffset the index where conversion begins + * @param numSigBytes the number of significant bytes in your array + * @param destination the array to hold the conversion + * @param destOffset the index where output will be put + * @return the destination array + * @since 1.3 + */ + private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, + int destOffset) { + + byte[] ALPHABET = _STANDARD_ALPHABET; + + int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) + | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) + | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); + + switch (numSigBytes) { + case 3: + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; + destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f]; + return destination; + + case 2: + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; + destination[destOffset + 3] = EQUALS_SIGN; + return destination; + + case 1: + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = EQUALS_SIGN; + destination[destOffset + 3] = EQUALS_SIGN; + return destination; + + default: + return destination; + } + } + + /** + * Encode string as a byte array in Base64 annotation. + * + * @param string + * @return The Base64-encoded data as a string + */ + public static String encode(String string) { + byte[] bytes; + try { + bytes = string.getBytes(PREFERRED_ENCODING); + } catch (UnsupportedEncodingException e) { + bytes = string.getBytes(); + } + return encodeBytes(bytes); + } + + /** + * Encodes a byte array into Base64 notation. + * + * @param source The data to convert + * @return The Base64-encoded data as a String + * @throws NullPointerException if source array is null + * @throws IllegalArgumentException if source array, offset, or length are + * invalid + * @since 2.0 + */ + public static String encodeBytes(byte[] source) { + return encodeBytes(source, 0, source.length); + } + + /** + * Encodes a byte array into Base64 notation. + * + * @param source The data to convert + * @param off Offset in array where conversion should begin + * @param len Length of data to convert + * @return The Base64-encoded data as a String + * @throws NullPointerException if source array is null + * @throws IllegalArgumentException if source array, offset, or length are + * invalid + * @since 2.0 + */ + public static String encodeBytes(byte[] source, int off, int len) { + byte[] encoded = encodeBytesToBytes(source, off, len); + try { + return new String(encoded, PREFERRED_ENCODING); + } catch (UnsupportedEncodingException uue) { + return new String(encoded); + } + } + + /** + * Similar to {@link #encodeBytes(byte[], int, int)} but returns a byte array + * instead of instantiating a String. This is more efficient if you're working + * with I/O streams and have large data sets to encode. + * + * + * @param source The data to convert + * @param off Offset in array where conversion should begin + * @param len Length of data to convert + * @return The Base64-encoded data as a String if there is an error + * @throws NullPointerException if source array is null + * @throws IllegalArgumentException if source array, offset, or length are + * invalid + * @since 2.3.1 + */ + public static byte[] encodeBytesToBytes(byte[] source, int off, int len) { + + if (source == null) + throw new NullPointerException("Cannot serialize a null array."); + + if (off < 0) + throw new IllegalArgumentException("Cannot have negative offset: " + off); + + if (len < 0) + throw new IllegalArgumentException("Cannot have length offset: " + len); + + if (off + len > source.length) + throw new IllegalArgumentException(String + .format("Cannot have offset of %d and length of %d with array of length %d", off, len, source.length)); + + // Bytes needed for actual encoding + int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); + + byte[] outBuff = new byte[encLen]; + + int d = 0; + int e = 0; + int len2 = len - 2; + for (; d < len2; d += 3, e += 4) + encode3to4(source, d + off, 3, outBuff, e); + + if (d < len) { + encode3to4(source, d + off, len - d, outBuff, e); + e += 4; + } + + if (e <= outBuff.length - 1) { + byte[] finalOut = new byte[e]; + System.arraycopy(outBuff, 0, finalOut, 0, e); + return finalOut; + } else + return outBuff; + } + } + + /** + * HTTP request exception whose cause is always an {@link IOException} + */ + public static class HttpRequestException extends RuntimeException { + + private static final long serialVersionUID = -1170466989781746231L; + + /** + * Create a new HttpRequestException with the given cause + * + * @param cause + */ + public HttpRequestException(final IOException cause) { + super(cause); + } + + /** + * Get {@link IOException} that triggered this request exception + * + * @return {@link IOException} cause + */ + @Override + public IOException getCause() { + return (IOException) super.getCause(); + } + } + + /** + * Operation that handles executing a callback once complete and handling nested + * exceptions + * + * @param + */ + protected static abstract class Operation implements Callable { + + /** + * Run operation + * + * @return result + * @throws HttpRequestException + * @throws IOException + */ + protected abstract V run() throws HttpRequestException, IOException; + + /** + * Operation complete callback + * + * @throws IOException + */ + protected abstract void done() throws IOException; + + public V call() throws HttpRequestException { + boolean thrown = false; + try { + return run(); + } catch (HttpRequestException e) { + thrown = true; + throw e; + } catch (IOException e) { + thrown = true; + throw new HttpRequestException(e); + } finally { + try { + done(); + } catch (IOException e) { + if (!thrown) + throw new HttpRequestException(e); + } + } + } + } + + /** + * Class that ensures a {@link Closeable} gets closed with proper exception + * handling. + * + * @param + */ + protected static abstract class CloseOperation extends Operation { + + private final Closeable closeable; + + private final boolean ignoreCloseExceptions; + + /** + * Create closer for operation + * + * @param closeable + * @param ignoreCloseExceptions + */ + protected CloseOperation(final Closeable closeable, final boolean ignoreCloseExceptions) { + this.closeable = closeable; + this.ignoreCloseExceptions = ignoreCloseExceptions; + } + + @Override + protected void done() throws IOException { + if (closeable instanceof Flushable) + ((Flushable) closeable).flush(); + if (ignoreCloseExceptions) + try { + closeable.close(); + } catch (IOException e) { + // Ignored + } + else + closeable.close(); + } + } + + /** + * Class that and ensures a {@link Flushable} gets flushed with proper exception + * handling. + * + * @param + */ + protected static abstract class FlushOperation extends Operation { + + private final Flushable flushable; + + /** + * Create flush operation + * + * @param flushable + */ + protected FlushOperation(final Flushable flushable) { + this.flushable = flushable; + } + + @Override + protected void done() throws IOException { + flushable.flush(); + } + } + + /** + * Request output stream + */ + public static class RequestOutputStream extends BufferedOutputStream { + + private final CharsetEncoder encoder; + + /** + * Create request output stream + * + * @param stream + * @param charset + * @param bufferSize + */ + public RequestOutputStream(final OutputStream stream, final String charset, final int bufferSize) { + super(stream, bufferSize); + + encoder = Charset.forName(getValidCharset(charset)).newEncoder(); + } + + /** + * Write string to stream + * + * @param value + * @return this stream + * @throws IOException + */ + public RequestOutputStream write(final String value) throws IOException { + final ByteBuffer bytes = encoder.encode(CharBuffer.wrap(value)); + + super.write(bytes.array(), 0, bytes.limit()); + + return this; + } + } + + /** + * Represents array of any type as list of objects so we can easily iterate over + * it + * + * @param array of elements + * @return list with the same elements + */ + private static List arrayToList(final Object array) { + if (array instanceof Object[]) + return Arrays.asList((Object[]) array); + + List result = new ArrayList(); + // Arrays of the primitive types can't be cast to array of Object, so this: + if (array instanceof int[]) + for (int value : (int[]) array) + result.add(value); + else if (array instanceof boolean[]) + for (boolean value : (boolean[]) array) + result.add(value); + else if (array instanceof long[]) + for (long value : (long[]) array) + result.add(value); + else if (array instanceof float[]) + for (float value : (float[]) array) + result.add(value); + else if (array instanceof double[]) + for (double value : (double[]) array) + result.add(value); + else if (array instanceof short[]) + for (short value : (short[]) array) + result.add(value); + else if (array instanceof byte[]) + for (byte value : (byte[]) array) + result.add(value); + else if (array instanceof char[]) + for (char value : (char[]) array) + result.add(value); + return result; + } + + /** + * Encode the given URL as an ASCII {@link String} + *

+ * This method ensures the path and query segments of the URL are properly + * encoded such as ' ' characters being encoded to '%20' or any UTF-8 characters + * that are non-ASCII. No encoding of URLs is done by default by the + * {@link HttpRequest} constructors and so if URL encoding is needed this method + * should be called before calling the {@link HttpRequest} constructor. + * + * @param url + * @return encoded URL + * @throws HttpRequestException + */ + public static String encode(final CharSequence url) throws HttpRequestException { + URL parsed; + try { + parsed = new URL(url.toString()); + } catch (IOException e) { + throw new HttpRequestException(e); + } + + String host = parsed.getHost(); + int port = parsed.getPort(); + if (port != -1) + host = host + ':' + Integer.toString(port); + + try { + String encoded = new URI(parsed.getProtocol(), host, parsed.getPath(), parsed.getQuery(), null).toASCIIString(); + int paramsStart = encoded.indexOf('?'); + if (paramsStart > 0 && paramsStart + 1 < encoded.length()) + encoded = encoded.substring(0, paramsStart + 1) + encoded.substring(paramsStart + 1).replace("+", "%2B"); + return encoded; + } catch (URISyntaxException e) { + IOException io = new IOException("Parsing URI failed"); + io.initCause(e); + throw new HttpRequestException(io); + } + } + + /** + * Append given map as query parameters to the base URL + *

+ * Each map entry's key will be a parameter name and the value's + * {@link Object#toString()} will be the parameter value. + * + * @param url + * @param params + * @return URL with appended query params + */ + public static String append(final CharSequence url, final Map params) { + final String baseUrl = url.toString(); + if (params == null || params.isEmpty()) + return baseUrl; + + final StringBuilder result = new StringBuilder(baseUrl); + + addPathSeparator(baseUrl, result); + addParamPrefix(baseUrl, result); + + Entry entry; + Iterator iterator = params.entrySet().iterator(); + entry = (Entry) iterator.next(); + addParam(entry.getKey().toString(), entry.getValue(), result); + + while (iterator.hasNext()) { + result.append('&'); + entry = (Entry) iterator.next(); + addParam(entry.getKey().toString(), entry.getValue(), result); + } + + return result.toString(); + } + + /** + * Append given name/value pairs as query parameters to the base URL + *

+ * The params argument is interpreted as a sequence of name/value pairs so the + * given number of params must be divisible by 2. + * + * @param url + * @param params name/value pairs + * @return URL with appended query params + */ + public static String append(final CharSequence url, final Object... params) { + final String baseUrl = url.toString(); + if (params == null || params.length == 0) + return baseUrl; + + if (params.length % 2 != 0) + throw new IllegalArgumentException("Must specify an even number of parameter names/values"); + + final StringBuilder result = new StringBuilder(baseUrl); + + addPathSeparator(baseUrl, result); + addParamPrefix(baseUrl, result); + + addParam(params[0], params[1], result); + + for (int i = 2; i < params.length; i += 2) { + result.append('&'); + addParam(params[i], params[i + 1], result); + } + + return result.toString(); + } + + /** + * Start a 'GET' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest get(final CharSequence url) throws HttpRequestException { + return new HttpRequest(url, METHOD_GET); + } + + /** + * Start a 'GET' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest get(final URL url) throws HttpRequestException { + return new HttpRequest(url, METHOD_GET); + } + + /** + * Start a 'GET' request to the given URL along with the query params + * + * @param baseUrl + * @param params The query parameters to include as part of the baseUrl + * @param encode true to encode the full URL + * + * @see #append(CharSequence, Map) + * @see #encode(CharSequence) + * + * @return request + */ + public static HttpRequest get(final CharSequence baseUrl, final Map params, final boolean encode) { + String url = append(baseUrl, params); + return get(encode ? encode(url) : url); + } + + /** + * Start a 'GET' request to the given URL along with the query params + * + * @param baseUrl + * @param encode true to encode the full URL + * @param params the name/value query parameter pairs to include as part of the + * baseUrl + * + * @see #append(CharSequence, Object...) + * @see #encode(CharSequence) + * + * @return request + */ + public static HttpRequest get(final CharSequence baseUrl, final boolean encode, final Object... params) { + String url = append(baseUrl, params); + return get(encode ? encode(url) : url); + } + + /** + * Start a 'POST' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest post(final CharSequence url) throws HttpRequestException { + return new HttpRequest(url, METHOD_POST); + } + + /** + * Start a 'POST' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest post(final URL url) throws HttpRequestException { + return new HttpRequest(url, METHOD_POST); + } + + /** + * Start a 'POST' request to the given URL along with the query params + * + * @param baseUrl + * @param params the query parameters to include as part of the baseUrl + * @param encode true to encode the full URL + * + * @see #append(CharSequence, Map) + * @see #encode(CharSequence) + * + * @return request + */ + public static HttpRequest post(final CharSequence baseUrl, final Map params, final boolean encode) { + String url = append(baseUrl, params); + return post(encode ? encode(url) : url); + } + + /** + * Start a 'POST' request to the given URL along with the query params + * + * @param baseUrl + * @param encode true to encode the full URL + * @param params the name/value query parameter pairs to include as part of the + * baseUrl + * + * @see #append(CharSequence, Object...) + * @see #encode(CharSequence) + * + * @return request + */ + public static HttpRequest post(final CharSequence baseUrl, final boolean encode, final Object... params) { + String url = append(baseUrl, params); + return post(encode ? encode(url) : url); + } + + /** + * Start a 'PUT' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest put(final CharSequence url) throws HttpRequestException { + return new HttpRequest(url, METHOD_PUT); + } + + /** + * Start a 'PUT' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest put(final URL url) throws HttpRequestException { + return new HttpRequest(url, METHOD_PUT); + } + + /** + * Start a 'PUT' request to the given URL along with the query params + * + * @param baseUrl + * @param params the query parameters to include as part of the baseUrl + * @param encode true to encode the full URL + * + * @see #append(CharSequence, Map) + * @see #encode(CharSequence) + * + * @return request + */ + public static HttpRequest put(final CharSequence baseUrl, final Map params, final boolean encode) { + String url = append(baseUrl, params); + return put(encode ? encode(url) : url); + } + + /** + * Start a 'PUT' request to the given URL along with the query params + * + * @param baseUrl + * @param encode true to encode the full URL + * @param params the name/value query parameter pairs to include as part of the + * baseUrl + * + * @see #append(CharSequence, Object...) + * @see #encode(CharSequence) + * + * @return request + */ + public static HttpRequest put(final CharSequence baseUrl, final boolean encode, final Object... params) { + String url = append(baseUrl, params); + return put(encode ? encode(url) : url); + } + + /** + * Start a 'DELETE' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest delete(final CharSequence url) throws HttpRequestException { + return new HttpRequest(url, METHOD_DELETE); + } + + /** + * Start a 'DELETE' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest delete(final URL url) throws HttpRequestException { + return new HttpRequest(url, METHOD_DELETE); + } + + /** + * Start a 'DELETE' request to the given URL along with the query params + * + * @param baseUrl + * @param params The query parameters to include as part of the baseUrl + * @param encode true to encode the full URL + * + * @see #append(CharSequence, Map) + * @see #encode(CharSequence) + * + * @return request + */ + public static HttpRequest delete(final CharSequence baseUrl, final Map params, final boolean encode) { + String url = append(baseUrl, params); + return delete(encode ? encode(url) : url); + } + + /** + * Start a 'DELETE' request to the given URL along with the query params + * + * @param baseUrl + * @param encode true to encode the full URL + * @param params the name/value query parameter pairs to include as part of the + * baseUrl + * + * @see #append(CharSequence, Object...) + * @see #encode(CharSequence) + * + * @return request + */ + public static HttpRequest delete(final CharSequence baseUrl, final boolean encode, final Object... params) { + String url = append(baseUrl, params); + return delete(encode ? encode(url) : url); + } + + /** + * Start a 'HEAD' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest head(final CharSequence url) throws HttpRequestException { + return new HttpRequest(url, METHOD_HEAD); + } + + /** + * Start a 'HEAD' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest head(final URL url) throws HttpRequestException { + return new HttpRequest(url, METHOD_HEAD); + } + + /** + * Start a 'HEAD' request to the given URL along with the query params + * + * @param baseUrl + * @param params The query parameters to include as part of the baseUrl + * @param encode true to encode the full URL + * + * @see #append(CharSequence, Map) + * @see #encode(CharSequence) + * + * @return request + */ + public static HttpRequest head(final CharSequence baseUrl, final Map params, final boolean encode) { + String url = append(baseUrl, params); + return head(encode ? encode(url) : url); + } + + /** + * Start a 'GET' request to the given URL along with the query params + * + * @param baseUrl + * @param encode true to encode the full URL + * @param params the name/value query parameter pairs to include as part of the + * baseUrl + * + * @see #append(CharSequence, Object...) + * @see #encode(CharSequence) + * + * @return request + */ + public static HttpRequest head(final CharSequence baseUrl, final boolean encode, final Object... params) { + String url = append(baseUrl, params); + return head(encode ? encode(url) : url); + } + + /** + * Start an 'OPTIONS' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest options(final CharSequence url) throws HttpRequestException { + return new HttpRequest(url, METHOD_OPTIONS); + } + + /** + * Start an 'OPTIONS' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest options(final URL url) throws HttpRequestException { + return new HttpRequest(url, METHOD_OPTIONS); + } + + /** + * Start a 'TRACE' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest trace(final CharSequence url) throws HttpRequestException { + return new HttpRequest(url, METHOD_TRACE); + } + + /** + * Start a 'TRACE' request to the given URL + * + * @param url + * @return request + * @throws HttpRequestException + */ + public static HttpRequest trace(final URL url) throws HttpRequestException { + return new HttpRequest(url, METHOD_TRACE); + } + + /** + * Set the 'http.keepAlive' property to the given value. + *

+ * This setting will apply to all requests. + * + * @param keepAlive + */ + public static void keepAlive(final boolean keepAlive) { + setProperty("http.keepAlive", Boolean.toString(keepAlive)); + } + + /** + * Set the 'http.maxConnections' property to the given value. + *

+ * This setting will apply to all requests. + * + * @param maxConnections + */ + public static void maxConnections(final int maxConnections) { + setProperty("http.maxConnections", Integer.toString(maxConnections)); + } + + /** + * Set the 'http.proxyHost' and 'https.proxyHost' properties to the given host + * value. + *

+ * This setting will apply to all requests. + * + * @param host + */ + public static void proxyHost(final String host) { + setProperty("http.proxyHost", host); + setProperty("https.proxyHost", host); + } + + /** + * Set the 'http.proxyPort' and 'https.proxyPort' properties to the given port + * number. + *

+ * This setting will apply to all requests. + * + * @param port + */ + public static void proxyPort(final int port) { + final String portValue = Integer.toString(port); + setProperty("http.proxyPort", portValue); + setProperty("https.proxyPort", portValue); + } + + /** + * Set the 'http.nonProxyHosts' property to the given host values. + *

+ * Hosts will be separated by a '|' character. + *

+ * This setting will apply to all requests. + * + * @param hosts + */ + public static void nonProxyHosts(final String... hosts) { + if (hosts != null && hosts.length > 0) { + StringBuilder separated = new StringBuilder(); + int last = hosts.length - 1; + for (int i = 0; i < last; i++) + separated.append(hosts[i]).append('|'); + separated.append(hosts[last]); + setProperty("http.nonProxyHosts", separated.toString()); + } else + setProperty("http.nonProxyHosts", null); + } + + /** + * Set property to given value. + *

+ * Specifying a null value will cause the property to be cleared + * + * @param name + * @param value + * @return previous value + */ + private static String setProperty(final String name, final String value) { + final PrivilegedAction action; + if (value != null) + action = new PrivilegedAction() { + + public String run() { + return System.setProperty(name, value); + } + }; + else + action = new PrivilegedAction() { + + public String run() { + return System.clearProperty(name); + } + }; + return AccessController.doPrivileged(action); + } + + private HttpURLConnection connection = null; + + private final URL url; + + private final String requestMethod; + + private RequestOutputStream output; + + private boolean multipart; + + private boolean form; + + private boolean ignoreCloseExceptions = true; + + private boolean uncompress = false; + + private int bufferSize = 8192; + + private long totalSize = -1; + + private long totalWritten = 0; + + private String httpProxyHost; + + private int httpProxyPort; + + private UploadProgress progress = UploadProgress.DEFAULT; + + /** + * Create HTTP connection wrapper + * + * @param url Remote resource URL. + * @param method HTTP request method (e.g., "GET", "POST"). + * @throws HttpRequestException + */ + public HttpRequest(final CharSequence url, final String method) throws HttpRequestException { + try { + this.url = new URL(url.toString()); + } catch (MalformedURLException e) { + throw new HttpRequestException(e); + } + this.requestMethod = method; + } + + /** + * Create HTTP connection wrapper + * + * @param url Remote resource URL. + * @param method HTTP request method (e.g., "GET", "POST"). + * @throws HttpRequestException + */ + public HttpRequest(final URL url, final String method) throws HttpRequestException { + this.url = url; + this.requestMethod = method; + } + + private Proxy createProxy() { + return new Proxy(HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort)); + } + + private HttpURLConnection createConnection() { + try { + final HttpURLConnection connection; + if (httpProxyHost != null) + connection = CONNECTION_FACTORY.create(url, createProxy()); + else + connection = CONNECTION_FACTORY.create(url); + connection.setRequestMethod(requestMethod); + return connection; + } catch (IOException e) { + throw new HttpRequestException(e); + } + } + + @Override + public String toString() { + return method() + ' ' + url(); + } + + /** + * Get underlying connection + * + * @return connection + */ + public HttpURLConnection getConnection() { + if (connection == null) + connection = createConnection(); + return connection; + } + + /** + * Set whether or not to ignore exceptions that occur from calling + * {@link Closeable#close()} + *

+ * The default value of this setting is true + * + * @param ignore + * @return this request + */ + public HttpRequest ignoreCloseExceptions(final boolean ignore) { + ignoreCloseExceptions = ignore; + return this; + } + + /** + * Get whether or not exceptions thrown by {@link Closeable#close()} are ignored + * + * @return true if ignoring, false if throwing + */ + public boolean ignoreCloseExceptions() { + return ignoreCloseExceptions; + } + + /** + * Get the status code of the response + * + * @return the response code + * @throws HttpRequestException + */ + public int code() throws HttpRequestException { + try { + closeOutput(); + return getConnection().getResponseCode(); + } catch (IOException e) { + throw new HttpRequestException(e); + } + } + + /** + * Set the value of the given {@link AtomicInteger} to the status code of the + * response + * + * @param output + * @return this request + * @throws HttpRequestException + */ + public HttpRequest code(final AtomicInteger output) throws HttpRequestException { + output.set(code()); + return this; + } + + /** + * Is the response code a 200 OK? + * + * @return true if 200, false otherwise + * @throws HttpRequestException + */ + public boolean ok() throws HttpRequestException { + return HTTP_OK == code(); + } + + /** + * Is the response code a 201 Created? + * + * @return true if 201, false otherwise + * @throws HttpRequestException + */ + public boolean created() throws HttpRequestException { + return HTTP_CREATED == code(); + } + + /** + * Is the response code a 204 No Content? + * + * @return true if 204, false otherwise + * @throws HttpRequestException + */ + public boolean noContent() throws HttpRequestException { + return HTTP_NO_CONTENT == code(); + } + + /** + * Is the response code a 500 Internal Server Error? + * + * @return true if 500, false otherwise + * @throws HttpRequestException + */ + public boolean serverError() throws HttpRequestException { + return HTTP_INTERNAL_ERROR == code(); + } + + /** + * Is the response code a 400 Bad Request? + * + * @return true if 400, false otherwise + * @throws HttpRequestException + */ + public boolean badRequest() throws HttpRequestException { + return HTTP_BAD_REQUEST == code(); + } + + /** + * Is the response code a 404 Not Found? + * + * @return true if 404, false otherwise + * @throws HttpRequestException + */ + public boolean notFound() throws HttpRequestException { + return HTTP_NOT_FOUND == code(); + } + + /** + * Is the response code a 304 Not Modified? + * + * @return true if 304, false otherwise + * @throws HttpRequestException + */ + public boolean notModified() throws HttpRequestException { + return HTTP_NOT_MODIFIED == code(); + } + + /** + * Get status message of the response + * + * @return message + * @throws HttpRequestException + */ + public String message() throws HttpRequestException { + try { + closeOutput(); + return getConnection().getResponseMessage(); + } catch (IOException e) { + throw new HttpRequestException(e); + } + } + + /** + * Disconnect the connection + * + * @return this request + */ + public HttpRequest disconnect() { + getConnection().disconnect(); + return this; + } + + /** + * Set chunked streaming mode to the given size + * + * @param size + * @return this request + */ + public HttpRequest chunk(final int size) { + getConnection().setChunkedStreamingMode(size); + return this; + } + + /** + * Set the size used when buffering and copying between streams + *

+ * This size is also used for send and receive buffers created for both char and + * byte arrays + *

+ * The default buffer size is 8,192 bytes + * + * @param size + * @return this request + */ + public HttpRequest bufferSize(final int size) { + if (size < 1) + throw new IllegalArgumentException("Size must be greater than zero"); + bufferSize = size; + return this; + } + + /** + * Get the configured buffer size + *

+ * The default buffer size is 8,192 bytes + * + * @return buffer size + */ + public int bufferSize() { + return bufferSize; + } + + /** + * Set whether or not the response body should be automatically uncompressed + * when read from. + *

+ * This will only affect requests that have the 'Content-Encoding' response + * header set to 'gzip'. + *

+ * This causes all receive methods to use a {@link GZIPInputStream} when + * applicable so that higher level streams and readers can read the data + * uncompressed. + *

+ * Setting this option does not cause any request headers to be set + * automatically so {@link #acceptGzipEncoding()} should be used in conjunction + * with this setting to tell the server to gzip the response. + * + * @param uncompress + * @return this request + */ + public HttpRequest uncompress(final boolean uncompress) { + this.uncompress = uncompress; + return this; + } + + /** + * Create byte array output stream + * + * @return stream + */ + protected ByteArrayOutputStream byteStream() { + final int size = contentLength(); + if (size > 0) + return new ByteArrayOutputStream(size); + else + return new ByteArrayOutputStream(); + } + + /** + * Get response as {@link String} in given character set + *

+ * This will fall back to using the UTF-8 character set if the given charset is + * null + * + * @param charset + * @return string + * @throws HttpRequestException + */ + public String body(final String charset) throws HttpRequestException { + final ByteArrayOutputStream output = byteStream(); + try { + copy(buffer(), output); + return output.toString(getValidCharset(charset)); + } catch (IOException e) { + throw new HttpRequestException(e); + } + } + + /** + * Get response as {@link String} using character set returned from + * {@link #charset()} + * + * @return string + * @throws HttpRequestException + */ + public String body() throws HttpRequestException { + return body(charset()); + } + + /** + * Get the response body as a {@link String} and set it as the value of the + * given reference. + * + * @param output + * @return this request + * @throws HttpRequestException + */ + public HttpRequest body(final AtomicReference output) throws HttpRequestException { + output.set(body()); + return this; + } + + /** + * Get the response body as a {@link String} and set it as the value of the + * given reference. + * + * @param output + * @param charset + * @return this request + * @throws HttpRequestException + */ + public HttpRequest body(final AtomicReference output, final String charset) throws HttpRequestException { + output.set(body(charset)); + return this; + } + + /** + * Is the response body empty? + * + * @return true if the Content-Length response header is 0, false otherwise + * @throws HttpRequestException + */ + public boolean isBodyEmpty() throws HttpRequestException { + return contentLength() == 0; + } + + /** + * Get response as byte array + * + * @return byte array + * @throws HttpRequestException + */ + public byte[] bytes() throws HttpRequestException { + final ByteArrayOutputStream output = byteStream(); + try { + copy(buffer(), output); + } catch (IOException e) { + throw new HttpRequestException(e); + } + return output.toByteArray(); + } + + /** + * Get response in a buffered stream + * + * @see #bufferSize(int) + * @return stream + * @throws HttpRequestException + */ + public BufferedInputStream buffer() throws HttpRequestException { + return new BufferedInputStream(stream(), bufferSize); + } + + /** + * Get stream to response body + * + * @return stream + * @throws HttpRequestException + */ + public InputStream stream() throws HttpRequestException { + InputStream stream; + if (code() < HTTP_BAD_REQUEST) + try { + stream = getConnection().getInputStream(); + } catch (IOException e) { + throw new HttpRequestException(e); + } + else { + stream = getConnection().getErrorStream(); + if (stream == null) + try { + stream = getConnection().getInputStream(); + } catch (IOException e) { + if (contentLength() > 0) + throw new HttpRequestException(e); + else + stream = new ByteArrayInputStream(new byte[0]); + } + } + + if (!uncompress || !ENCODING_GZIP.equals(contentEncoding())) + return stream; + else + try { + return new GZIPInputStream(stream); + } catch (IOException e) { + throw new HttpRequestException(e); + } + } + + /** + * Get reader to response body using given character set. + *

+ * This will fall back to using the UTF-8 character set if the given charset is + * null + * + * @param charset + * @return reader + * @throws HttpRequestException + */ + public InputStreamReader reader(final String charset) throws HttpRequestException { + try { + return new InputStreamReader(stream(), getValidCharset(charset)); + } catch (UnsupportedEncodingException e) { + throw new HttpRequestException(e); + } + } + + /** + * Get reader to response body using the character set returned from + * {@link #charset()} + * + * @return reader + * @throws HttpRequestException + */ + public InputStreamReader reader() throws HttpRequestException { + return reader(charset()); + } + + /** + * Get buffered reader to response body using the given character set r and the + * configured buffer size + * + * + * @see #bufferSize(int) + * @param charset + * @return reader + * @throws HttpRequestException + */ + public BufferedReader bufferedReader(final String charset) throws HttpRequestException { + return new BufferedReader(reader(charset), bufferSize); + } + + /** + * Get buffered reader to response body using the character set returned from + * {@link #charset()} and the configured buffer size + * + * @see #bufferSize(int) + * @return reader + * @throws HttpRequestException + */ + public BufferedReader bufferedReader() throws HttpRequestException { + return bufferedReader(charset()); + } + + /** + * Stream response body to file + * + * @param file + * @return this request + * @throws HttpRequestException + */ + public HttpRequest receive(final File file) throws HttpRequestException { + final OutputStream output; + try { + output = new BufferedOutputStream(new FileOutputStream(file), bufferSize); + } catch (FileNotFoundException e) { + throw new HttpRequestException(e); + } + return new CloseOperation(output, ignoreCloseExceptions) { + + @Override + protected HttpRequest run() throws HttpRequestException, IOException { + return receive(output); + } + }.call(); + } + + /** + * Stream response to given output stream + * + * @param output + * @return this request + * @throws HttpRequestException + */ + public HttpRequest receive(final OutputStream output) throws HttpRequestException { + try { + return copy(buffer(), output); + } catch (IOException e) { + throw new HttpRequestException(e); + } + } + + /** + * Stream response to given print stream + * + * @param output + * @return this request + * @throws HttpRequestException + */ + public HttpRequest receive(final PrintStream output) throws HttpRequestException { + return receive((OutputStream) output); + } + + /** + * Receive response into the given appendable + * + * @param appendable + * @return this request + * @throws HttpRequestException + */ + public HttpRequest receive(final Appendable appendable) throws HttpRequestException { + final BufferedReader reader = bufferedReader(); + return new CloseOperation(reader, ignoreCloseExceptions) { + + @Override + public HttpRequest run() throws IOException { + final CharBuffer buffer = CharBuffer.allocate(bufferSize); + int read; + while ((read = reader.read(buffer)) != -1) { + buffer.rewind(); + appendable.append(buffer, 0, read); + buffer.rewind(); + } + return HttpRequest.this; + } + }.call(); + } + + /** + * Receive response into the given writer + * + * @param writer + * @return this request + * @throws HttpRequestException + */ + public HttpRequest receive(final Writer writer) throws HttpRequestException { + final BufferedReader reader = bufferedReader(); + return new CloseOperation(reader, ignoreCloseExceptions) { + + @Override + public HttpRequest run() throws IOException { + return copy(reader, writer); + } + }.call(); + } + + /** + * Set read timeout on connection to given value + * + * @param timeout + * @return this request + */ + public HttpRequest readTimeout(final int timeout) { + getConnection().setReadTimeout(timeout); + return this; + } + + /** + * Set connect timeout on connection to given value + * + * @param timeout + * @return this request + */ + public HttpRequest connectTimeout(final int timeout) { + getConnection().setConnectTimeout(timeout); + return this; + } + + /** + * Set header name to given value + * + * @param name + * @param value + * @return this request + */ + public HttpRequest header(final String name, final String value) { + getConnection().setRequestProperty(name, value); + return this; + } + + /** + * Set header name to given value + * + * @param name + * @param value + * @return this request + */ + public HttpRequest header(final String name, final Number value) { + return header(name, value != null ? value.toString() : null); + } + + /** + * Set all headers found in given map where the keys are the header names and + * the values are the header values + * + * @param headers + * @return this request + */ + public HttpRequest headers(final Map headers) { + if (!headers.isEmpty()) + for (Entry header : headers.entrySet()) + header(header); + return this; + } + + /** + * Set header to have given entry's key as the name and value as the value + * + * @param header + * @return this request + */ + public HttpRequest header(final Entry header) { + return header(header.getKey(), header.getValue()); + } + + /** + * Get a response header + * + * @param name + * @return response header + * @throws HttpRequestException + */ + public String header(final String name) throws HttpRequestException { + closeOutputQuietly(); + return getConnection().getHeaderField(name); + } + + /** + * Get all the response headers + * + * @return map of response header names to their value(s) + * @throws HttpRequestException + */ + public Map> headers() throws HttpRequestException { + closeOutputQuietly(); + return getConnection().getHeaderFields(); + } + + /** + * Get a date header from the response falling back to returning -1 if the + * header is missing or parsing fails + * + * @param name + * @return date, -1 on failures + * @throws HttpRequestException + */ + public long dateHeader(final String name) throws HttpRequestException { + return dateHeader(name, -1L); + } + + /** + * Get a date header from the response falling back to returning the given + * default value if the header is missing or parsing fails + * + * @param name + * @param defaultValue + * @return date, default value on failures + * @throws HttpRequestException + */ + public long dateHeader(final String name, final long defaultValue) throws HttpRequestException { + closeOutputQuietly(); + return getConnection().getHeaderFieldDate(name, defaultValue); + } + + /** + * Get an integer header from the response falling back to returning -1 if the + * header is missing or parsing fails + * + * @param name + * @return header value as an integer, -1 when missing or parsing fails + * @throws HttpRequestException + */ + public int intHeader(final String name) throws HttpRequestException { + return intHeader(name, -1); + } + + /** + * Get an integer header value from the response falling back to the given + * default value if the header is missing or if parsing fails + * + * @param name + * @param defaultValue + * @return header value as an integer, default value when missing or parsing + * fails + * @throws HttpRequestException + */ + public int intHeader(final String name, final int defaultValue) throws HttpRequestException { + closeOutputQuietly(); + return getConnection().getHeaderFieldInt(name, defaultValue); + } + + /** + * Get all values of the given header from the response + * + * @param name + * @return non-null but possibly empty array of {@link String} header values + */ + public String[] headers(final String name) { + final Map> headers = headers(); + if (headers == null || headers.isEmpty()) + return EMPTY_STRINGS; + + final List values = headers.get(name); + if (values != null && !values.isEmpty()) + return values.toArray(new String[values.size()]); + else + return EMPTY_STRINGS; + } + + /** + * Get parameter with given name from header value in response + * + * @param headerName + * @param paramName + * @return parameter value or null if missing + */ + public String parameter(final String headerName, final String paramName) { + return getParam(header(headerName), paramName); + } + + /** + * Get all parameters from header value in response + *

+ * This will be all key=value pairs after the first ';' that are separated by a + * ';' + * + * @param headerName + * @return non-null but possibly empty map of parameter headers + */ + public Map parameters(final String headerName) { + return getParams(header(headerName)); + } + + /** + * Get parameter values from header value + * + * @param header + * @return parameter value or null if none + */ + protected Map getParams(final String header) { + if (header == null || header.length() == 0) + return Collections.emptyMap(); + + final int headerLength = header.length(); + int start = header.indexOf(';') + 1; + if (start == 0 || start == headerLength) + return Collections.emptyMap(); + + int end = header.indexOf(';', start); + if (end == -1) + end = headerLength; + + Map params = new LinkedHashMap(); + while (start < end) { + int nameEnd = header.indexOf('=', start); + if (nameEnd != -1 && nameEnd < end) { + String name = header.substring(start, nameEnd).trim(); + if (name.length() > 0) { + String value = header.substring(nameEnd + 1, end).trim(); + int length = value.length(); + if (length != 0) + if (length > 2 && '"' == value.charAt(0) && '"' == value.charAt(length - 1)) + params.put(name, value.substring(1, length - 1)); + else + params.put(name, value); + } + } + + start = end + 1; + end = header.indexOf(';', start); + if (end == -1) + end = headerLength; + } + + return params; + } + + /** + * Get parameter value from header value + * + * @param value + * @param paramName + * @return parameter value or null if none + */ + protected String getParam(final String value, final String paramName) { + if (value == null || value.length() == 0) + return null; + + final int length = value.length(); + int start = value.indexOf(';') + 1; + if (start == 0 || start == length) + return null; + + int end = value.indexOf(';', start); + if (end == -1) + end = length; + + while (start < end) { + int nameEnd = value.indexOf('=', start); + if (nameEnd != -1 && nameEnd < end && paramName.equals(value.substring(start, nameEnd).trim())) { + String paramValue = value.substring(nameEnd + 1, end).trim(); + int valueLength = paramValue.length(); + if (valueLength != 0) + if (valueLength > 2 && '"' == paramValue.charAt(0) && '"' == paramValue.charAt(valueLength - 1)) + return paramValue.substring(1, valueLength - 1); + else + return paramValue; + } + + start = end + 1; + end = value.indexOf(';', start); + if (end == -1) + end = length; + } + + return null; + } + + /** + * Get 'charset' parameter from 'Content-Type' response header + * + * @return charset or null if none + */ + public String charset() { + return parameter(HEADER_CONTENT_TYPE, PARAM_CHARSET); + } + + /** + * Set the 'User-Agent' header to given value + * + * @param userAgent + * @return this request + */ + public HttpRequest userAgent(final String userAgent) { + return header(HEADER_USER_AGENT, userAgent); + } + + /** + * Set the 'Referer' header to given value + * + * @param referer + * @return this request + */ + public HttpRequest referer(final String referer) { + return header(HEADER_REFERER, referer); + } + + /** + * Set value of {@link HttpURLConnection#setUseCaches(boolean)} + * + * @param useCaches + * @return this request + */ + public HttpRequest useCaches(final boolean useCaches) { + getConnection().setUseCaches(useCaches); + return this; + } + + /** + * Set the 'Accept-Encoding' header to given value + * + * @param acceptEncoding + * @return this request + */ + public HttpRequest acceptEncoding(final String acceptEncoding) { + return header(HEADER_ACCEPT_ENCODING, acceptEncoding); + } + + /** + * Set the 'Accept-Encoding' header to 'gzip' + * + * @see #uncompress(boolean) + * @return this request + */ + public HttpRequest acceptGzipEncoding() { + return acceptEncoding(ENCODING_GZIP); + } + + /** + * Set the 'Accept-Charset' header to given value + * + * @param acceptCharset + * @return this request + */ + public HttpRequest acceptCharset(final String acceptCharset) { + return header(HEADER_ACCEPT_CHARSET, acceptCharset); + } + + /** + * Get the 'Content-Encoding' header from the response + * + * @return this request + */ + public String contentEncoding() { + return header(HEADER_CONTENT_ENCODING); + } + + /** + * Get the 'Server' header from the response + * + * @return server + */ + public String server() { + return header(HEADER_SERVER); + } + + /** + * Get the 'Date' header from the response + * + * @return date value, -1 on failures + */ + public long date() { + return dateHeader(HEADER_DATE); + } + + /** + * Get the 'Cache-Control' header from the response + * + * @return cache control + */ + public String cacheControl() { + return header(HEADER_CACHE_CONTROL); + } + + /** + * Get the 'ETag' header from the response + * + * @return entity tag + */ + public String eTag() { + return header(HEADER_ETAG); + } + + /** + * Get the 'Expires' header from the response + * + * @return expires value, -1 on failures + */ + public long expires() { + return dateHeader(HEADER_EXPIRES); + } + + /** + * Get the 'Last-Modified' header from the response + * + * @return last modified value, -1 on failures + */ + public long lastModified() { + return dateHeader(HEADER_LAST_MODIFIED); + } + + /** + * Get the 'Location' header from the response + * + * @return location + */ + public String location() { + return header(HEADER_LOCATION); + } + + /** + * Set the 'Authorization' header to given value + * + * @param authorization + * @return this request + */ + public HttpRequest authorization(final String authorization) { + return header(HEADER_AUTHORIZATION, authorization); + } + + /** + * Set the 'Proxy-Authorization' header to given value + * + * @param proxyAuthorization + * @return this request + */ + public HttpRequest proxyAuthorization(final String proxyAuthorization) { + return header(HEADER_PROXY_AUTHORIZATION, proxyAuthorization); + } + + /** + * Set the 'Authorization' header to given values in Basic authentication format + * + * @param name + * @param password + * @return this request + */ + public HttpRequest basic(final String name, final String password) { + return authorization("Basic " + Base64.encode(name + ':' + password)); + } + + /** + * Set the 'Proxy-Authorization' header to given values in Basic authentication + * format + * + * @param name + * @param password + * @return this request + */ + public HttpRequest proxyBasic(final String name, final String password) { + return proxyAuthorization("Basic " + Base64.encode(name + ':' + password)); + } + + /** + * Set the 'If-Modified-Since' request header to the given value + * + * @param ifModifiedSince + * @return this request + */ + public HttpRequest ifModifiedSince(final long ifModifiedSince) { + getConnection().setIfModifiedSince(ifModifiedSince); + return this; + } + + /** + * Set the 'If-None-Match' request header to the given value + * + * @param ifNoneMatch + * @return this request + */ + public HttpRequest ifNoneMatch(final String ifNoneMatch) { + return header(HEADER_IF_NONE_MATCH, ifNoneMatch); + } + + /** + * Set the 'Content-Type' request header to the given value + * + * @param contentType + * @return this request + */ + public HttpRequest contentType(final String contentType) { + return contentType(contentType, null); + } + + /** + * Set the 'Content-Type' request header to the given value and charset + * + * @param contentType + * @param charset + * @return this request + */ + public HttpRequest contentType(final String contentType, final String charset) { + if (charset != null && charset.length() > 0) { + final String separator = "; " + PARAM_CHARSET + '='; + return header(HEADER_CONTENT_TYPE, contentType + separator + charset); + } else + return header(HEADER_CONTENT_TYPE, contentType); + } + + /** + * Get the 'Content-Type' header from the response + * + * @return response header value + */ + public String contentType() { + return header(HEADER_CONTENT_TYPE); + } + + /** + * Get the 'Content-Length' header from the response + * + * @return response header value + */ + public int contentLength() { + return intHeader(HEADER_CONTENT_LENGTH); + } + + /** + * Set the 'Content-Length' request header to the given value + * + * @param contentLength + * @return this request + */ + public HttpRequest contentLength(final String contentLength) { + return contentLength(Integer.parseInt(contentLength)); + } + + /** + * Set the 'Content-Length' request header to the given value + * + * @param contentLength + * @return this request + */ + public HttpRequest contentLength(final int contentLength) { + getConnection().setFixedLengthStreamingMode(contentLength); + return this; + } + + /** + * Set the 'Accept' header to given value + * + * @param accept + * @return this request + */ + public HttpRequest accept(final String accept) { + return header(HEADER_ACCEPT, accept); + } + + /** + * Set the 'Accept' header to 'application/json' + * + * @return this request + */ + public HttpRequest acceptJson() { + return accept(CONTENT_TYPE_JSON); + } + + /** + * Copy from input stream to output stream + * + * @param input + * @param output + * @return this request + * @throws IOException + */ + protected HttpRequest copy(final InputStream input, final OutputStream output) throws IOException { + return new CloseOperation(input, ignoreCloseExceptions) { + + @Override + public HttpRequest run() throws IOException { + final byte[] buffer = new byte[bufferSize]; + int read; + while ((read = input.read(buffer)) != -1) { + output.write(buffer, 0, read); + totalWritten += read; + progress.onUpload(totalWritten, totalSize); + } + return HttpRequest.this; + } + }.call(); + } + + /** + * Copy from reader to writer + * + * @param input + * @param output + * @return this request + * @throws IOException + */ + protected HttpRequest copy(final Reader input, final Writer output) throws IOException { + return new CloseOperation(input, ignoreCloseExceptions) { + + @Override + public HttpRequest run() throws IOException { + final char[] buffer = new char[bufferSize]; + int read; + while ((read = input.read(buffer)) != -1) { + output.write(buffer, 0, read); + totalWritten += read; + progress.onUpload(totalWritten, -1); + } + return HttpRequest.this; + } + }.call(); + } + + /** + * Set the UploadProgress callback for this request + * + * @param callback + * @return this request + */ + public HttpRequest progress(final UploadProgress callback) { + if (callback == null) + progress = UploadProgress.DEFAULT; + else + progress = callback; + return this; + } + + private HttpRequest incrementTotalSize(final long size) { + if (totalSize == -1) + totalSize = 0; + totalSize += size; + return this; + } + + /** + * Close output stream + * + * @return this request + * @throws HttpRequestException + * @throws IOException + */ + protected HttpRequest closeOutput() throws IOException { + progress(null); + if (output == null) + return this; + if (multipart) + output.write(CRLF + "--" + BOUNDARY + "--" + CRLF); + if (ignoreCloseExceptions) + try { + output.close(); + } catch (IOException ignored) { + // Ignored + } + else + output.close(); + output = null; + return this; + } + + /** + * Call {@link #closeOutput()} and re-throw a caught {@link IOException}s as an + * {@link HttpRequestException} + * + * @return this request + * @throws HttpRequestException + */ + protected HttpRequest closeOutputQuietly() throws HttpRequestException { + try { + return closeOutput(); + } catch (IOException e) { + throw new HttpRequestException(e); + } + } + + /** + * Open output stream + * + * @return this request + * @throws IOException + */ + protected HttpRequest openOutput() throws IOException { + if (output != null) + return this; + getConnection().setDoOutput(true); + final String charset = getParam(getConnection().getRequestProperty(HEADER_CONTENT_TYPE), PARAM_CHARSET); + output = new RequestOutputStream(getConnection().getOutputStream(), charset, bufferSize); + return this; + } + + /** + * Start part of a multipart + * + * @return this request + * @throws IOException + */ + protected HttpRequest startPart() throws IOException { + if (!multipart) { + multipart = true; + contentType(CONTENT_TYPE_MULTIPART).openOutput(); + output.write("--" + BOUNDARY + CRLF); + } else + output.write(CRLF + "--" + BOUNDARY + CRLF); + return this; + } + + /** + * Write part header + * + * @param name + * @param filename + * @return this request + * @throws IOException + */ + protected HttpRequest writePartHeader(final String name, final String filename) throws IOException { + return writePartHeader(name, filename, null); + } + + /** + * Write part header + * + * @param name + * @param filename + * @param contentType + * @return this request + * @throws IOException + */ + protected HttpRequest writePartHeader(final String name, final String filename, final String contentType) + throws IOException { + final StringBuilder partBuffer = new StringBuilder(); + partBuffer.append("form-data; name=\"").append(name); + if (filename != null) + partBuffer.append("\"; filename=\"").append(filename); + partBuffer.append('"'); + partHeader("Content-Disposition", partBuffer.toString()); + if (contentType != null) + partHeader(HEADER_CONTENT_TYPE, contentType); + return send(CRLF); + } + + /** + * Write part of a multipart request to the request body + * + * @param name + * @param part + * @return this request + */ + public HttpRequest part(final String name, final String part) { + return part(name, null, part); + } + + /** + * Write part of a multipart request to the request body + * + * @param name + * @param filename + * @param part + * @return this request + * @throws HttpRequestException + */ + public HttpRequest part(final String name, final String filename, final String part) throws HttpRequestException { + return part(name, filename, null, part); + } + + /** + * Write part of a multipart request to the request body + * + * @param name + * @param filename + * @param contentType value of the Content-Type part header + * @param part + * @return this request + * @throws HttpRequestException + */ + public HttpRequest part(final String name, final String filename, final String contentType, final String part) + throws HttpRequestException { + try { + startPart(); + writePartHeader(name, filename, contentType); + output.write(part); + } catch (IOException e) { + throw new HttpRequestException(e); + } + return this; + } + + /** + * Write part of a multipart request to the request body + * + * @param name + * @param part + * @return this request + * @throws HttpRequestException + */ + public HttpRequest part(final String name, final Number part) throws HttpRequestException { + return part(name, null, part); + } + + /** + * Write part of a multipart request to the request body + * + * @param name + * @param filename + * @param part + * @return this request + * @throws HttpRequestException + */ + public HttpRequest part(final String name, final String filename, final Number part) throws HttpRequestException { + return part(name, filename, part != null ? part.toString() : null); + } + + /** + * Write part of a multipart request to the request body + * + * @param name + * @param part + * @return this request + * @throws HttpRequestException + */ + public HttpRequest part(final String name, final File part) throws HttpRequestException { + return part(name, null, part); + } + + /** + * Write part of a multipart request to the request body + * + * @param name + * @param filename + * @param part + * @return this request + * @throws HttpRequestException + */ + public HttpRequest part(final String name, final String filename, final File part) throws HttpRequestException { + return part(name, filename, null, part); + } + + /** + * Write part of a multipart request to the request body + * + * @param name + * @param filename + * @param contentType value of the Content-Type part header + * @param part + * @return this request + * @throws HttpRequestException + */ + public HttpRequest part(final String name, final String filename, final String contentType, final File part) + throws HttpRequestException { + final InputStream stream; + try { + stream = new BufferedInputStream(new FileInputStream(part)); + incrementTotalSize(part.length()); + } catch (IOException e) { + throw new HttpRequestException(e); + } + return part(name, filename, contentType, stream); + } + + /** + * Write part of a multipart request to the request body + * + * @param name + * @param part + * @return this request + * @throws HttpRequestException + */ + public HttpRequest part(final String name, final InputStream part) throws HttpRequestException { + return part(name, null, null, part); + } + + /** + * Write part of a multipart request to the request body + * + * @param name + * @param filename + * @param contentType value of the Content-Type part header + * @param part + * @return this request + * @throws HttpRequestException + */ + public HttpRequest part(final String name, final String filename, final String contentType, final InputStream part) + throws HttpRequestException { + try { + startPart(); + writePartHeader(name, filename, contentType); + copy(part, output); + } catch (IOException e) { + throw new HttpRequestException(e); + } + return this; + } + + /** + * Write a multipart header to the response body + * + * @param name + * @param value + * @return this request + * @throws HttpRequestException + */ + public HttpRequest partHeader(final String name, final String value) throws HttpRequestException { + return send(name).send(": ").send(value).send(CRLF); + } + + /** + * Write contents of file to request body + * + * @param input + * @return this request + * @throws HttpRequestException + */ + public HttpRequest send(final File input) throws HttpRequestException { + final InputStream stream; + try { + stream = new BufferedInputStream(new FileInputStream(input)); + incrementTotalSize(input.length()); + } catch (FileNotFoundException e) { + throw new HttpRequestException(e); + } + return send(stream); + } + + /** + * Write byte array to request body + * + * @param input + * @return this request + * @throws HttpRequestException + */ + public HttpRequest send(final byte[] input) throws HttpRequestException { + if (input != null) + incrementTotalSize(input.length); + return send(new ByteArrayInputStream(input)); + } + + /** + * Write stream to request body + *

+ * The given stream will be closed once sending completes + * + * @param input + * @return this request + * @throws HttpRequestException + */ + public HttpRequest send(final InputStream input) throws HttpRequestException { + try { + openOutput(); + copy(input, output); + } catch (IOException e) { + throw new HttpRequestException(e); + } + return this; + } + + /** + * Write reader to request body + *

+ * The given reader will be closed once sending completes + * + * @param input + * @return this request + * @throws HttpRequestException + */ + public HttpRequest send(final Reader input) throws HttpRequestException { + try { + openOutput(); + } catch (IOException e) { + throw new HttpRequestException(e); + } + final Writer writer = new OutputStreamWriter(output, output.encoder.charset()); + return new FlushOperation(writer) { + + @Override + protected HttpRequest run() throws IOException { + return copy(input, writer); + } + }.call(); + } + + /** + * Write char sequence to request body + *

+ * The charset configured via {@link #contentType(String)} will be used and + * UTF-8 will be used if it is unset. + * + * @param value + * @return this request + * @throws HttpRequestException + */ + public HttpRequest send(final CharSequence value) throws HttpRequestException { + try { + openOutput(); + output.write(value.toString()); + } catch (IOException e) { + throw new HttpRequestException(e); + } + return this; + } + + /** + * Create writer to request output stream + * + * @return writer + * @throws HttpRequestException + */ + public OutputStreamWriter writer() throws HttpRequestException { + try { + openOutput(); + return new OutputStreamWriter(output, output.encoder.charset()); + } catch (IOException e) { + throw new HttpRequestException(e); + } + } + + /** + * Write the values in the map as form data to the request body + *

+ * The pairs specified will be URL-encoded in UTF-8 and sent with the + * 'application/x-www-form-urlencoded' content-type + * + * @param values + * @return this request + * @throws HttpRequestException + */ + public HttpRequest form(final Map values) throws HttpRequestException { + return form(values, CHARSET_UTF8); + } + + /** + * Write the key and value in the entry as form data to the request body + *

+ * The pair specified will be URL-encoded in UTF-8 and sent with the + * 'application/x-www-form-urlencoded' content-type + * + * @param entry + * @return this request + * @throws HttpRequestException + */ + public HttpRequest form(final Entry entry) throws HttpRequestException { + return form(entry, CHARSET_UTF8); + } + + /** + * Write the key and value in the entry as form data to the request body + *

+ * The pair specified will be URL-encoded and sent with the + * 'application/x-www-form-urlencoded' content-type + * + * @param entry + * @param charset + * @return this request + * @throws HttpRequestException + */ + public HttpRequest form(final Entry entry, final String charset) throws HttpRequestException { + return form(entry.getKey(), entry.getValue(), charset); + } + + /** + * Write the name/value pair as form data to the request body + *

+ * The pair specified will be URL-encoded in UTF-8 and sent with the + * 'application/x-www-form-urlencoded' content-type + * + * @param name + * @param value + * @return this request + * @throws HttpRequestException + */ + public HttpRequest form(final Object name, final Object value) throws HttpRequestException { + return form(name, value, CHARSET_UTF8); + } + + /** + * Write the name/value pair as form data to the request body + *

+ * The values specified will be URL-encoded and sent with the + * 'application/x-www-form-urlencoded' content-type + * + * @param name + * @param value + * @param charset + * @return this request + * @throws HttpRequestException + */ + public HttpRequest form(final Object name, final Object value, String charset) throws HttpRequestException { + final boolean first = !form; + if (first) { + contentType(CONTENT_TYPE_FORM, charset); + form = true; + } + charset = getValidCharset(charset); + try { + openOutput(); + if (!first) + output.write('&'); + output.write(URLEncoder.encode(name.toString(), charset)); + output.write('='); + if (value != null) + output.write(URLEncoder.encode(value.toString(), charset)); + } catch (IOException e) { + throw new HttpRequestException(e); + } + return this; + } + + /** + * Write the values in the map as encoded form data to the request body + * + * @param values + * @param charset + * @return this request + * @throws HttpRequestException + */ + public HttpRequest form(final Map values, final String charset) throws HttpRequestException { + if (!values.isEmpty()) + for (Entry entry : values.entrySet()) + form(entry, charset); + return this; + } + + public HttpRequest setSSLSocketFactory(SSLSocketFactory socketFactory) throws HttpRequestException { + final HttpURLConnection connection = getConnection(); + if (connection instanceof HttpsURLConnection) + ((HttpsURLConnection) connection).setSSLSocketFactory(socketFactory); + return this; + } + + public HttpRequest setHostnameVerifier(HostnameVerifier verifier) { + final HttpURLConnection connection = getConnection(); + if (connection instanceof HttpsURLConnection) + ((HttpsURLConnection) connection).setHostnameVerifier(verifier); + return this; + } + + /** + * Get the {@link URL} of this request's connection + * + * @return request URL + */ + public URL url() { + return getConnection().getURL(); + } + + /** + * Get the HTTP method of this request + * + * @return method + */ + public String method() { + return getConnection().getRequestMethod(); + } + + /** + * Configure an HTTP proxy on this connection. Use + * {{@link #proxyBasic(String, String)} if this proxy requires basic + * authentication. + * + * @param proxyHost + * @param proxyPort + * @return this request + */ + public HttpRequest useProxy(final String proxyHost, final int proxyPort) { + if (connection != null) + throw new IllegalStateException( + "The connection has already been created. This method must be called before reading or writing to the request."); + + this.httpProxyHost = proxyHost; + this.httpProxyPort = proxyPort; + return this; + } + + /** + * Set whether or not the underlying connection should follow redirects in the + * response. + * + * @param followRedirects - true fo follow redirects, false to not. + * @return this request + */ + public HttpRequest followRedirects(final boolean followRedirects) { + getConnection().setInstanceFollowRedirects(followRedirects); + return this; + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/JsonUtils.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/JsonUtils.java new file mode 100644 index 0000000000..72f1b48018 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/JsonUtils.java @@ -0,0 +1,58 @@ +package com.silkimen.http; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class JsonUtils { + public static HashMap getStringMap(JSONObject object) throws JSONException { + HashMap map = new HashMap(); + + if (object == null) { + return map; + } + + Iterator i = object.keys(); + + while (i.hasNext()) { + String key = (String) i.next(); + map.put(key, object.getString(key)); + } + return map; + } + + public static HashMap getObjectMap(JSONObject object) throws JSONException { + HashMap map = new HashMap(); + + if (object == null) { + return map; + } + + Iterator i = object.keys(); + + while (i.hasNext()) { + String key = (String) i.next(); + Object value = object.get(key); + + if (value instanceof JSONArray) { + map.put(key, getObjectList((JSONArray) value)); + } else { + map.put(key, object.get(key)); + } + } + return map; + } + + public static ArrayList getObjectList(JSONArray array) throws JSONException { + ArrayList list = new ArrayList(); + + for (int i = 0; i < array.length(); i++) { + list.add(array.get(i)); + } + return list; + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/KeyChainKeyManager.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/KeyChainKeyManager.java new file mode 100644 index 0000000000..ecdaa38c7f --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/KeyChainKeyManager.java @@ -0,0 +1,57 @@ +package com.silkimen.http; + +import android.content.Context; +import android.security.KeyChain; + +import java.net.Socket; +import java.security.Principal; +import java.security.PrivateKey; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.X509ExtendedKeyManager; + +public class KeyChainKeyManager extends X509ExtendedKeyManager { + private final String alias; + private final X509Certificate[] chain; + private final PrivateKey key; + + public KeyChainKeyManager(String alias, PrivateKey key, X509Certificate[] chain) { + this.alias = alias; + this.key = key; + this.chain = chain; + } + + @Override + public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) { + return this.alias; + } + + @Override + public X509Certificate[] getCertificateChain(String alias) { + return chain; + } + + @Override + public PrivateKey getPrivateKey(String alias) { + return key; + } + + @Override + public final String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { + // not a client SSLSocket callback + throw new UnsupportedOperationException(); + } + + @Override + public final String[] getClientAliases(String keyType, Principal[] issuers) { + // not a client SSLSocket callback + throw new UnsupportedOperationException(); + } + + @Override + public final String[] getServerAliases(String keyType, Principal[] issuers) { + // not a client SSLSocket callback + throw new UnsupportedOperationException(); + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSConfiguration.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSConfiguration.java new file mode 100644 index 0000000000..ed6f0d01b8 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSConfiguration.java @@ -0,0 +1,64 @@ +package com.silkimen.http; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; + +import com.silkimen.http.TLSSocketFactory; + +public class TLSConfiguration { + private TrustManager[] trustManagers = null; + private KeyManager[] keyManagers = null; + private HostnameVerifier hostnameVerifier = null; + private String[] blacklistedProtocols = {}; + + private SSLSocketFactory socketFactory; + + public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { + this.hostnameVerifier = hostnameVerifier; + } + + public void setKeyManagers(KeyManager[] keyManagers) { + this.keyManagers = keyManagers; + this.socketFactory = null; + } + + public void setTrustManagers(TrustManager[] trustManagers) { + this.trustManagers = trustManagers; + this.socketFactory = null; + } + + public void setBlacklistedProtocols(String[] protocols) { + this.blacklistedProtocols = protocols; + this.socketFactory = null; + } + + public HostnameVerifier getHostnameVerifier() { + return this.hostnameVerifier; + } + + public SSLSocketFactory getTLSSocketFactory() throws IOException { + if (this.socketFactory != null) { + return this.socketFactory; + } + + try { + SSLContext context = SSLContext.getInstance("TLS"); + + context.init(this.keyManagers, this.trustManagers, new SecureRandom()); + this.socketFactory = new TLSSocketFactory(context, this.blacklistedProtocols); + + return this.socketFactory; + } catch (GeneralSecurityException e) { + IOException ioException = new IOException("Security exception occured while configuring TLS context"); + ioException.initCause(e); + throw ioException; + } + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSSocketFactory.java b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSSocketFactory.java new file mode 100644 index 0000000000..3e4682f3b7 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSSocketFactory.java @@ -0,0 +1,84 @@ +package com.silkimen.http; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.net.UnknownHostException; + +import java.util.ArrayList; +import java.util.List; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +public class TLSSocketFactory extends SSLSocketFactory { + + private SSLSocketFactory delegate; + private List blacklistedProtocols; + + public TLSSocketFactory(SSLContext context, String[] blacklistedProtocols) { + this.delegate = context.getSocketFactory(); + this.blacklistedProtocols = new ArrayList(); + + for (int i = 0; i < blacklistedProtocols.length; ++i) { + this.blacklistedProtocols.add(blacklistedProtocols[i].trim()); + } + } + + @Override + public String[] getDefaultCipherSuites() { + return delegate.getDefaultCipherSuites(); + } + + @Override + public String[] getSupportedCipherSuites() { + return delegate.getSupportedCipherSuites(); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { + return enableTLSOnSocket(delegate.createSocket(socket, host, port, autoClose)); + } + + @Override + public Socket createSocket(String host, int port) throws IOException, UnknownHostException { + return enableTLSOnSocket(delegate.createSocket(host, port)); + } + + @Override + public Socket createSocket(String host, int port, InetAddress localHost, int localPort) + throws IOException, UnknownHostException { + return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort)); + } + + @Override + public Socket createSocket(InetAddress host, int port) throws IOException { + return enableTLSOnSocket(delegate.createSocket(host, port)); + } + + @Override + public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) + throws IOException { + return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort)); + } + + private Socket enableTLSOnSocket(Socket socket) { + if (socket == null || !(socket instanceof SSLSocket)) { + return socket; + } + + String[] supported = ((SSLSocket) socket).getSupportedProtocols(); + List filtered = new ArrayList(); + + for (int i = 0; i < supported.length; ++i) { + if (!this.blacklistedProtocols.contains(supported[i])) { + filtered.add(supported[i]); + } + } + + ((SSLSocket) socket).setEnabledProtocols(filtered.toArray(new String[0])); + + return socket; + } +} diff --git a/src/plugins/cordova-plugin-advanced-http/www/advanced-http.js b/src/plugins/cordova-plugin-advanced-http/www/advanced-http.js new file mode 100644 index 0000000000..bd1237ad0b --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/advanced-http.js @@ -0,0 +1,25 @@ +/* + * A native HTTP Plugin for Cordova / PhoneGap. + */ + +var pluginId = module.id.slice(0, module.id.lastIndexOf('.')); + +var exec = require('cordova/exec'); +var base64 = require('cordova/base64'); +var messages = require(pluginId + '.messages'); +var errorCodes = require(pluginId + '.error-codes'); +var globalConfigs = require(pluginId + '.global-configs'); +var jsUtil = require(pluginId + '.js-util'); +var ToughCookie = require(pluginId + '.tough-cookie'); +var lodash = require(pluginId + '.lodash'); +var WebStorageCookieStore = require(pluginId + '.local-storage-store')(ToughCookie, lodash); +var cookieHandler = require(pluginId + '.cookie-handler')(window.localStorage, ToughCookie, WebStorageCookieStore); +var dependencyValidator = require(pluginId + '.dependency-validator')(window, window.console, messages); +var ponyfills = require(pluginId + '.ponyfills')(window); +var helpers = require(pluginId + '.helpers')(window, jsUtil, cookieHandler, messages, base64, errorCodes, dependencyValidator, ponyfills); +var urlUtil = require(pluginId + '.url-util')(jsUtil); +var publicInterface = require(pluginId + '.public-interface')(exec, cookieHandler, urlUtil, helpers, globalConfigs, errorCodes, ponyfills); + +dependencyValidator.logWarnings(); + +module.exports = publicInterface; diff --git a/src/plugins/cordova-plugin-advanced-http/www/cookie-handler.js b/src/plugins/cordova-plugin-advanced-http/www/cookie-handler.js new file mode 100644 index 0000000000..f8dd24c54a --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/cookie-handler.js @@ -0,0 +1,70 @@ +module.exports = function init(storage, ToughCookie, WebStorageCookieStore) { + var storeKey = '__advancedHttpCookieStore__'; + + var store = new WebStorageCookieStore(storage, storeKey); + var cookieJar = new ToughCookie.CookieJar(store); + + return { + setCookieFromString: setCookieFromString, + setCookie: setCookie, + getCookieString: getCookieString, + clearCookies: clearCookies, + removeCookies: removeCookies + }; + + function splitCookieString(cookieStr) { + var cookieParts = cookieStr.split(','); + var splitCookies = []; + var processedCookie = null; + + for (var i = 0; i < cookieParts.length; ++i) { + if (cookieParts[i].substr(-11, 8).toLowerCase() === 'expires=') { + processedCookie = cookieParts[i] + ',' + cookieParts[i + 1]; + i++; + } else { + processedCookie = cookieParts[i]; + } + + processedCookie = processedCookie.trim(); + splitCookies.push(processedCookie); + } + + return splitCookies; + } + + function setCookieFromString(url, cookieStr) { + if (!cookieStr) return; + + var cookies = splitCookieString(cookieStr); + + for (var i = 0; i < cookies.length; ++i) { + cookieJar.setCookieSync(cookies[i], url, { ignoreError: true }); + } + } + + function setCookie(url, cookie, options) { + options = options || {}; + options.ignoreError = false; + cookieJar.setCookieSync(cookie, url, options); + } + + function getCookieString(url) { + return cookieJar.getCookieStringSync(url); + } + + function clearCookies() { + window.localStorage.removeItem(storeKey); + } + + function removeCookies(url, cb) { + cookieJar.getCookies(url, function (error, cookies) { + if (!cookies || cookies.length === 0) { + return cb(null, []); + } + + var domain = cookies[0].domain; + + cookieJar.store.removeCookies(domain, null, cb); + }); + } +}; diff --git a/src/plugins/cordova-plugin-advanced-http/www/dependency-validator.js b/src/plugins/cordova-plugin-advanced-http/www/dependency-validator.js new file mode 100644 index 0000000000..99510345a1 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/dependency-validator.js @@ -0,0 +1,43 @@ +module.exports = function init(global, console, messages) { + var interface = { + checkBlobApi: checkBlobApi, + checkFileReaderApi: checkFileReaderApi, + checkFormDataInstance: checkFormDataInstance, + checkTextEncoderApi: checkTextEncoderApi, + logWarnings: logWarnings, + }; + + return interface; + + function logWarnings() { + if (!global.FormData) { + console.warn(messages.MISSING_FORMDATA_API); + } else if (!global.FormData.prototype || !global.FormData.prototype.entries) { + console.warn(messages.MISSING_FORMDATA_ENTRIES_API); + } + } + + function checkBlobApi() { + if (!global.Blob || !global.Blob.prototype) { + throw new Error(messages.MISSING_BLOB_API); + } + } + + function checkFileReaderApi() { + if (!global.FileReader || !global.FileReader.prototype) { + throw new Error(messages.MISSING_FILE_READER_API); + } + } + + function checkFormDataInstance(instance) { + if (!instance || !instance.entries) { + throw new Error(messages.MISSING_FORMDATA_ENTRIES_API); + } + } + + function checkTextEncoderApi() { + if (!global.TextEncoder || !global.TextEncoder.prototype) { + throw new Error(messages.MISSING_TEXT_ENCODER_API); + } + } +}; diff --git a/src/plugins/cordova-plugin-advanced-http/www/error-codes.js b/src/plugins/cordova-plugin-advanced-http/www/error-codes.js new file mode 100644 index 0000000000..15c13c0f4b --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/error-codes.js @@ -0,0 +1,10 @@ +module.exports = { + GENERIC: -1, + SSL_EXCEPTION: -2, + SERVER_NOT_FOUND: -3, + TIMEOUT: -4, + UNSUPPORTED_URL: -5, + NOT_CONNECTED: -6, + POST_PROCESSING_FAILED: -7, + ABORTED: -8, +}; diff --git a/src/plugins/cordova-plugin-advanced-http/www/global-configs.js b/src/plugins/cordova-plugin-advanced-http/www/global-configs.js new file mode 100644 index 0000000000..7f43baa837 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/global-configs.js @@ -0,0 +1,10 @@ +var globalConfigs = { + headers: {}, + serializer: 'urlencoded', + followRedirect: true, + timeout: 60.0, + connectTimeout: 60.0, + readTimeout: 60.0 +}; + +module.exports = globalConfigs; diff --git a/src/plugins/cordova-plugin-advanced-http/www/helpers.js b/src/plugins/cordova-plugin-advanced-http/www/helpers.js new file mode 100644 index 0000000000..ed070fe622 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/helpers.js @@ -0,0 +1,516 @@ +module.exports = function init(global, jsUtil, cookieHandler, messages, base64, errorCodes, dependencyValidator, ponyfills) { + var validSerializers = ['urlencoded', 'json', 'utf8', 'raw', 'multipart']; + var validCertModes = ['default', 'nocheck', 'pinned', 'legacy']; + var validClientAuthModes = ['none', 'systemstore', 'buffer']; + var validHttpMethods = ['get', 'put', 'post', 'patch', 'head', 'delete', 'options', 'upload', 'download']; + var validResponseTypes = ['text', 'json', 'arraybuffer', 'blob']; + + var nextRequestId = (function(){ + var currReqId = 0; + return function nextRequestId() { + return ++currReqId; + } + })(); + + var interface = { + b64EncodeUnicode: b64EncodeUnicode, + checkClientAuthMode: checkClientAuthMode, + checkClientAuthOptions: checkClientAuthOptions, + checkDownloadFilePath: checkDownloadFilePath, + checkFollowRedirectValue: checkFollowRedirectValue, + checkForBlacklistedHeaderKey: checkForBlacklistedHeaderKey, + checkForInvalidHeaderValue: checkForInvalidHeaderValue, + checkSerializer: checkSerializer, + checkSSLCertMode: checkSSLCertMode, + checkTimeoutValue: checkTimeoutValue, + checkUploadFileOptions: checkUploadFileOptions, + getMergedHeaders: getMergedHeaders, + processData: processData, + handleMissingCallbacks: handleMissingCallbacks, + handleMissingOptions: handleMissingOptions, + injectCookieHandler: injectCookieHandler, + injectFileEntryHandler: injectFileEntryHandler, + injectRawResponseHandler: injectRawResponseHandler, + nextRequestId: nextRequestId, + }; + + // expose all functions for testing purposes + if (init.debug) { + interface.mergeHeaders = mergeHeaders; + interface.checkForValidStringValue = checkForValidStringValue; + interface.checkKeyValuePairObject = checkKeyValuePairObject; + interface.checkHttpMethod = checkHttpMethod; + interface.checkResponseType = checkResponseType; + interface.checkHeadersObject = checkHeadersObject; + interface.checkParamsObject = checkParamsObject; + interface.resolveCookieString = resolveCookieString; + interface.createFileEntry = createFileEntry; + interface.getCookieHeader = getCookieHeader; + interface.getMatchingHostHeaders = getMatchingHostHeaders; + interface.getAllowedDataTypes = getAllowedDataTypes; + } + + return interface; + + // Thanks Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_.22Unicode_Problem.22 + function b64EncodeUnicode(str) { + return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) { + return String.fromCharCode('0x' + p1); + })); + } + + function mergeHeaders(globalHeaders, localHeaders) { + var globalKeys = Object.keys(globalHeaders); + var key; + + for (var i = 0; i < globalKeys.length; i++) { + key = globalKeys[i]; + + if (!localHeaders.hasOwnProperty(key)) { + localHeaders[key] = globalHeaders[key]; + } + } + + return localHeaders; + } + + function checkForValidStringValue(list, value, onInvalidValueMessage) { + if (jsUtil.getTypeOf(value) !== 'String') { + throw new Error(onInvalidValueMessage + ' ' + list.join(', ')); + } + + value = value.trim().toLowerCase(); + + if (list.indexOf(value) === -1) { + throw new Error(onInvalidValueMessage + ' ' + list.join(', ')); + } + + return value; + } + + function checkKeyValuePairObject(obj, allowedChildren, onInvalidValueMessage) { + if (jsUtil.getTypeOf(obj) !== 'Object') { + throw new Error(onInvalidValueMessage); + } + + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + if (allowedChildren.indexOf(jsUtil.getTypeOf(obj[keys[i]])) === -1) { + throw new Error(onInvalidValueMessage); + } + } + + return obj; + } + + function checkArray(array, allowedDataTypes, onInvalidValueMessage) { + if (jsUtil.getTypeOf(array) !== 'Array') { + throw new Error(onInvalidValueMessage); + } + + for (var i = 0; i < array.length; ++i) { + if (allowedDataTypes.indexOf(jsUtil.getTypeOf(array[i])) === -1) { + throw new Error(onInvalidValueMessage); + } + } + + return array; + } + + function checkHttpMethod(method) { + return checkForValidStringValue(validHttpMethods, method, messages.INVALID_HTTP_METHOD); + } + + function checkResponseType(type) { + return checkForValidStringValue(validResponseTypes, type, messages.INVALID_RESPONSE_TYPE); + } + + function checkSerializer(serializer) { + return checkForValidStringValue(validSerializers, serializer, messages.INVALID_DATA_SERIALIZER); + } + + function checkSSLCertMode(mode) { + return checkForValidStringValue(validCertModes, mode, messages.INVALID_SSL_CERT_MODE); + } + + function checkClientAuthMode(mode) { + return checkForValidStringValue(validClientAuthModes, mode, messages.INVALID_CLIENT_AUTH_MODE); + } + + function checkClientAuthOptions(mode, options) { + options = options || {}; + + // none + if (mode === validClientAuthModes[0]) { + return { + alias: null, + rawPkcs: null, + pkcsPassword: '' + }; + } + + if (jsUtil.getTypeOf(options) !== 'Object') { + throw new Error(messages.INVALID_CLIENT_AUTH_OPTIONS); + } + + // systemstore + if (mode === validClientAuthModes[1]) { + if (jsUtil.getTypeOf(options.alias) !== 'String' + && jsUtil.getTypeOf(options.alias) !== 'Undefined') { + throw new Error(messages.INVALID_CLIENT_AUTH_ALIAS); + } + + return { + alias: jsUtil.getTypeOf(options.alias) === 'Undefined' ? null : options.alias, + rawPkcs: null, + pkcsPassword: '' + }; + } + + // buffer + if (mode === validClientAuthModes[2]) { + if (jsUtil.getTypeOf(options.rawPkcs) !== 'ArrayBuffer') { + throw new Error(messages.INVALID_CLIENT_AUTH_RAW_PKCS); + } + + if (jsUtil.getTypeOf(options.pkcsPassword) !== 'String') { + throw new Error(messages.INVALID_CLIENT_AUTH_PKCS_PASSWORD); + } + + return { + alias: null, + rawPkcs: options.rawPkcs, + pkcsPassword: options.pkcsPassword + } + } + } + + function checkForBlacklistedHeaderKey(key) { + if (key.toLowerCase() === 'cookie') { + throw new Error(messages.ADDING_COOKIES_NOT_SUPPORTED); + } + + return key; + } + + function checkForInvalidHeaderValue(value) { + var type = jsUtil.getTypeOf(value); + + if (type !== 'String' && type !== 'Null') { + throw new Error(messages.INVALID_HEADER_VALUE); + } + + return value; + } + + function checkTimeoutValue(timeout) { + if (jsUtil.getTypeOf(timeout) !== 'Number' || timeout < 0) { + throw new Error(messages.INVALID_TIMEOUT_VALUE); + } + + return timeout; + } + + function checkFollowRedirectValue(follow) { + if (jsUtil.getTypeOf(follow) !== 'Boolean') { + throw new Error(messages.INVALID_FOLLOW_REDIRECT_VALUE); + } + + return follow; + } + + function checkHeadersObject(headers) { + return checkKeyValuePairObject(headers, ['String'], messages.TYPE_MISMATCH_HEADERS); + } + + function checkParamsObject(params) { + return checkKeyValuePairObject(params, ['String', 'Array'], messages.TYPE_MISMATCH_PARAMS); + } + + function checkDownloadFilePath(filePath) { + if (!filePath || jsUtil.getTypeOf(filePath) !== 'String') { + throw new Error(messages.INVALID_DOWNLOAD_FILE_PATH); + } + + return filePath; + } + + function checkUploadFileOptions(filePaths, names) { + if (jsUtil.getTypeOf(filePaths) === 'String') { + filePaths = [filePaths]; + } + + if (jsUtil.getTypeOf(names) === 'String') { + names = [names]; + } + + var opts = { + filePaths: checkArray(filePaths, ['String'], messages.TYPE_MISMATCH_FILE_PATHS), + names: checkArray(names, ['String'], messages.TYPE_MISMATCH_NAMES) + }; + + if (!opts.filePaths.length) { + throw new Error(messages.EMPTY_FILE_PATHS); + } + + if (!opts.names.length) { + throw new Error(messages.EMPTY_NAMES); + } + + return opts; + } + + function resolveCookieString(headers) { + var keys = Object.keys(headers || {}); + + for (var i = 0; i < keys.length; ++i) { + if (keys[i].match(/^set-cookie$/i)) { + return headers[keys[i]]; + } + } + + return null; + } + + function createFileEntry(rawEntry) { + var entry = new (require('cordova-plugin-file.FileEntry'))(); + + entry.isDirectory = rawEntry.isDirectory; + entry.isFile = rawEntry.isFile; + entry.name = rawEntry.name; + entry.fullPath = rawEntry.fullPath; + entry.filesystem = new FileSystem(rawEntry.filesystemName || (rawEntry.filesystem == global.PERSISTENT ? 'persistent' : 'temporary')); + entry.nativeURL = rawEntry.nativeURL; + + return entry; + } + + function injectCookieHandler(url, cb) { + return function (response) { + cookieHandler.setCookieFromString(url, resolveCookieString(response.headers)); + cb(response); + } + } + + function injectRawResponseHandler(responseType, success, failure) { + return function (response) { + var dataType = jsUtil.getTypeOf(response.data); + + // don't need post-processing if it's already binary type (on browser platform) + if (dataType === 'ArrayBuffer' || dataType === 'Blob') { + return success(response); + } + + try { + // json + if (responseType === validResponseTypes[1]) { + response.data = response.data === '' + ? undefined + : JSON.parse(response.data); + } + + // arraybuffer + else if (responseType === validResponseTypes[2]) { + response.data = response.data === '' + ? null + : base64.toArrayBuffer(response.data); + } + + // blob + else if (responseType === validResponseTypes[3]) { + if (response.data === '') { + response.data = null; + } else { + var buffer = base64.toArrayBuffer(response.data); + var type = response.headers['content-type'] || ''; + var blob = new Blob([buffer], { type: type }); + response.data = blob; + } + } + + success(response); + } catch (error) { + failure({ + status: errorCodes.POST_PROCESSING_FAILED, + error: messages.POST_PROCESSING_FAILED + ' ' + error.message, + url: response.url, + headers: response.headers + }); + } + } + } + + function injectFileEntryHandler(cb) { + return function (response) { + var fileEntry = createFileEntry(response.file); + response.file = fileEntry; + response.data = fileEntry; + cb(fileEntry, response); + } + } + + function getCookieHeader(url) { + var cookieString = cookieHandler.getCookieString(url); + + if (cookieString.length) { + return { Cookie: cookieHandler.getCookieString(url) }; + } + + return {}; + } + + function getMatchingHostHeaders(url, headersList) { + var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i); + var domain = matches && matches[1]; + + return headersList[domain] || null; + } + + function getMergedHeaders(url, requestHeaders, predefinedHeaders) { + var globalHeaders = predefinedHeaders['*'] || {}; + var hostHeaders = getMatchingHostHeaders(url, predefinedHeaders) || {}; + var mergedHeaders = mergeHeaders(globalHeaders, hostHeaders); + + mergedHeaders = mergeHeaders(mergedHeaders, requestHeaders); + mergedHeaders = mergeHeaders(mergedHeaders, getCookieHeader(url)); + + return mergedHeaders; + } + + function getAllowedDataTypes(dataSerializer) { + switch (dataSerializer) { + case 'utf8': + return ['String']; + case 'urlencoded': + return ['Object']; + case 'json': + return ['Array', 'Object']; + case 'raw': + return ['Uint8Array', 'ArrayBuffer']; + default: + return []; + } + } + + function getAllowedInstanceTypes(dataSerializer) { + return dataSerializer === 'multipart' ? ['FormData'] : null; + } + + function processData(data, dataSerializer, cb) { + var currentDataType = jsUtil.getTypeOf(data); + var allowedDataTypes = getAllowedDataTypes(dataSerializer); + var allowedInstanceTypes = getAllowedInstanceTypes(dataSerializer); + + if (allowedInstanceTypes) { + var isCorrectInstanceType = false; + + allowedInstanceTypes.forEach(function (type) { + if ((global[type] && data instanceof global[type]) || (ponyfills[type] && data instanceof ponyfills[type])) { + isCorrectInstanceType = true; + } + }); + + if (!isCorrectInstanceType) { + throw new Error(messages.INSTANCE_TYPE_MISMATCH_DATA + ' ' + allowedInstanceTypes.join(', ')); + } + } + + if (!allowedInstanceTypes && allowedDataTypes.indexOf(currentDataType) === -1) { + throw new Error(messages.TYPE_MISMATCH_DATA + ' ' + allowedDataTypes.join(', ')); + } + + switch (dataSerializer) { + case 'utf8': + return cb({ text: data }); + case 'raw': + return cb(currentDataType === 'Uint8Array' ? data.buffer : data); + case 'multipart': + return processFormData(data, cb); + default: + return cb(data); + } + } + + function processFormData(data, cb) { + dependencyValidator.checkBlobApi(); + dependencyValidator.checkFileReaderApi(); + dependencyValidator.checkTextEncoderApi(); + dependencyValidator.checkFormDataInstance(data); + + var textEncoder = new global.TextEncoder('utf8'); + var iterator = data.entries(); + + var result = { + buffers: [], + names: [], + fileNames: [], + types: [] + }; + + processFormDataIterator(iterator, textEncoder, result, cb); + } + + function processFormDataIterator(iterator, textEncoder, result, onFinished) { + var entry = iterator.next(); + + if (entry.done) { + return onFinished(result); + } + + if (entry.value[1] instanceof global.Blob || entry.value[1] instanceof global.File) { + var reader = new global.FileReader(); + + reader.onload = function () { + result.buffers.push(base64.fromArrayBuffer(reader.result)); + result.names.push(entry.value[0]); + result.fileNames.push(entry.value[1].name !== undefined ? entry.value[1].name : 'blob'); + result.types.push(entry.value[1].type || ''); + processFormDataIterator(iterator, textEncoder, result, onFinished); + }; + + return reader.readAsArrayBuffer(entry.value[1]); + } + + if (jsUtil.getTypeOf(entry.value[1]) === 'String') { + result.buffers.push(base64.fromArrayBuffer(textEncoder.encode(entry.value[1]).buffer)); + result.names.push(entry.value[0]); + result.fileNames.push(null); + result.types.push('text/plain'); + + return processFormDataIterator(iterator, textEncoder, result, onFinished) + } + + // skip items which are not supported + processFormDataIterator(iterator, textEncoder, result, onFinished); + } + + function handleMissingCallbacks(successFn, failFn) { + if (jsUtil.getTypeOf(successFn) !== 'Function') { + throw new Error(messages.MANDATORY_SUCCESS); + } + + if (jsUtil.getTypeOf(failFn) !== 'Function') { + throw new Error(messages.MANDATORY_FAIL); + } + } + + function handleMissingOptions(options, globals) { + options = options || {}; + + return { + data: jsUtil.getTypeOf(options.data) === 'Undefined' ? null : options.data, + filePath: options.filePath, + followRedirect: checkFollowRedirectValue(options.followRedirect || globals.followRedirect), + headers: checkHeadersObject(options.headers || {}), + method: checkHttpMethod(options.method || validHttpMethods[0]), + name: options.name, + params: checkParamsObject(options.params || {}), + responseType: checkResponseType(options.responseType || validResponseTypes[0]), + serializer: checkSerializer(options.serializer || globals.serializer), + connectTimeout: checkTimeoutValue(options.connectTimeout || globals.connectTimeout), + readTimeout: checkTimeoutValue(options.readTimeout || globals.readTimeout), + timeout: checkTimeoutValue(options.timeout || globals.timeout) + }; + } +}; diff --git a/src/plugins/cordova-plugin-advanced-http/www/js-util.js b/src/plugins/cordova-plugin-advanced-http/www/js-util.js new file mode 100644 index 0000000000..593dcc02b7 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/js-util.js @@ -0,0 +1,32 @@ +module.exports = { + // typeof is not working reliably in JS + getTypeOf: function (object) { + switch (Object.prototype.toString.call(object)) { + case '[object Array]': + return 'Array'; + case '[object Blob]': + return 'Blob'; + case '[object Uint8Array]': + return 'Uint8Array'; + case '[object ArrayBuffer]': + return 'ArrayBuffer'; + case '[object Boolean]': + return 'Boolean'; + case '[object Function]': + return 'Function'; + case '[object Null]': + return 'Null'; + case '[object Number]': + return 'Number'; + case '[object Object]': + return 'Object'; + case '[object String]': + return 'String'; + case '[object Undefined]': + return 'Undefined'; + default: + return 'Unknown'; + } + } +} + diff --git a/src/plugins/cordova-plugin-advanced-http/www/local-storage-store.js b/src/plugins/cordova-plugin-advanced-http/www/local-storage-store.js new file mode 100644 index 0000000000..c25e41a0b3 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/local-storage-store.js @@ -0,0 +1,181 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2016 Exponent + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * Based on "tough-cookie-web-storage-store" v1.0.0 + * Thanks James Ide: https://github.com/exponentjs/tough-cookie-web-storage-store + * + * Modified by Sefa Ilkimen for cordova plugin integration + * + */ + +'use strict'; + +module.exports = function init(ToughCookie, _) { + function WebStorageCookieStore(storage, storeKey) { + ToughCookie.Store.call(this); + this._storage = storage; + this._storeKey = storeKey || '__cookieStore__'; + this.synchronous = true; + } + + WebStorageCookieStore.prototype = Object.create(ToughCookie.Store); + + WebStorageCookieStore.prototype.findCookie = function (domain, path, key, callback) { + var store = this._readStore(); + var cookie = _.get(store, [domain, path, key], null); + + callback(null, ToughCookie.Cookie.fromJSON(cookie)); + }; + + WebStorageCookieStore.prototype.findCookies = function (domain, path, callback) { + if (!domain) { + callback(null, []); + return; + } + + var that = this; + var cookies = []; + var store = this._readStore(); + var domains = ToughCookie.permuteDomain(domain) || [domain]; + + domains.forEach(function (domain) { + if (!store[domain]) { + return; + } + + var matchingPaths = Object.keys(store[domain]); + + if (path != null) { + matchingPaths = matchingPaths.filter(function (cookiePath) { + return that._isOnPath(cookiePath, path); + }); + } + + matchingPaths.forEach(function (path) { + Array.prototype.push.apply(cookies, _.values(store[domain][path])); + }); + }); + + cookies = cookies.map(function (cookie) { + return ToughCookie.Cookie.fromJSON(cookie); + }); + + callback(null, cookies); + }; + + /** + * Returns whether `cookiePath` is on the given `urlPath` + */ + WebStorageCookieStore.prototype._isOnPath = function (cookiePath, urlPath) { + if (!cookiePath) { + return false; + } + + if (cookiePath === urlPath) { + return true; + } + + if (urlPath.indexOf(cookiePath) !== 0) { + return false; + } + + if (cookiePath[cookiePath.length - 1] !== '/' && urlPath[cookiePath.length] !== '/') { + return false; + } + + return true; + }; + + WebStorageCookieStore.prototype.putCookie = function (cookie, callback) { + var store = this._readStore(); + + _.set(store, [cookie.domain, cookie.path, cookie.key], cookie); + this._writeStore(store); + callback(null); + }; + + WebStorageCookieStore.prototype.updateCookie = function (oldCookie, newCookie, callback) { + this.putCookie(newCookie, callback); + }; + + + WebStorageCookieStore.prototype.removeCookie = function (domain, path, key, callback) { + var store = this._readStore(); + + _.unset(store, [domain, path, key]); + this._writeStore(store); + callback(null); + }; + + WebStorageCookieStore.prototype.removeCookies = function (domain, path, callback) { + var store = this._readStore(); + + if (path == null) { + _.unset(store, [domain]); + } else { + _.unset(store, [domain, path]); + } + + this._writeStore(store); + callback(null); + }; + + WebStorageCookieStore.prototype.getAllCookies = function (callback) { + var cookies = []; + var store = this._readStore(); + + Object.keys(store).forEach(function (domain) { + Object.keys(store[domain]).forEach(function (path) { + Array.prototype.push.apply(cookies, _.values(store[domain][path])); + }); + }); + + cookies = cookies.map(function (cookie) { + return ToughCookie.Cookie.fromJSON(cookie); + }); + + cookies.sort(function (c1, c2) { + return (c1.creationIndex || 0) - (c2.creationIndex || 0); + }); + + callback(null, cookies); + }; + + WebStorageCookieStore.prototype._readStore = function () { + var json = this._storage.getItem(this._storeKey); + + if (json !== null) { + try { + return JSON.parse(json); + } catch (e) { } + } + + return {}; + }; + + WebStorageCookieStore.prototype._writeStore = function (store) { + this._storage.setItem(this._storeKey, JSON.stringify(store)); + }; + + return WebStorageCookieStore; +}; diff --git a/src/plugins/cordova-plugin-advanced-http/www/lodash.js b/src/plugins/cordova-plugin-advanced-http/www/lodash.js new file mode 100644 index 0000000000..302dd8baaa --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/lodash.js @@ -0,0 +1,20 @@ +/** + * @license + * Lodash (Custom Build) lodash.com/license | Underscore.js 1.8.3 underscorejs.org/LICENSE + * Build: `lodash include="get,set,unset,values" exports="node"` + */ +;(function(){function t(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=t; +}function S(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function w(t){return null!=t&&typeof t=="object"}function x(t){return typeof t=="symbol"||w(t)&&"[object Symbol]"==l(t)}function F(t){return null==t?"":p(t)}function $(t){if(A(t)){var e=ft(t),r=!e&&st(t),n=!e&&!r&&pt(t),o=!e&&!r&&!n&&ht(t);if(e=e||r||n||o){for(var r=t.length,u=String,i=-1,c=Array(r);++it)&&(t==e.length-1?e.pop():rt.call(e,t,1),--this.size,true)},u.prototype.get=function(t){var e=this.__data__;return t=c(e,t),0>t?E:e[t][1]},u.prototype.has=function(t){ +return-1n?(++this.size,r.push([t,e])):r[n][1]=e,this},i.prototype.clear=function(){this.size=0,this.__data__={hash:new o,map:new(it||u),string:new o}},i.prototype.delete=function(t){return t=y(this,t).delete(t),this.size-=t?1:0,t},i.prototype.get=function(t){return y(this,t).get(t)},i.prototype.has=function(t){return y(this,t).has(t)},i.prototype.set=function(t,e){var r=y(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1, +this};var lt=function(t){t=d(t,function(t){return 500===e.size&&e.clear(),t});var e=t.cache;return t}(function(t){var e=[];return P.test(t)&&e.push(""),t.replace(U,function(t,r,n,o){e.push(n?o.replace(C,"$1"):r||t)}),e});d.Cache=i;var st=s(function(){return arguments}())?s:function(t){return w(t)&&Q.call(t,"callee")&&!et.call(t,"callee")},ft=Array.isArray,pt=D||k,ht=N?e(N):f;n.keys=$,n.memoize=d,n.set=function(t,e,r){if(null!=t&&S(t)){e=h(e,t);for(var n=-1,o=e.length,u=o-1,i=t;null!=i&&++no.length)){var u=0,i=-1,c=-1,l=o.length;for(0>u&&(u=-u>l?0:l+u),i=i>l?l:i,0>i&&(i+=l),l=u>i?0:i-u>>>0,u>>>=0,i=Array(l);++c', + EMPTY_NAMES: 'advanced-http: "names" option array must not be empty, ', + INSTANCE_TYPE_MISMATCH_DATA: 'advanced-http: "data" option is configured to support only following instance types:', + INVALID_CLIENT_AUTH_ALIAS: 'advanced-http: invalid client certificate alias, needs to be a string or undefined, ', + INVALID_CLIENT_AUTH_MODE: 'advanced-http: invalid client certificate authentication mode, supported modes are:', + INVALID_CLIENT_AUTH_OPTIONS: 'advanced-http: invalid client certificate authentication options, needs to be an dictionary style object', + INVALID_CLIENT_AUTH_PKCS_PASSWORD: 'advanced-http: invalid PKCS12 container password, needs to be a string, ', + INVALID_CLIENT_AUTH_RAW_PKCS: 'advanced-http: invalid PKCS12 container, needs to be an array buffer, ', + INVALID_DATA_SERIALIZER: 'advanced-http: invalid serializer, supported serializers are:', + INVALID_DOWNLOAD_FILE_PATH: 'advanced-http: invalid "filePath" value, needs to be a string, ', + INVALID_FOLLOW_REDIRECT_VALUE: 'advanced-http: invalid follow redirect value, needs to be a boolean value, ', + INVALID_HEADER_VALUE: 'advanced-http: invalid header value, needs to be a string or null, ', + INVALID_HTTP_METHOD: 'advanced-http: invalid HTTP method, supported methods are:', + INVALID_RESPONSE_TYPE: 'advanced-http: invalid response type, supported types are:', + INVALID_SSL_CERT_MODE: 'advanced-http: invalid SSL cert mode, supported modes are:', + INVALID_TIMEOUT_VALUE: 'advanced-http: invalid timeout value, needs to be a positive numeric value, ', + MANDATORY_FAIL: 'advanced-http: missing mandatory "onFail" callback function', + MANDATORY_SUCCESS: 'advanced-http: missing mandatory "onSuccess" callback function', + MISSING_BLOB_API: 'advanced-http: Blob API is not supported in this webview. If you want to use "multipart/form-data" requests, you need to load a polyfill library before loading this plugin. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.', + MISSING_FILE_READER_API: 'advanced-http: FileReader API is not supported in this webview. If you want to use "multipart/form-data" requests, you need to load a polyfill library before loading this plugin. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.', + MISSING_FORMDATA_API: 'advanced-http: FormData API is not supported in this webview. If you want to use "multipart/form-data" requests, you need to load a polyfill library before loading this plugin. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.', + MISSING_FORMDATA_ENTRIES_API: 'advanced-http: Given instance of FormData does not implement FormData API specification correctly, FormData.entries() is missing. If you want to use "multipart/form-data" requests, you can use an included ponyfill. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.', + MISSING_TEXT_ENCODER_API: 'advanced-http: TextEncoder API is not supported in this webview. If you want to use "multipart/form-data" requests, you need to load a polyfill library before loading this plugin. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.', + POST_PROCESSING_FAILED: 'advanced-http: an error occured during post processing response:', + TYPE_MISMATCH_DATA: 'advanced-http: "data" option is configured to support only following data types:', + TYPE_MISMATCH_FILE_PATHS: 'advanced-http: "filePaths" option needs to be an string array, ', + TYPE_MISMATCH_HEADERS: 'advanced-http: "headers" option needs to be an dictionary style object with string values, ', + TYPE_MISMATCH_NAMES: 'advanced-http: "names" option needs to be an string array, ', + TYPE_MISMATCH_PARAMS: 'advanced-http: "params" option needs to be an dictionary style object, ', +}; diff --git a/src/plugins/cordova-plugin-advanced-http/www/ponyfills.js b/src/plugins/cordova-plugin-advanced-http/www/ponyfills.js new file mode 100644 index 0000000000..b13d774224 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/ponyfills.js @@ -0,0 +1,47 @@ +module.exports = function init(global) { + var interface = { FormData: FormData }; + + // expose all constructor functions for testing purposes + if (init.debug) { + interface.Iterator = Iterator; + } + + function FormData() { + this.__items = []; + } + + FormData.prototype.append = function(name, value, filename) { + if (global.File && value instanceof global.File) { + // nothing to do + } else if (global.Blob && value instanceof global.Blob) { + // mimic File instance by adding missing properties + value.lastModifiedDate = new Date(); + value.name = filename !== undefined ? filename : 'blob'; + } else { + value = String(value); + } + + this.__items.push([ name, value ]); + }; + + FormData.prototype.entries = function() { + return new Iterator(this.__items); + }; + + function Iterator(items) { + this.__items = items; + this.__position = -1; + } + + Iterator.prototype.next = function() { + this.__position += 1; + + if (this.__position < this.__items.length) { + return { done: false, value: this.__items[this.__position] }; + } + + return { done: true, value: undefined }; + } + + return interface; +}; diff --git a/src/plugins/cordova-plugin-advanced-http/www/public-interface.js b/src/plugins/cordova-plugin-advanced-http/www/public-interface.js new file mode 100644 index 0000000000..66b5261207 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/public-interface.js @@ -0,0 +1,239 @@ +module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConfigs, errorCodes, ponyfills) { + var publicInterface = { + getBasicAuthHeader: getBasicAuthHeader, + useBasicAuth: useBasicAuth, + getHeaders: getHeaders, + setHeader: setHeader, + getDataSerializer: getDataSerializer, + setDataSerializer: setDataSerializer, + setCookie: setCookie, + clearCookies: clearCookies, + removeCookies: removeCookies, + getCookieString: getCookieString, + getRequestTimeout: getRequestTimeout, + setRequestTimeout: setRequestTimeout, + getFollowRedirect: getFollowRedirect, + setFollowRedirect: setFollowRedirect, + // @Android Only + getConnectTimeout: getConnectTimeout, + // @Android Only + setConnectTimeout: setConnectTimeout, + getReadTimeout: getReadTimeout, + setReadTimeout: setReadTimeout, + setServerTrustMode: setServerTrustMode, + setClientAuthMode: setClientAuthMode, + sendRequest: sendRequest, + post: post, + put: put, + patch: patch, + get: get, + delete: del, + head: head, + options: options, + uploadFile: uploadFile, + downloadFile: downloadFile, + abort: abort, + ErrorCode: errorCodes, + ponyfills: ponyfills + }; + + function getBasicAuthHeader(username, password) { + return { 'Authorization': 'Basic ' + helpers.b64EncodeUnicode(username + ':' + password) }; + } + + function useBasicAuth(username, password) { + this.setHeader('*', 'Authorization', 'Basic ' + helpers.b64EncodeUnicode(username + ':' + password)); + } + + function getHeaders(host) { + return globalConfigs.headers[host || '*'] || null; + } + + function setHeader() { + // this one is for being backward compatible + var host = '*'; + var header = arguments[0]; + var value = arguments[1]; + + if (arguments.length === 3) { + host = arguments[0]; + header = arguments[1]; + value = arguments[2]; + } + + helpers.checkForBlacklistedHeaderKey(header); + helpers.checkForInvalidHeaderValue(value); + + globalConfigs.headers[host] = globalConfigs.headers[host] || {}; + + if (value === null) { + delete globalConfigs.headers[host][header]; + } else { + globalConfigs.headers[host][header] = value; + } + } + + function getDataSerializer() { + return globalConfigs.serializer; + } + + function setDataSerializer(serializer) { + globalConfigs.serializer = helpers.checkSerializer(serializer); + } + + function setCookie(url, cookie, options) { + cookieHandler.setCookie(url, cookie, options); + } + + function clearCookies() { + cookieHandler.clearCookies(); + } + + function removeCookies(url, callback) { + cookieHandler.removeCookies(url, callback); + } + + function getCookieString(url) { + return cookieHandler.getCookieString(url); + } + + function getRequestTimeout() { + return globalConfigs.timeout; + } + + function setRequestTimeout(timeout) { + globalConfigs.timeout = helpers.checkTimeoutValue(timeout); + globalConfigs.connectTimeout = helpers.checkTimeoutValue(timeout); + globalConfigs.readTimeout = helpers.checkTimeoutValue(timeout); + } + + function getConnectTimeout() { + return globalConfigs.connectTimeout; + } + + function setConnectTimeout(timeout) { + globalConfigs.connectTimeout = helpers.checkTimeoutValue(timeout); + } + + function getReadTimeout() { + return globalConfigs.readTimeout; + } + + function setReadTimeout(timeout) { + globalConfigs.readTimeout = helpers.checkTimeoutValue(timeout); + } + + function getFollowRedirect() { + return globalConfigs.followRedirect; + } + + function setFollowRedirect(follow) { + globalConfigs.followRedirect = helpers.checkFollowRedirectValue(follow); + } + + function setServerTrustMode(mode, success, failure) { + helpers.handleMissingCallbacks(success, failure); + + return exec(success, failure, 'CordovaHttpPlugin', 'setServerTrustMode', [helpers.checkSSLCertMode(mode)]); + } + + function setClientAuthMode() { + var mode = arguments[0]; + var options = null; + var success = arguments[1]; + var failure = arguments[2]; + + if (arguments.length === 4) { + options = arguments[1]; + success = arguments[2]; + failure = arguments[3]; + } + + mode = helpers.checkClientAuthMode(mode); + options = helpers.checkClientAuthOptions(mode, options); + + helpers.handleMissingCallbacks(success, failure); + + return exec(success, failure, 'CordovaHttpPlugin', 'setClientAuthMode', [mode, options.alias, options.rawPkcs, options.pkcsPassword]); + } + + function sendRequest(url, options, success, failure) { + helpers.handleMissingCallbacks(success, failure); + + options = helpers.handleMissingOptions(options, globalConfigs); + url = urlUtil.appendQueryParamsString(url, urlUtil.serializeQueryParams(options.params, true)); + + var headers = helpers.getMergedHeaders(url, options.headers, globalConfigs.headers); + + var onFail = helpers.injectCookieHandler(url, failure); + var onSuccess = helpers.injectCookieHandler(url, helpers.injectRawResponseHandler(options.responseType, success, failure)); + + var reqId = helpers.nextRequestId(); + + switch (options.method) { + case 'post': + case 'put': + case 'patch': + helpers.processData(options.data, options.serializer, function (data) { + exec(onSuccess, onFail, 'CordovaHttpPlugin', options.method, [url, data, options.serializer, headers, options.connectTimeout, options.readTimeout, options.followRedirect, options.responseType, reqId]); + }); + break; + case 'upload': + var fileOptions = helpers.checkUploadFileOptions(options.filePath, options.name); + exec(onSuccess, onFail, 'CordovaHttpPlugin', 'uploadFiles', [url, headers, fileOptions.filePaths, fileOptions.names, options.connectTimeout, options.readTimeout, options.followRedirect, options.responseType, reqId]); + break; + case 'download': + var filePath = helpers.checkDownloadFilePath(options.filePath); + var onDownloadSuccess = helpers.injectCookieHandler(url, helpers.injectFileEntryHandler(success)); + exec(onDownloadSuccess, onFail, 'CordovaHttpPlugin', 'downloadFile', [url, headers, filePath, options.connectTimeout, options.readTimeout, options.followRedirect, reqId]); + break; + default: + exec(onSuccess, onFail, 'CordovaHttpPlugin', options.method, [url, headers, options.connectTimeout, options.readTimeout, options.followRedirect, options.responseType, reqId]); + break; + } + + return reqId; + } + + function post(url, data, headers, success, failure) { + return publicInterface.sendRequest(url, { method: 'post', data: data, headers: headers }, success, failure); + }; + + function put(url, data, headers, success, failure) { + return publicInterface.sendRequest(url, { method: 'put', data: data, headers: headers }, success, failure); + } + + function patch(url, data, headers, success, failure) { + return publicInterface.sendRequest(url, { method: 'patch', data: data, headers: headers }, success, failure); + } + + function get(url, params, headers, success, failure) { + return publicInterface.sendRequest(url, { method: 'get', params: params, headers: headers }, success, failure); + }; + + function del(url, params, headers, success, failure) { + return publicInterface.sendRequest(url, { method: 'delete', params: params, headers: headers }, success, failure); + } + + function head(url, params, headers, success, failure) { + return publicInterface.sendRequest(url, { method: 'head', params: params, headers: headers }, success, failure); + } + + function options(url, params, headers, success, failure) { + return publicInterface.sendRequest(url, { method: 'options', params: params, headers: headers }, success, failure); + }; + + function uploadFile(url, params, headers, filePath, name, success, failure) { + return publicInterface.sendRequest(url, { method: 'upload', params: params, headers: headers, filePath: filePath, name: name }, success, failure); + } + + function downloadFile(url, params, headers, filePath, success, failure) { + return publicInterface.sendRequest(url, { method: 'download', params: params, headers: headers, filePath: filePath }, success, failure); + } + + function abort(requestId , success, failure) { + return exec(success, failure, 'CordovaHttpPlugin', 'abort', [requestId]); + } + + return publicInterface; +} diff --git a/src/plugins/cordova-plugin-advanced-http/www/umd-tough-cookie.js b/src/plugins/cordova-plugin-advanced-http/www/umd-tough-cookie.js new file mode 100644 index 0000000000..89f265187f --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/umd-tough-cookie.js @@ -0,0 +1,5061 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["ToughCookie"] = factory(); + else + root["ToughCookie"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + 'use strict'; + var urlParse = __webpack_require__(1).parse; + var util = __webpack_require__(8); + var ipRegex = __webpack_require__(12)({ exact: true }); + var pubsuffix = __webpack_require__(13); + var Store = __webpack_require__(17).Store; + var MemoryCookieStore = __webpack_require__(18).MemoryCookieStore; + var pathMatch = __webpack_require__(20).pathMatch; + var VERSION = __webpack_require__(21); + + var punycode; + try { + punycode = __webpack_require__(15); + } catch(e) { + console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization"); + } + + // From RFC6265 S4.1.1 + // note that it excludes \x3B ";" + var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; + + var CONTROL_CHARS = /[\x00-\x1F]/; + + // From Chromium // '\r', '\n' and '\0' should be treated as a terminator in + // the "relaxed" mode, see: + // https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 + var TERMINATORS = ['\n', '\r', '\0']; + + // RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' + // Note ';' is \x3B + var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; + + // date-time parsing constants (RFC6265 S5.1.1) + + var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; + + var MONTH_TO_NUM = { + jan:0, feb:1, mar:2, apr:3, may:4, jun:5, + jul:6, aug:7, sep:8, oct:9, nov:10, dec:11 + }; + var NUM_TO_MONTH = [ + 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' + ]; + var NUM_TO_DAY = [ + 'Sun','Mon','Tue','Wed','Thu','Fri','Sat' + ]; + + var MAX_TIME = 2147483647000; // 31-bit max + var MIN_TIME = 0; // 31-bit min + + /* + * Parses a Natural number (i.e., non-negative integer) with either the + * *DIGIT ( non-digit *OCTET ) + * or + * *DIGIT + * grammar (RFC6265 S5.1.1). + * + * The "trailingOK" boolean controls if the grammar accepts a + * "( non-digit *OCTET )" trailer. + */ + function parseDigits(token, minDigits, maxDigits, trailingOK) { + var count = 0; + while (count < token.length) { + var c = token.charCodeAt(count); + // "non-digit = %x00-2F / %x3A-FF" + if (c <= 0x2F || c >= 0x3A) { + break; + } + count++; + } + + // constrain to a minimum and maximum number of digits. + if (count < minDigits || count > maxDigits) { + return null; + } + + if (!trailingOK && count != token.length) { + return null; + } + + return parseInt(token.substr(0,count), 10); + } + + function parseTime(token) { + var parts = token.split(':'); + var result = [0,0,0]; + + /* RF6256 S5.1.1: + * time = hms-time ( non-digit *OCTET ) + * hms-time = time-field ":" time-field ":" time-field + * time-field = 1*2DIGIT + */ + + if (parts.length !== 3) { + return null; + } + + for (var i = 0; i < 3; i++) { + // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be + // followed by "( non-digit *OCTET )" so therefore the last time-field can + // have a trailer + var trailingOK = (i == 2); + var num = parseDigits(parts[i], 1, 2, trailingOK); + if (num === null) { + return null; + } + result[i] = num; + } + + return result; + } + + function parseMonth(token) { + token = String(token).substr(0,3).toLowerCase(); + var num = MONTH_TO_NUM[token]; + return num >= 0 ? num : null; + } + + /* + * RFC6265 S5.1.1 date parser (see RFC for full grammar) + */ + function parseDate(str) { + if (!str) { + return; + } + + /* RFC6265 S5.1.1: + * 2. Process each date-token sequentially in the order the date-tokens + * appear in the cookie-date + */ + var tokens = str.split(DATE_DELIM); + if (!tokens) { + return; + } + + var hour = null; + var minute = null; + var second = null; + var dayOfMonth = null; + var month = null; + var year = null; + + for (var i=0; i= 70 && year <= 99) { + year += 1900; + } else if (year >= 0 && year <= 69) { + year += 2000; + } + } + } + } + + /* RFC 6265 S5.1.1 + * "5. Abort these steps and fail to parse the cookie-date if: + * * at least one of the found-day-of-month, found-month, found- + * year, or found-time flags is not set, + * * the day-of-month-value is less than 1 or greater than 31, + * * the year-value is less than 1601, + * * the hour-value is greater than 23, + * * the minute-value is greater than 59, or + * * the second-value is greater than 59. + * (Note that leap seconds cannot be represented in this syntax.)" + * + * So, in order as above: + */ + if ( + dayOfMonth === null || month === null || year === null || second === null || + dayOfMonth < 1 || dayOfMonth > 31 || + year < 1601 || + hour > 23 || + minute > 59 || + second > 59 + ) { + return; + } + + return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); + } + + function formatDate(date) { + var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d; + var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h; + var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m; + var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s; + return NUM_TO_DAY[date.getUTCDay()] + ', ' + + d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+ + h+':'+m+':'+s+' GMT'; + } + + // S5.1.2 Canonicalized Host Names + function canonicalDomain(str) { + if (str == null) { + return null; + } + str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading . + + // convert to IDN if any non-ASCII characters + if (punycode && /[^\u0001-\u007f]/.test(str)) { + str = punycode.toASCII(str); + } + + return str.toLowerCase(); + } + + // S5.1.3 Domain Matching + function domainMatch(str, domStr, canonicalize) { + if (str == null || domStr == null) { + return null; + } + if (canonicalize !== false) { + str = canonicalDomain(str); + domStr = canonicalDomain(domStr); + } + + /* + * "The domain string and the string are identical. (Note that both the + * domain string and the string will have been canonicalized to lower case at + * this point)" + */ + if (str == domStr) { + return true; + } + + /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */ + + /* "* The string is a host name (i.e., not an IP address)." */ + if (ipRegex.test(str)) { + return false; + } + + /* "* The domain string is a suffix of the string" */ + var idx = str.indexOf(domStr); + if (idx <= 0) { + return false; // it's a non-match (-1) or prefix (0) + } + + // e.g "a.b.c".indexOf("b.c") === 2 + // 5 === 3+2 + if (str.length !== domStr.length + idx) { // it's not a suffix + return false; + } + + /* "* The last character of the string that is not included in the domain + * string is a %x2E (".") character." */ + if (str.substr(idx-1,1) !== '.') { + return false; + } + + return true; + } + + + // RFC6265 S5.1.4 Paths and Path-Match + + /* + * "The user agent MUST use an algorithm equivalent to the following algorithm + * to compute the default-path of a cookie:" + * + * Assumption: the path (and not query part or absolute uri) is passed in. + */ + function defaultPath(path) { + // "2. If the uri-path is empty or if the first character of the uri-path is not + // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. + if (!path || path.substr(0,1) !== "/") { + return "/"; + } + + // "3. If the uri-path contains no more than one %x2F ("/") character, output + // %x2F ("/") and skip the remaining step." + if (path === "/") { + return path; + } + + var rightSlash = path.lastIndexOf("/"); + if (rightSlash === 0) { + return "/"; + } + + // "4. Output the characters of the uri-path from the first character up to, + // but not including, the right-most %x2F ("/")." + return path.slice(0, rightSlash); + } + + function trimTerminator(str) { + for (var t = 0; t < TERMINATORS.length; t++) { + var terminatorIdx = str.indexOf(TERMINATORS[t]); + if (terminatorIdx !== -1) { + str = str.substr(0,terminatorIdx); + } + } + + return str; + } + + function parseCookiePair(cookiePair, looseMode) { + cookiePair = trimTerminator(cookiePair); + + var firstEq = cookiePair.indexOf('='); + if (looseMode) { + if (firstEq === 0) { // '=' is immediately at start + cookiePair = cookiePair.substr(1); + firstEq = cookiePair.indexOf('='); // might still need to split on '=' + } + } else { // non-loose mode + if (firstEq <= 0) { // no '=' or is at start + return; // needs to have non-empty "cookie-name" + } + } + + var cookieName, cookieValue; + if (firstEq <= 0) { + cookieName = ""; + cookieValue = cookiePair.trim(); + } else { + cookieName = cookiePair.substr(0, firstEq).trim(); + cookieValue = cookiePair.substr(firstEq+1).trim(); + } + + if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { + return; + } + + var c = new Cookie(); + c.key = cookieName; + c.value = cookieValue; + return c; + } + + function parse(str, options) { + if (!options || typeof options !== 'object') { + options = {}; + } + str = str.trim(); + + // We use a regex to parse the "name-value-pair" part of S5.2 + var firstSemi = str.indexOf(';'); // S5.2 step 1 + var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi); + var c = parseCookiePair(cookiePair, !!options.loose); + if (!c) { + return; + } + + if (firstSemi === -1) { + return c; + } + + // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question)." plus later on in the same section + // "discard the first ";" and trim". + var unparsed = str.slice(firstSemi + 1).trim(); + + // "If the unparsed-attributes string is empty, skip the rest of these + // steps." + if (unparsed.length === 0) { + return c; + } + + /* + * S5.2 says that when looping over the items "[p]rocess the attribute-name + * and attribute-value according to the requirements in the following + * subsections" for every item. Plus, for many of the individual attributes + * in S5.3 it says to use the "attribute-value of the last attribute in the + * cookie-attribute-list". Therefore, in this implementation, we overwrite + * the previous value. + */ + var cookie_avs = unparsed.split(';'); + while (cookie_avs.length) { + var av = cookie_avs.shift().trim(); + if (av.length === 0) { // happens if ";;" appears + continue; + } + var av_sep = av.indexOf('='); + var av_key, av_value; + + if (av_sep === -1) { + av_key = av; + av_value = null; + } else { + av_key = av.substr(0,av_sep); + av_value = av.substr(av_sep+1); + } + + av_key = av_key.trim().toLowerCase(); + + if (av_value) { + av_value = av_value.trim(); + } + + switch(av_key) { + case 'expires': // S5.2.1 + if (av_value) { + var exp = parseDate(av_value); + // "If the attribute-value failed to parse as a cookie date, ignore the + // cookie-av." + if (exp) { + // over and underflow not realistically a concern: V8's getTime() seems to + // store something larger than a 32-bit time_t (even with 32-bit node) + c.expires = exp; + } + } + break; + + case 'max-age': // S5.2.2 + if (av_value) { + // "If the first character of the attribute-value is not a DIGIT or a "-" + // character ...[or]... If the remainder of attribute-value contains a + // non-DIGIT character, ignore the cookie-av." + if (/^-?[0-9]+$/.test(av_value)) { + var delta = parseInt(av_value, 10); + // "If delta-seconds is less than or equal to zero (0), let expiry-time + // be the earliest representable date and time." + c.setMaxAge(delta); + } + } + break; + + case 'domain': // S5.2.3 + // "If the attribute-value is empty, the behavior is undefined. However, + // the user agent SHOULD ignore the cookie-av entirely." + if (av_value) { + // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E + // (".") character." + var domain = av_value.trim().replace(/^\./, ''); + if (domain) { + // "Convert the cookie-domain to lower case." + c.domain = domain.toLowerCase(); + } + } + break; + + case 'path': // S5.2.4 + /* + * "If the attribute-value is empty or if the first character of the + * attribute-value is not %x2F ("/"): + * Let cookie-path be the default-path. + * Otherwise: + * Let cookie-path be the attribute-value." + * + * We'll represent the default-path as null since it depends on the + * context of the parsing. + */ + c.path = av_value && av_value[0] === "/" ? av_value : null; + break; + + case 'secure': // S5.2.5 + /* + * "If the attribute-name case-insensitively matches the string "Secure", + * the user agent MUST append an attribute to the cookie-attribute-list + * with an attribute-name of Secure and an empty attribute-value." + */ + c.secure = true; + break; + + case 'httponly': // S5.2.6 -- effectively the same as 'secure' + c.httpOnly = true; + break; + + default: + c.extensions = c.extensions || []; + c.extensions.push(av); + break; + } + } + + return c; + } + + // avoid the V8 deoptimization monster! + function jsonParse(str) { + var obj; + try { + obj = JSON.parse(str); + } catch (e) { + return e; + } + return obj; + } + + function fromJSON(str) { + if (!str) { + return null; + } + + var obj; + if (typeof str === 'string') { + obj = jsonParse(str); + if (obj instanceof Error) { + return null; + } + } else { + // assume it's an Object + obj = str; + } + + var c = new Cookie(); + for (var i=0; i 1) { + var lindex = path.lastIndexOf('/'); + if (lindex === 0) { + break; + } + path = path.substr(0,lindex); + permutations.push(path); + } + permutations.push('/'); + return permutations; + } + + function getCookieContext(url) { + if (url instanceof Object) { + return url; + } + // NOTE: decodeURI will throw on malformed URIs (see GH-32). + // Therefore, we will just skip decoding for such URIs. + try { + url = decodeURI(url); + } + catch(err) { + // Silently swallow error + } + + return urlParse(url); + } + + function Cookie(options) { + options = options || {}; + + Object.keys(options).forEach(function(prop) { + if (Cookie.prototype.hasOwnProperty(prop) && + Cookie.prototype[prop] !== options[prop] && + prop.substr(0,1) !== '_') + { + this[prop] = options[prop]; + } + }, this); + + this.creation = this.creation || new Date(); + + // used to break creation ties in cookieCompare(): + Object.defineProperty(this, 'creationIndex', { + configurable: false, + enumerable: false, // important for assert.deepEqual checks + writable: true, + value: ++Cookie.cookiesCreated + }); + } + + Cookie.cookiesCreated = 0; // incremented each time a cookie is created + + Cookie.parse = parse; + Cookie.fromJSON = fromJSON; + + Cookie.prototype.key = ""; + Cookie.prototype.value = ""; + + // the order in which the RFC has them: + Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity + Cookie.prototype.maxAge = null; // takes precedence over expires for TTL + Cookie.prototype.domain = null; + Cookie.prototype.path = null; + Cookie.prototype.secure = false; + Cookie.prototype.httpOnly = false; + Cookie.prototype.extensions = null; + + // set by the CookieJar: + Cookie.prototype.hostOnly = null; // boolean when set + Cookie.prototype.pathIsDefault = null; // boolean when set + Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse + Cookie.prototype.lastAccessed = null; // Date when set + Object.defineProperty(Cookie.prototype, 'creationIndex', { + configurable: true, + enumerable: false, + writable: true, + value: 0 + }); + + Cookie.serializableProperties = Object.keys(Cookie.prototype) + .filter(function(prop) { + return !( + Cookie.prototype[prop] instanceof Function || + prop === 'creationIndex' || + prop.substr(0,1) === '_' + ); + }); + + Cookie.prototype.inspect = function inspect() { + var now = Date.now(); + return 'Cookie="'+this.toString() + + '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') + + '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') + + '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') + + '"'; + }; + + // Use the new custom inspection symbol to add the custom inspect function if + // available. + if (util.inspect.custom) { + Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect; + } + + Cookie.prototype.toJSON = function() { + var obj = {}; + + var props = Cookie.serializableProperties; + for (var i=0; i', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = __webpack_require__(5); + + function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; + } + + Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; + }; + + // format a parsed object into a url string + function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); + } + + Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; + }; + + function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); + } + + Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + }; + + function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); + } + + Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; + + Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; + }; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {/*! https://mths.be/punycode v1.3.2 by @mathias */ + ;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + true + ) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { + return punycode; + }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } + + }(this)); + + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)(module), (function() { return this; }()))) + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + module.exports = function(module) { + if(!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + module.children = []; + module.webpackPolyfill = 1; + } + return module; + } + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + 'use strict'; + + module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } + }; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.decode = exports.parse = __webpack_require__(6); + exports.encode = exports.stringify = __webpack_require__(7); + + +/***/ }), +/* 6 */ +/***/ (function(module, exports) { + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + // If obj.hasOwnProperty has been overridden, then calling + // obj.hasOwnProperty(prop) will break. + // See: https://github.com/joyent/node/issues/1707 + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; + }; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports) { + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } + }; + + module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); + }; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var formatRegExp = /%[sdj%]/g; + exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + }; + + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + }; + + + var debugs = {}; + var debugEnviron; + exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + }; + + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + exports.inspect = inspect; + + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + exports.isArray = isArray; + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + exports.isBoolean = isBoolean; + + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + + function isNumber(arg) { + return typeof arg === 'number'; + } + exports.isNumber = isNumber; + + function isString(arg) { + return typeof arg === 'string'; + } + exports.isString = isString; + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + exports.isSymbol = isSymbol; + + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + exports.isRegExp = isRegExp; + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + exports.isObject = isObject; + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + exports.isDate = isDate; + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + exports.isError = isError; + + function isFunction(arg) { + return typeof arg === 'function'; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + exports.isPrimitive = isPrimitive; + + exports.isBuffer = __webpack_require__(10); + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); + }; + + + /** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ + exports.inherits = __webpack_require__(11); + + exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + }; + + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(9))) + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + // shim for using process in browser + var process = module.exports = {}; + + // cached from whatever global is present so that test runners that stub it + // don't break things. But we need to wrap it in a try catch in case it is + // wrapped in strict mode code which doesn't define any globals. It's inside a + // function because try/catches deoptimize in certain engines. + + var cachedSetTimeout; + var cachedClearTimeout; + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + (function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + } ()) + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + process.title = 'browser'; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ''; // empty string to avoid regexp issues + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + process.prependListener = noop; + process.prependOnceListener = noop; + + process.listeners = function (name) { return [] } + + process.binding = function (name) { + throw new Error('process.binding is not supported'); + }; + + process.cwd = function () { return '/' }; + process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); + }; + process.umask = function() { return 0; }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports) { + + module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; + } + +/***/ }), +/* 11 */ +/***/ (function(module, exports) { + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } + + +/***/ }), +/* 12 */ +/***/ (function(module, exports) { + + 'use strict'; + + const word = '[a-fA-F\\d:]'; + const b = `(?:(?<=\\s|^)(?=${word})|(?<=${word})(?=\\s|$))`; + + const v4 = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}'; + + const v6seg = '[a-fA-F\\d]{1,4}'; + const v6 = ` + ( + (?:${v6seg}:){7}(?:${v6seg}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8 + (?:${v6seg}:){6}(?:${v4}|:${v6seg}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4 + (?:${v6seg}:){5}(?::${v4}|(:${v6seg}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4 + (?:${v6seg}:){4}(?:(:${v6seg}){0,1}:${v4}|(:${v6seg}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4 + (?:${v6seg}:){3}(?:(:${v6seg}){0,2}:${v4}|(:${v6seg}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4 + (?:${v6seg}:){2}(?:(:${v6seg}){0,3}:${v4}|(:${v6seg}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4 + (?:${v6seg}:){1}(?:(:${v6seg}){0,4}:${v4}|(:${v6seg}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4 + (?::((?::${v6seg}){0,5}:${v4}|(?::${v6seg}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4 + )(%[0-9a-zA-Z]{1,})? // %eth0 %1 + `.replace(/\s*\/\/.*$/gm, '').replace(/\n/g, '').trim(); + + const ip = opts => opts && opts.exact ? + new RegExp(`(?:^${v4}$)|(?:^${v6}$)`) : + new RegExp(`(?:${b}${v4}${b})|(?:${b}${v6}${b})`, 'g'); + + ip.v4 = opts => opts && opts.exact ? new RegExp(`^${v4}$`) : new RegExp(`${b}${v4}${b}`, 'g'); + ip.v6 = opts => opts && opts.exact ? new RegExp(`^${v6}$`) : new RegExp(`${b}${v6}${b}`, 'g'); + + module.exports = ip; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + + /*! + * Copyright (c) 2018, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + 'use strict'; + var psl = __webpack_require__(14); + + function getPublicSuffix(domain) { + return psl.get(domain); + } + + exports.getPublicSuffix = getPublicSuffix; + + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + + /*eslint no-var:0, prefer-arrow-callback: 0, object-shorthand: 0 */ + 'use strict'; + + + var Punycode = __webpack_require__(15); + + + var internals = {}; + + + // + // Read rules from file. + // + internals.rules = __webpack_require__(16).map(function (rule) { + + return { + rule: rule, + suffix: rule.replace(/^(\*\.|\!)/, ''), + punySuffix: -1, + wildcard: rule.charAt(0) === '*', + exception: rule.charAt(0) === '!' + }; + }); + + + // + // Check is given string ends with `suffix`. + // + internals.endsWith = function (str, suffix) { + + return str.indexOf(suffix, str.length - suffix.length) !== -1; + }; + + + // + // Find rule for a given domain. + // + internals.findRule = function (domain) { + + var punyDomain = Punycode.toASCII(domain); + return internals.rules.reduce(function (memo, rule) { + + if (rule.punySuffix === -1){ + rule.punySuffix = Punycode.toASCII(rule.suffix); + } + if (!internals.endsWith(punyDomain, '.' + rule.punySuffix) && punyDomain !== rule.punySuffix) { + return memo; + } + // This has been commented out as it never seems to run. This is because + // sub tlds always appear after their parents and we never find a shorter + // match. + //if (memo) { + // var memoSuffix = Punycode.toASCII(memo.suffix); + // if (memoSuffix.length >= punySuffix.length) { + // return memo; + // } + //} + return rule; + }, null); + }; + + + // + // Error codes and messages. + // + exports.errorCodes = { + DOMAIN_TOO_SHORT: 'Domain name too short.', + DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.', + LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.', + LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.', + LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.', + LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.', + LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.' + }; + + + // + // Validate domain name and throw if not valid. + // + // From wikipedia: + // + // Hostnames are composed of series of labels concatenated with dots, as are all + // domain names. Each label must be between 1 and 63 characters long, and the + // entire hostname (including the delimiting dots) has a maximum of 255 chars. + // + // Allowed chars: + // + // * `a-z` + // * `0-9` + // * `-` but not as a starting or ending character + // * `.` as a separator for the textual portions of a domain name + // + // * http://en.wikipedia.org/wiki/Domain_name + // * http://en.wikipedia.org/wiki/Hostname + // + internals.validate = function (input) { + + // Before we can validate we need to take care of IDNs with unicode chars. + var ascii = Punycode.toASCII(input); + + if (ascii.length < 1) { + return 'DOMAIN_TOO_SHORT'; + } + if (ascii.length > 255) { + return 'DOMAIN_TOO_LONG'; + } + + // Check each part's length and allowed chars. + var labels = ascii.split('.'); + var label; + + for (var i = 0; i < labels.length; ++i) { + label = labels[i]; + if (!label.length) { + return 'LABEL_TOO_SHORT'; + } + if (label.length > 63) { + return 'LABEL_TOO_LONG'; + } + if (label.charAt(0) === '-') { + return 'LABEL_STARTS_WITH_DASH'; + } + if (label.charAt(label.length - 1) === '-') { + return 'LABEL_ENDS_WITH_DASH'; + } + if (!/^[a-z0-9\-]+$/.test(label)) { + return 'LABEL_INVALID_CHARS'; + } + } + }; + + + // + // Public API + // + + + // + // Parse domain. + // + exports.parse = function (input) { + + if (typeof input !== 'string') { + throw new TypeError('Domain name must be a string.'); + } + + // Force domain to lowercase. + var domain = input.slice(0).toLowerCase(); + + // Handle FQDN. + // TODO: Simply remove trailing dot? + if (domain.charAt(domain.length - 1) === '.') { + domain = domain.slice(0, domain.length - 1); + } + + // Validate and sanitise input. + var error = internals.validate(domain); + if (error) { + return { + input: input, + error: { + message: exports.errorCodes[error], + code: error + } + }; + } + + var parsed = { + input: input, + tld: null, + sld: null, + domain: null, + subdomain: null, + listed: false + }; + + var domainParts = domain.split('.'); + + // Non-Internet TLD + if (domainParts[domainParts.length - 1] === 'local') { + return parsed; + } + + var handlePunycode = function () { + + if (!/xn--/.test(domain)) { + return parsed; + } + if (parsed.domain) { + parsed.domain = Punycode.toASCII(parsed.domain); + } + if (parsed.subdomain) { + parsed.subdomain = Punycode.toASCII(parsed.subdomain); + } + return parsed; + }; + + var rule = internals.findRule(domain); + + // Unlisted tld. + if (!rule) { + if (domainParts.length < 2) { + return parsed; + } + parsed.tld = domainParts.pop(); + parsed.sld = domainParts.pop(); + parsed.domain = [parsed.sld, parsed.tld].join('.'); + if (domainParts.length) { + parsed.subdomain = domainParts.pop(); + } + return handlePunycode(); + } + + // At this point we know the public suffix is listed. + parsed.listed = true; + + var tldParts = rule.suffix.split('.'); + var privateParts = domainParts.slice(0, domainParts.length - tldParts.length); + + if (rule.exception) { + privateParts.push(tldParts.shift()); + } + + parsed.tld = tldParts.join('.'); + + if (!privateParts.length) { + return handlePunycode(); + } + + if (rule.wildcard) { + tldParts.unshift(privateParts.pop()); + parsed.tld = tldParts.join('.'); + } + + if (!privateParts.length) { + return handlePunycode(); + } + + parsed.sld = privateParts.pop(); + parsed.domain = [parsed.sld, parsed.tld].join('.'); + + if (privateParts.length) { + parsed.subdomain = privateParts.join('.'); + } + + return handlePunycode(); + }; + + + // + // Get domain. + // + exports.get = function (domain) { + + if (!domain) { + return null; + } + return exports.parse(domain).domain || null; + }; + + + // + // Check whether domain belongs to a known public suffix. + // + exports.isValid = function (domain) { + + var parsed = exports.parse(domain); + return Boolean(parsed.domain && parsed.listed); + }; + + +/***/ }), +/* 15 */ +/***/ (function(module, exports) { + + 'use strict'; + + /** Highest positive signed 32-bit float value */ + const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + const base = 36; + const tMin = 1; + const tMax = 26; + const skew = 38; + const damp = 700; + const initialBias = 72; + const initialN = 128; // 0x80 + const delimiter = '-'; // '\x2D' + + /** Regular expressions */ + const regexPunycode = /^xn--/; + const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars + const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + + /** Error messages */ + const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }; + + /** Convenience shortcuts */ + const baseMinusTMin = base - tMin; + const floor = Math.floor; + const stringFromCharCode = String.fromCharCode; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + const result = []; + let length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + const parts = string.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + const labels = string.split('.'); + const encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + const ucs2encode = array => String.fromCodePoint(...array); + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + const basicToDigit = function(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; + }; + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + }; + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + }; + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + let oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); + }; + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + let inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + let basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + }; + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + }; + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + }; + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + module.exports = punycode; + + +/***/ }), +/* 16 */ +/***/ (function(module, exports) { + + module.exports = ["ac","com.ac","edu.ac","gov.ac","net.ac","mil.ac","org.ac","ad","nom.ad","ae","co.ae","net.ae","org.ae","sch.ae","ac.ae","gov.ae","mil.ae","aero","accident-investigation.aero","accident-prevention.aero","aerobatic.aero","aeroclub.aero","aerodrome.aero","agents.aero","aircraft.aero","airline.aero","airport.aero","air-surveillance.aero","airtraffic.aero","air-traffic-control.aero","ambulance.aero","amusement.aero","association.aero","author.aero","ballooning.aero","broker.aero","caa.aero","cargo.aero","catering.aero","certification.aero","championship.aero","charter.aero","civilaviation.aero","club.aero","conference.aero","consultant.aero","consulting.aero","control.aero","council.aero","crew.aero","design.aero","dgca.aero","educator.aero","emergency.aero","engine.aero","engineer.aero","entertainment.aero","equipment.aero","exchange.aero","express.aero","federation.aero","flight.aero","freight.aero","fuel.aero","gliding.aero","government.aero","groundhandling.aero","group.aero","hanggliding.aero","homebuilt.aero","insurance.aero","journal.aero","journalist.aero","leasing.aero","logistics.aero","magazine.aero","maintenance.aero","media.aero","microlight.aero","modelling.aero","navigation.aero","parachuting.aero","paragliding.aero","passenger-association.aero","pilot.aero","press.aero","production.aero","recreation.aero","repbody.aero","res.aero","research.aero","rotorcraft.aero","safety.aero","scientist.aero","services.aero","show.aero","skydiving.aero","software.aero","student.aero","trader.aero","trading.aero","trainer.aero","union.aero","workinggroup.aero","works.aero","af","gov.af","com.af","org.af","net.af","edu.af","ag","com.ag","org.ag","net.ag","co.ag","nom.ag","ai","off.ai","com.ai","net.ai","org.ai","al","com.al","edu.al","gov.al","mil.al","net.al","org.al","am","co.am","com.am","commune.am","net.am","org.am","ao","ed.ao","gv.ao","og.ao","co.ao","pb.ao","it.ao","aq","ar","com.ar","edu.ar","gob.ar","gov.ar","int.ar","mil.ar","musica.ar","net.ar","org.ar","tur.ar","arpa","e164.arpa","in-addr.arpa","ip6.arpa","iris.arpa","uri.arpa","urn.arpa","as","gov.as","asia","at","ac.at","co.at","gv.at","or.at","au","com.au","net.au","org.au","edu.au","gov.au","asn.au","id.au","info.au","conf.au","oz.au","act.au","nsw.au","nt.au","qld.au","sa.au","tas.au","vic.au","wa.au","act.edu.au","catholic.edu.au","nsw.edu.au","nt.edu.au","qld.edu.au","sa.edu.au","tas.edu.au","vic.edu.au","wa.edu.au","qld.gov.au","sa.gov.au","tas.gov.au","vic.gov.au","wa.gov.au","education.tas.edu.au","schools.nsw.edu.au","aw","com.aw","ax","az","com.az","net.az","int.az","gov.az","org.az","edu.az","info.az","pp.az","mil.az","name.az","pro.az","biz.az","ba","com.ba","edu.ba","gov.ba","mil.ba","net.ba","org.ba","bb","biz.bb","co.bb","com.bb","edu.bb","gov.bb","info.bb","net.bb","org.bb","store.bb","tv.bb","*.bd","be","ac.be","bf","gov.bf","bg","a.bg","b.bg","c.bg","d.bg","e.bg","f.bg","g.bg","h.bg","i.bg","j.bg","k.bg","l.bg","m.bg","n.bg","o.bg","p.bg","q.bg","r.bg","s.bg","t.bg","u.bg","v.bg","w.bg","x.bg","y.bg","z.bg","0.bg","1.bg","2.bg","3.bg","4.bg","5.bg","6.bg","7.bg","8.bg","9.bg","bh","com.bh","edu.bh","net.bh","org.bh","gov.bh","bi","co.bi","com.bi","edu.bi","or.bi","org.bi","biz","bj","asso.bj","barreau.bj","gouv.bj","bm","com.bm","edu.bm","gov.bm","net.bm","org.bm","bn","com.bn","edu.bn","gov.bn","net.bn","org.bn","bo","com.bo","edu.bo","gob.bo","int.bo","org.bo","net.bo","mil.bo","tv.bo","web.bo","academia.bo","agro.bo","arte.bo","blog.bo","bolivia.bo","ciencia.bo","cooperativa.bo","democracia.bo","deporte.bo","ecologia.bo","economia.bo","empresa.bo","indigena.bo","industria.bo","info.bo","medicina.bo","movimiento.bo","musica.bo","natural.bo","nombre.bo","noticias.bo","patria.bo","politica.bo","profesional.bo","plurinacional.bo","pueblo.bo","revista.bo","salud.bo","tecnologia.bo","tksat.bo","transporte.bo","wiki.bo","br","9guacu.br","abc.br","adm.br","adv.br","agr.br","aju.br","am.br","anani.br","aparecida.br","arq.br","art.br","ato.br","b.br","barueri.br","belem.br","bhz.br","bio.br","blog.br","bmd.br","boavista.br","bsb.br","campinagrande.br","campinas.br","caxias.br","cim.br","cng.br","cnt.br","com.br","contagem.br","coop.br","cri.br","cuiaba.br","curitiba.br","def.br","ecn.br","eco.br","edu.br","emp.br","eng.br","esp.br","etc.br","eti.br","far.br","feira.br","flog.br","floripa.br","fm.br","fnd.br","fortal.br","fot.br","foz.br","fst.br","g12.br","ggf.br","goiania.br","gov.br","ac.gov.br","al.gov.br","am.gov.br","ap.gov.br","ba.gov.br","ce.gov.br","df.gov.br","es.gov.br","go.gov.br","ma.gov.br","mg.gov.br","ms.gov.br","mt.gov.br","pa.gov.br","pb.gov.br","pe.gov.br","pi.gov.br","pr.gov.br","rj.gov.br","rn.gov.br","ro.gov.br","rr.gov.br","rs.gov.br","sc.gov.br","se.gov.br","sp.gov.br","to.gov.br","gru.br","imb.br","ind.br","inf.br","jab.br","jampa.br","jdf.br","joinville.br","jor.br","jus.br","leg.br","lel.br","londrina.br","macapa.br","maceio.br","manaus.br","maringa.br","mat.br","med.br","mil.br","morena.br","mp.br","mus.br","natal.br","net.br","niteroi.br","*.nom.br","not.br","ntr.br","odo.br","ong.br","org.br","osasco.br","palmas.br","poa.br","ppg.br","pro.br","psc.br","psi.br","pvh.br","qsl.br","radio.br","rec.br","recife.br","ribeirao.br","rio.br","riobranco.br","riopreto.br","salvador.br","sampa.br","santamaria.br","santoandre.br","saobernardo.br","saogonca.br","sjc.br","slg.br","slz.br","sorocaba.br","srv.br","taxi.br","tc.br","teo.br","the.br","tmp.br","trd.br","tur.br","tv.br","udi.br","vet.br","vix.br","vlog.br","wiki.br","zlg.br","bs","com.bs","net.bs","org.bs","edu.bs","gov.bs","bt","com.bt","edu.bt","gov.bt","net.bt","org.bt","bv","bw","co.bw","org.bw","by","gov.by","mil.by","com.by","of.by","bz","com.bz","net.bz","org.bz","edu.bz","gov.bz","ca","ab.ca","bc.ca","mb.ca","nb.ca","nf.ca","nl.ca","ns.ca","nt.ca","nu.ca","on.ca","pe.ca","qc.ca","sk.ca","yk.ca","gc.ca","cat","cc","cd","gov.cd","cf","cg","ch","ci","org.ci","or.ci","com.ci","co.ci","edu.ci","ed.ci","ac.ci","net.ci","go.ci","asso.ci","aéroport.ci","int.ci","presse.ci","md.ci","gouv.ci","*.ck","!www.ck","cl","gov.cl","gob.cl","co.cl","mil.cl","cm","co.cm","com.cm","gov.cm","net.cm","cn","ac.cn","com.cn","edu.cn","gov.cn","net.cn","org.cn","mil.cn","公司.cn","网络.cn","網絡.cn","ah.cn","bj.cn","cq.cn","fj.cn","gd.cn","gs.cn","gz.cn","gx.cn","ha.cn","hb.cn","he.cn","hi.cn","hl.cn","hn.cn","jl.cn","js.cn","jx.cn","ln.cn","nm.cn","nx.cn","qh.cn","sc.cn","sd.cn","sh.cn","sn.cn","sx.cn","tj.cn","xj.cn","xz.cn","yn.cn","zj.cn","hk.cn","mo.cn","tw.cn","co","arts.co","com.co","edu.co","firm.co","gov.co","info.co","int.co","mil.co","net.co","nom.co","org.co","rec.co","web.co","com","coop","cr","ac.cr","co.cr","ed.cr","fi.cr","go.cr","or.cr","sa.cr","cu","com.cu","edu.cu","org.cu","net.cu","gov.cu","inf.cu","cv","cw","com.cw","edu.cw","net.cw","org.cw","cx","gov.cx","cy","ac.cy","biz.cy","com.cy","ekloges.cy","gov.cy","ltd.cy","name.cy","net.cy","org.cy","parliament.cy","press.cy","pro.cy","tm.cy","cz","de","dj","dk","dm","com.dm","net.dm","org.dm","edu.dm","gov.dm","do","art.do","com.do","edu.do","gob.do","gov.do","mil.do","net.do","org.do","sld.do","web.do","dz","com.dz","org.dz","net.dz","gov.dz","edu.dz","asso.dz","pol.dz","art.dz","ec","com.ec","info.ec","net.ec","fin.ec","k12.ec","med.ec","pro.ec","org.ec","edu.ec","gov.ec","gob.ec","mil.ec","edu","ee","edu.ee","gov.ee","riik.ee","lib.ee","med.ee","com.ee","pri.ee","aip.ee","org.ee","fie.ee","eg","com.eg","edu.eg","eun.eg","gov.eg","mil.eg","name.eg","net.eg","org.eg","sci.eg","*.er","es","com.es","nom.es","org.es","gob.es","edu.es","et","com.et","gov.et","org.et","edu.et","biz.et","name.et","info.et","net.et","eu","fi","aland.fi","*.fj","*.fk","fm","fo","fr","asso.fr","com.fr","gouv.fr","nom.fr","prd.fr","tm.fr","aeroport.fr","avocat.fr","avoues.fr","cci.fr","chambagri.fr","chirurgiens-dentistes.fr","experts-comptables.fr","geometre-expert.fr","greta.fr","huissier-justice.fr","medecin.fr","notaires.fr","pharmacien.fr","port.fr","veterinaire.fr","ga","gb","gd","ge","com.ge","edu.ge","gov.ge","org.ge","mil.ge","net.ge","pvt.ge","gf","gg","co.gg","net.gg","org.gg","gh","com.gh","edu.gh","gov.gh","org.gh","mil.gh","gi","com.gi","ltd.gi","gov.gi","mod.gi","edu.gi","org.gi","gl","co.gl","com.gl","edu.gl","net.gl","org.gl","gm","gn","ac.gn","com.gn","edu.gn","gov.gn","org.gn","net.gn","gov","gp","com.gp","net.gp","mobi.gp","edu.gp","org.gp","asso.gp","gq","gr","com.gr","edu.gr","net.gr","org.gr","gov.gr","gs","gt","com.gt","edu.gt","gob.gt","ind.gt","mil.gt","net.gt","org.gt","gu","com.gu","edu.gu","gov.gu","guam.gu","info.gu","net.gu","org.gu","web.gu","gw","gy","co.gy","com.gy","edu.gy","gov.gy","net.gy","org.gy","hk","com.hk","edu.hk","gov.hk","idv.hk","net.hk","org.hk","公司.hk","教育.hk","敎育.hk","政府.hk","個人.hk","个人.hk","箇人.hk","網络.hk","网络.hk","组織.hk","網絡.hk","网絡.hk","组织.hk","組織.hk","組织.hk","hm","hn","com.hn","edu.hn","org.hn","net.hn","mil.hn","gob.hn","hr","iz.hr","from.hr","name.hr","com.hr","ht","com.ht","shop.ht","firm.ht","info.ht","adult.ht","net.ht","pro.ht","org.ht","med.ht","art.ht","coop.ht","pol.ht","asso.ht","edu.ht","rel.ht","gouv.ht","perso.ht","hu","co.hu","info.hu","org.hu","priv.hu","sport.hu","tm.hu","2000.hu","agrar.hu","bolt.hu","casino.hu","city.hu","erotica.hu","erotika.hu","film.hu","forum.hu","games.hu","hotel.hu","ingatlan.hu","jogasz.hu","konyvelo.hu","lakas.hu","media.hu","news.hu","reklam.hu","sex.hu","shop.hu","suli.hu","szex.hu","tozsde.hu","utazas.hu","video.hu","id","ac.id","biz.id","co.id","desa.id","go.id","mil.id","my.id","net.id","or.id","ponpes.id","sch.id","web.id","ie","gov.ie","il","ac.il","co.il","gov.il","idf.il","k12.il","muni.il","net.il","org.il","im","ac.im","co.im","com.im","ltd.co.im","net.im","org.im","plc.co.im","tt.im","tv.im","in","co.in","firm.in","net.in","org.in","gen.in","ind.in","nic.in","ac.in","edu.in","res.in","gov.in","mil.in","info","int","eu.int","io","com.io","iq","gov.iq","edu.iq","mil.iq","com.iq","org.iq","net.iq","ir","ac.ir","co.ir","gov.ir","id.ir","net.ir","org.ir","sch.ir","ایران.ir","ايران.ir","is","net.is","com.is","edu.is","gov.is","org.is","int.is","it","gov.it","edu.it","abr.it","abruzzo.it","aosta-valley.it","aostavalley.it","bas.it","basilicata.it","cal.it","calabria.it","cam.it","campania.it","emilia-romagna.it","emiliaromagna.it","emr.it","friuli-v-giulia.it","friuli-ve-giulia.it","friuli-vegiulia.it","friuli-venezia-giulia.it","friuli-veneziagiulia.it","friuli-vgiulia.it","friuliv-giulia.it","friulive-giulia.it","friulivegiulia.it","friulivenezia-giulia.it","friuliveneziagiulia.it","friulivgiulia.it","fvg.it","laz.it","lazio.it","lig.it","liguria.it","lom.it","lombardia.it","lombardy.it","lucania.it","mar.it","marche.it","mol.it","molise.it","piedmont.it","piemonte.it","pmn.it","pug.it","puglia.it","sar.it","sardegna.it","sardinia.it","sic.it","sicilia.it","sicily.it","taa.it","tos.it","toscana.it","trentin-sud-tirol.it","trentin-süd-tirol.it","trentin-sudtirol.it","trentin-südtirol.it","trentin-sued-tirol.it","trentin-suedtirol.it","trentino-a-adige.it","trentino-aadige.it","trentino-alto-adige.it","trentino-altoadige.it","trentino-s-tirol.it","trentino-stirol.it","trentino-sud-tirol.it","trentino-süd-tirol.it","trentino-sudtirol.it","trentino-südtirol.it","trentino-sued-tirol.it","trentino-suedtirol.it","trentino.it","trentinoa-adige.it","trentinoaadige.it","trentinoalto-adige.it","trentinoaltoadige.it","trentinos-tirol.it","trentinostirol.it","trentinosud-tirol.it","trentinosüd-tirol.it","trentinosudtirol.it","trentinosüdtirol.it","trentinosued-tirol.it","trentinosuedtirol.it","trentinsud-tirol.it","trentinsüd-tirol.it","trentinsudtirol.it","trentinsüdtirol.it","trentinsued-tirol.it","trentinsuedtirol.it","tuscany.it","umb.it","umbria.it","val-d-aosta.it","val-daosta.it","vald-aosta.it","valdaosta.it","valle-aosta.it","valle-d-aosta.it","valle-daosta.it","valleaosta.it","valled-aosta.it","valledaosta.it","vallee-aoste.it","vallée-aoste.it","vallee-d-aoste.it","vallée-d-aoste.it","valleeaoste.it","valléeaoste.it","valleedaoste.it","valléedaoste.it","vao.it","vda.it","ven.it","veneto.it","ag.it","agrigento.it","al.it","alessandria.it","alto-adige.it","altoadige.it","an.it","ancona.it","andria-barletta-trani.it","andria-trani-barletta.it","andriabarlettatrani.it","andriatranibarletta.it","ao.it","aosta.it","aoste.it","ap.it","aq.it","aquila.it","ar.it","arezzo.it","ascoli-piceno.it","ascolipiceno.it","asti.it","at.it","av.it","avellino.it","ba.it","balsan-sudtirol.it","balsan-südtirol.it","balsan-suedtirol.it","balsan.it","bari.it","barletta-trani-andria.it","barlettatraniandria.it","belluno.it","benevento.it","bergamo.it","bg.it","bi.it","biella.it","bl.it","bn.it","bo.it","bologna.it","bolzano-altoadige.it","bolzano.it","bozen-sudtirol.it","bozen-südtirol.it","bozen-suedtirol.it","bozen.it","br.it","brescia.it","brindisi.it","bs.it","bt.it","bulsan-sudtirol.it","bulsan-südtirol.it","bulsan-suedtirol.it","bulsan.it","bz.it","ca.it","cagliari.it","caltanissetta.it","campidano-medio.it","campidanomedio.it","campobasso.it","carbonia-iglesias.it","carboniaiglesias.it","carrara-massa.it","carraramassa.it","caserta.it","catania.it","catanzaro.it","cb.it","ce.it","cesena-forli.it","cesena-forlì.it","cesenaforli.it","cesenaforlì.it","ch.it","chieti.it","ci.it","cl.it","cn.it","co.it","como.it","cosenza.it","cr.it","cremona.it","crotone.it","cs.it","ct.it","cuneo.it","cz.it","dell-ogliastra.it","dellogliastra.it","en.it","enna.it","fc.it","fe.it","fermo.it","ferrara.it","fg.it","fi.it","firenze.it","florence.it","fm.it","foggia.it","forli-cesena.it","forlì-cesena.it","forlicesena.it","forlìcesena.it","fr.it","frosinone.it","ge.it","genoa.it","genova.it","go.it","gorizia.it","gr.it","grosseto.it","iglesias-carbonia.it","iglesiascarbonia.it","im.it","imperia.it","is.it","isernia.it","kr.it","la-spezia.it","laquila.it","laspezia.it","latina.it","lc.it","le.it","lecce.it","lecco.it","li.it","livorno.it","lo.it","lodi.it","lt.it","lu.it","lucca.it","macerata.it","mantova.it","massa-carrara.it","massacarrara.it","matera.it","mb.it","mc.it","me.it","medio-campidano.it","mediocampidano.it","messina.it","mi.it","milan.it","milano.it","mn.it","mo.it","modena.it","monza-brianza.it","monza-e-della-brianza.it","monza.it","monzabrianza.it","monzaebrianza.it","monzaedellabrianza.it","ms.it","mt.it","na.it","naples.it","napoli.it","no.it","novara.it","nu.it","nuoro.it","og.it","ogliastra.it","olbia-tempio.it","olbiatempio.it","or.it","oristano.it","ot.it","pa.it","padova.it","padua.it","palermo.it","parma.it","pavia.it","pc.it","pd.it","pe.it","perugia.it","pesaro-urbino.it","pesarourbino.it","pescara.it","pg.it","pi.it","piacenza.it","pisa.it","pistoia.it","pn.it","po.it","pordenone.it","potenza.it","pr.it","prato.it","pt.it","pu.it","pv.it","pz.it","ra.it","ragusa.it","ravenna.it","rc.it","re.it","reggio-calabria.it","reggio-emilia.it","reggiocalabria.it","reggioemilia.it","rg.it","ri.it","rieti.it","rimini.it","rm.it","rn.it","ro.it","roma.it","rome.it","rovigo.it","sa.it","salerno.it","sassari.it","savona.it","si.it","siena.it","siracusa.it","so.it","sondrio.it","sp.it","sr.it","ss.it","suedtirol.it","südtirol.it","sv.it","ta.it","taranto.it","te.it","tempio-olbia.it","tempioolbia.it","teramo.it","terni.it","tn.it","to.it","torino.it","tp.it","tr.it","trani-andria-barletta.it","trani-barletta-andria.it","traniandriabarletta.it","tranibarlettaandria.it","trapani.it","trento.it","treviso.it","trieste.it","ts.it","turin.it","tv.it","ud.it","udine.it","urbino-pesaro.it","urbinopesaro.it","va.it","varese.it","vb.it","vc.it","ve.it","venezia.it","venice.it","verbania.it","vercelli.it","verona.it","vi.it","vibo-valentia.it","vibovalentia.it","vicenza.it","viterbo.it","vr.it","vs.it","vt.it","vv.it","je","co.je","net.je","org.je","*.jm","jo","com.jo","org.jo","net.jo","edu.jo","sch.jo","gov.jo","mil.jo","name.jo","jobs","jp","ac.jp","ad.jp","co.jp","ed.jp","go.jp","gr.jp","lg.jp","ne.jp","or.jp","aichi.jp","akita.jp","aomori.jp","chiba.jp","ehime.jp","fukui.jp","fukuoka.jp","fukushima.jp","gifu.jp","gunma.jp","hiroshima.jp","hokkaido.jp","hyogo.jp","ibaraki.jp","ishikawa.jp","iwate.jp","kagawa.jp","kagoshima.jp","kanagawa.jp","kochi.jp","kumamoto.jp","kyoto.jp","mie.jp","miyagi.jp","miyazaki.jp","nagano.jp","nagasaki.jp","nara.jp","niigata.jp","oita.jp","okayama.jp","okinawa.jp","osaka.jp","saga.jp","saitama.jp","shiga.jp","shimane.jp","shizuoka.jp","tochigi.jp","tokushima.jp","tokyo.jp","tottori.jp","toyama.jp","wakayama.jp","yamagata.jp","yamaguchi.jp","yamanashi.jp","栃木.jp","愛知.jp","愛媛.jp","兵庫.jp","熊本.jp","茨城.jp","北海道.jp","千葉.jp","和歌山.jp","長崎.jp","長野.jp","新潟.jp","青森.jp","静岡.jp","東京.jp","石川.jp","埼玉.jp","三重.jp","京都.jp","佐賀.jp","大分.jp","大阪.jp","奈良.jp","宮城.jp","宮崎.jp","富山.jp","山口.jp","山形.jp","山梨.jp","岩手.jp","岐阜.jp","岡山.jp","島根.jp","広島.jp","徳島.jp","沖縄.jp","滋賀.jp","神奈川.jp","福井.jp","福岡.jp","福島.jp","秋田.jp","群馬.jp","香川.jp","高知.jp","鳥取.jp","鹿児島.jp","*.kawasaki.jp","*.kitakyushu.jp","*.kobe.jp","*.nagoya.jp","*.sapporo.jp","*.sendai.jp","*.yokohama.jp","!city.kawasaki.jp","!city.kitakyushu.jp","!city.kobe.jp","!city.nagoya.jp","!city.sapporo.jp","!city.sendai.jp","!city.yokohama.jp","aisai.aichi.jp","ama.aichi.jp","anjo.aichi.jp","asuke.aichi.jp","chiryu.aichi.jp","chita.aichi.jp","fuso.aichi.jp","gamagori.aichi.jp","handa.aichi.jp","hazu.aichi.jp","hekinan.aichi.jp","higashiura.aichi.jp","ichinomiya.aichi.jp","inazawa.aichi.jp","inuyama.aichi.jp","isshiki.aichi.jp","iwakura.aichi.jp","kanie.aichi.jp","kariya.aichi.jp","kasugai.aichi.jp","kira.aichi.jp","kiyosu.aichi.jp","komaki.aichi.jp","konan.aichi.jp","kota.aichi.jp","mihama.aichi.jp","miyoshi.aichi.jp","nishio.aichi.jp","nisshin.aichi.jp","obu.aichi.jp","oguchi.aichi.jp","oharu.aichi.jp","okazaki.aichi.jp","owariasahi.aichi.jp","seto.aichi.jp","shikatsu.aichi.jp","shinshiro.aichi.jp","shitara.aichi.jp","tahara.aichi.jp","takahama.aichi.jp","tobishima.aichi.jp","toei.aichi.jp","togo.aichi.jp","tokai.aichi.jp","tokoname.aichi.jp","toyoake.aichi.jp","toyohashi.aichi.jp","toyokawa.aichi.jp","toyone.aichi.jp","toyota.aichi.jp","tsushima.aichi.jp","yatomi.aichi.jp","akita.akita.jp","daisen.akita.jp","fujisato.akita.jp","gojome.akita.jp","hachirogata.akita.jp","happou.akita.jp","higashinaruse.akita.jp","honjo.akita.jp","honjyo.akita.jp","ikawa.akita.jp","kamikoani.akita.jp","kamioka.akita.jp","katagami.akita.jp","kazuno.akita.jp","kitaakita.akita.jp","kosaka.akita.jp","kyowa.akita.jp","misato.akita.jp","mitane.akita.jp","moriyoshi.akita.jp","nikaho.akita.jp","noshiro.akita.jp","odate.akita.jp","oga.akita.jp","ogata.akita.jp","semboku.akita.jp","yokote.akita.jp","yurihonjo.akita.jp","aomori.aomori.jp","gonohe.aomori.jp","hachinohe.aomori.jp","hashikami.aomori.jp","hiranai.aomori.jp","hirosaki.aomori.jp","itayanagi.aomori.jp","kuroishi.aomori.jp","misawa.aomori.jp","mutsu.aomori.jp","nakadomari.aomori.jp","noheji.aomori.jp","oirase.aomori.jp","owani.aomori.jp","rokunohe.aomori.jp","sannohe.aomori.jp","shichinohe.aomori.jp","shingo.aomori.jp","takko.aomori.jp","towada.aomori.jp","tsugaru.aomori.jp","tsuruta.aomori.jp","abiko.chiba.jp","asahi.chiba.jp","chonan.chiba.jp","chosei.chiba.jp","choshi.chiba.jp","chuo.chiba.jp","funabashi.chiba.jp","futtsu.chiba.jp","hanamigawa.chiba.jp","ichihara.chiba.jp","ichikawa.chiba.jp","ichinomiya.chiba.jp","inzai.chiba.jp","isumi.chiba.jp","kamagaya.chiba.jp","kamogawa.chiba.jp","kashiwa.chiba.jp","katori.chiba.jp","katsuura.chiba.jp","kimitsu.chiba.jp","kisarazu.chiba.jp","kozaki.chiba.jp","kujukuri.chiba.jp","kyonan.chiba.jp","matsudo.chiba.jp","midori.chiba.jp","mihama.chiba.jp","minamiboso.chiba.jp","mobara.chiba.jp","mutsuzawa.chiba.jp","nagara.chiba.jp","nagareyama.chiba.jp","narashino.chiba.jp","narita.chiba.jp","noda.chiba.jp","oamishirasato.chiba.jp","omigawa.chiba.jp","onjuku.chiba.jp","otaki.chiba.jp","sakae.chiba.jp","sakura.chiba.jp","shimofusa.chiba.jp","shirako.chiba.jp","shiroi.chiba.jp","shisui.chiba.jp","sodegaura.chiba.jp","sosa.chiba.jp","tako.chiba.jp","tateyama.chiba.jp","togane.chiba.jp","tohnosho.chiba.jp","tomisato.chiba.jp","urayasu.chiba.jp","yachimata.chiba.jp","yachiyo.chiba.jp","yokaichiba.chiba.jp","yokoshibahikari.chiba.jp","yotsukaido.chiba.jp","ainan.ehime.jp","honai.ehime.jp","ikata.ehime.jp","imabari.ehime.jp","iyo.ehime.jp","kamijima.ehime.jp","kihoku.ehime.jp","kumakogen.ehime.jp","masaki.ehime.jp","matsuno.ehime.jp","matsuyama.ehime.jp","namikata.ehime.jp","niihama.ehime.jp","ozu.ehime.jp","saijo.ehime.jp","seiyo.ehime.jp","shikokuchuo.ehime.jp","tobe.ehime.jp","toon.ehime.jp","uchiko.ehime.jp","uwajima.ehime.jp","yawatahama.ehime.jp","echizen.fukui.jp","eiheiji.fukui.jp","fukui.fukui.jp","ikeda.fukui.jp","katsuyama.fukui.jp","mihama.fukui.jp","minamiechizen.fukui.jp","obama.fukui.jp","ohi.fukui.jp","ono.fukui.jp","sabae.fukui.jp","sakai.fukui.jp","takahama.fukui.jp","tsuruga.fukui.jp","wakasa.fukui.jp","ashiya.fukuoka.jp","buzen.fukuoka.jp","chikugo.fukuoka.jp","chikuho.fukuoka.jp","chikujo.fukuoka.jp","chikushino.fukuoka.jp","chikuzen.fukuoka.jp","chuo.fukuoka.jp","dazaifu.fukuoka.jp","fukuchi.fukuoka.jp","hakata.fukuoka.jp","higashi.fukuoka.jp","hirokawa.fukuoka.jp","hisayama.fukuoka.jp","iizuka.fukuoka.jp","inatsuki.fukuoka.jp","kaho.fukuoka.jp","kasuga.fukuoka.jp","kasuya.fukuoka.jp","kawara.fukuoka.jp","keisen.fukuoka.jp","koga.fukuoka.jp","kurate.fukuoka.jp","kurogi.fukuoka.jp","kurume.fukuoka.jp","minami.fukuoka.jp","miyako.fukuoka.jp","miyama.fukuoka.jp","miyawaka.fukuoka.jp","mizumaki.fukuoka.jp","munakata.fukuoka.jp","nakagawa.fukuoka.jp","nakama.fukuoka.jp","nishi.fukuoka.jp","nogata.fukuoka.jp","ogori.fukuoka.jp","okagaki.fukuoka.jp","okawa.fukuoka.jp","oki.fukuoka.jp","omuta.fukuoka.jp","onga.fukuoka.jp","onojo.fukuoka.jp","oto.fukuoka.jp","saigawa.fukuoka.jp","sasaguri.fukuoka.jp","shingu.fukuoka.jp","shinyoshitomi.fukuoka.jp","shonai.fukuoka.jp","soeda.fukuoka.jp","sue.fukuoka.jp","tachiarai.fukuoka.jp","tagawa.fukuoka.jp","takata.fukuoka.jp","toho.fukuoka.jp","toyotsu.fukuoka.jp","tsuiki.fukuoka.jp","ukiha.fukuoka.jp","umi.fukuoka.jp","usui.fukuoka.jp","yamada.fukuoka.jp","yame.fukuoka.jp","yanagawa.fukuoka.jp","yukuhashi.fukuoka.jp","aizubange.fukushima.jp","aizumisato.fukushima.jp","aizuwakamatsu.fukushima.jp","asakawa.fukushima.jp","bandai.fukushima.jp","date.fukushima.jp","fukushima.fukushima.jp","furudono.fukushima.jp","futaba.fukushima.jp","hanawa.fukushima.jp","higashi.fukushima.jp","hirata.fukushima.jp","hirono.fukushima.jp","iitate.fukushima.jp","inawashiro.fukushima.jp","ishikawa.fukushima.jp","iwaki.fukushima.jp","izumizaki.fukushima.jp","kagamiishi.fukushima.jp","kaneyama.fukushima.jp","kawamata.fukushima.jp","kitakata.fukushima.jp","kitashiobara.fukushima.jp","koori.fukushima.jp","koriyama.fukushima.jp","kunimi.fukushima.jp","miharu.fukushima.jp","mishima.fukushima.jp","namie.fukushima.jp","nango.fukushima.jp","nishiaizu.fukushima.jp","nishigo.fukushima.jp","okuma.fukushima.jp","omotego.fukushima.jp","ono.fukushima.jp","otama.fukushima.jp","samegawa.fukushima.jp","shimogo.fukushima.jp","shirakawa.fukushima.jp","showa.fukushima.jp","soma.fukushima.jp","sukagawa.fukushima.jp","taishin.fukushima.jp","tamakawa.fukushima.jp","tanagura.fukushima.jp","tenei.fukushima.jp","yabuki.fukushima.jp","yamato.fukushima.jp","yamatsuri.fukushima.jp","yanaizu.fukushima.jp","yugawa.fukushima.jp","anpachi.gifu.jp","ena.gifu.jp","gifu.gifu.jp","ginan.gifu.jp","godo.gifu.jp","gujo.gifu.jp","hashima.gifu.jp","hichiso.gifu.jp","hida.gifu.jp","higashishirakawa.gifu.jp","ibigawa.gifu.jp","ikeda.gifu.jp","kakamigahara.gifu.jp","kani.gifu.jp","kasahara.gifu.jp","kasamatsu.gifu.jp","kawaue.gifu.jp","kitagata.gifu.jp","mino.gifu.jp","minokamo.gifu.jp","mitake.gifu.jp","mizunami.gifu.jp","motosu.gifu.jp","nakatsugawa.gifu.jp","ogaki.gifu.jp","sakahogi.gifu.jp","seki.gifu.jp","sekigahara.gifu.jp","shirakawa.gifu.jp","tajimi.gifu.jp","takayama.gifu.jp","tarui.gifu.jp","toki.gifu.jp","tomika.gifu.jp","wanouchi.gifu.jp","yamagata.gifu.jp","yaotsu.gifu.jp","yoro.gifu.jp","annaka.gunma.jp","chiyoda.gunma.jp","fujioka.gunma.jp","higashiagatsuma.gunma.jp","isesaki.gunma.jp","itakura.gunma.jp","kanna.gunma.jp","kanra.gunma.jp","katashina.gunma.jp","kawaba.gunma.jp","kiryu.gunma.jp","kusatsu.gunma.jp","maebashi.gunma.jp","meiwa.gunma.jp","midori.gunma.jp","minakami.gunma.jp","naganohara.gunma.jp","nakanojo.gunma.jp","nanmoku.gunma.jp","numata.gunma.jp","oizumi.gunma.jp","ora.gunma.jp","ota.gunma.jp","shibukawa.gunma.jp","shimonita.gunma.jp","shinto.gunma.jp","showa.gunma.jp","takasaki.gunma.jp","takayama.gunma.jp","tamamura.gunma.jp","tatebayashi.gunma.jp","tomioka.gunma.jp","tsukiyono.gunma.jp","tsumagoi.gunma.jp","ueno.gunma.jp","yoshioka.gunma.jp","asaminami.hiroshima.jp","daiwa.hiroshima.jp","etajima.hiroshima.jp","fuchu.hiroshima.jp","fukuyama.hiroshima.jp","hatsukaichi.hiroshima.jp","higashihiroshima.hiroshima.jp","hongo.hiroshima.jp","jinsekikogen.hiroshima.jp","kaita.hiroshima.jp","kui.hiroshima.jp","kumano.hiroshima.jp","kure.hiroshima.jp","mihara.hiroshima.jp","miyoshi.hiroshima.jp","naka.hiroshima.jp","onomichi.hiroshima.jp","osakikamijima.hiroshima.jp","otake.hiroshima.jp","saka.hiroshima.jp","sera.hiroshima.jp","seranishi.hiroshima.jp","shinichi.hiroshima.jp","shobara.hiroshima.jp","takehara.hiroshima.jp","abashiri.hokkaido.jp","abira.hokkaido.jp","aibetsu.hokkaido.jp","akabira.hokkaido.jp","akkeshi.hokkaido.jp","asahikawa.hokkaido.jp","ashibetsu.hokkaido.jp","ashoro.hokkaido.jp","assabu.hokkaido.jp","atsuma.hokkaido.jp","bibai.hokkaido.jp","biei.hokkaido.jp","bifuka.hokkaido.jp","bihoro.hokkaido.jp","biratori.hokkaido.jp","chippubetsu.hokkaido.jp","chitose.hokkaido.jp","date.hokkaido.jp","ebetsu.hokkaido.jp","embetsu.hokkaido.jp","eniwa.hokkaido.jp","erimo.hokkaido.jp","esan.hokkaido.jp","esashi.hokkaido.jp","fukagawa.hokkaido.jp","fukushima.hokkaido.jp","furano.hokkaido.jp","furubira.hokkaido.jp","haboro.hokkaido.jp","hakodate.hokkaido.jp","hamatonbetsu.hokkaido.jp","hidaka.hokkaido.jp","higashikagura.hokkaido.jp","higashikawa.hokkaido.jp","hiroo.hokkaido.jp","hokuryu.hokkaido.jp","hokuto.hokkaido.jp","honbetsu.hokkaido.jp","horokanai.hokkaido.jp","horonobe.hokkaido.jp","ikeda.hokkaido.jp","imakane.hokkaido.jp","ishikari.hokkaido.jp","iwamizawa.hokkaido.jp","iwanai.hokkaido.jp","kamifurano.hokkaido.jp","kamikawa.hokkaido.jp","kamishihoro.hokkaido.jp","kamisunagawa.hokkaido.jp","kamoenai.hokkaido.jp","kayabe.hokkaido.jp","kembuchi.hokkaido.jp","kikonai.hokkaido.jp","kimobetsu.hokkaido.jp","kitahiroshima.hokkaido.jp","kitami.hokkaido.jp","kiyosato.hokkaido.jp","koshimizu.hokkaido.jp","kunneppu.hokkaido.jp","kuriyama.hokkaido.jp","kuromatsunai.hokkaido.jp","kushiro.hokkaido.jp","kutchan.hokkaido.jp","kyowa.hokkaido.jp","mashike.hokkaido.jp","matsumae.hokkaido.jp","mikasa.hokkaido.jp","minamifurano.hokkaido.jp","mombetsu.hokkaido.jp","moseushi.hokkaido.jp","mukawa.hokkaido.jp","muroran.hokkaido.jp","naie.hokkaido.jp","nakagawa.hokkaido.jp","nakasatsunai.hokkaido.jp","nakatombetsu.hokkaido.jp","nanae.hokkaido.jp","nanporo.hokkaido.jp","nayoro.hokkaido.jp","nemuro.hokkaido.jp","niikappu.hokkaido.jp","niki.hokkaido.jp","nishiokoppe.hokkaido.jp","noboribetsu.hokkaido.jp","numata.hokkaido.jp","obihiro.hokkaido.jp","obira.hokkaido.jp","oketo.hokkaido.jp","okoppe.hokkaido.jp","otaru.hokkaido.jp","otobe.hokkaido.jp","otofuke.hokkaido.jp","otoineppu.hokkaido.jp","oumu.hokkaido.jp","ozora.hokkaido.jp","pippu.hokkaido.jp","rankoshi.hokkaido.jp","rebun.hokkaido.jp","rikubetsu.hokkaido.jp","rishiri.hokkaido.jp","rishirifuji.hokkaido.jp","saroma.hokkaido.jp","sarufutsu.hokkaido.jp","shakotan.hokkaido.jp","shari.hokkaido.jp","shibecha.hokkaido.jp","shibetsu.hokkaido.jp","shikabe.hokkaido.jp","shikaoi.hokkaido.jp","shimamaki.hokkaido.jp","shimizu.hokkaido.jp","shimokawa.hokkaido.jp","shinshinotsu.hokkaido.jp","shintoku.hokkaido.jp","shiranuka.hokkaido.jp","shiraoi.hokkaido.jp","shiriuchi.hokkaido.jp","sobetsu.hokkaido.jp","sunagawa.hokkaido.jp","taiki.hokkaido.jp","takasu.hokkaido.jp","takikawa.hokkaido.jp","takinoue.hokkaido.jp","teshikaga.hokkaido.jp","tobetsu.hokkaido.jp","tohma.hokkaido.jp","tomakomai.hokkaido.jp","tomari.hokkaido.jp","toya.hokkaido.jp","toyako.hokkaido.jp","toyotomi.hokkaido.jp","toyoura.hokkaido.jp","tsubetsu.hokkaido.jp","tsukigata.hokkaido.jp","urakawa.hokkaido.jp","urausu.hokkaido.jp","uryu.hokkaido.jp","utashinai.hokkaido.jp","wakkanai.hokkaido.jp","wassamu.hokkaido.jp","yakumo.hokkaido.jp","yoichi.hokkaido.jp","aioi.hyogo.jp","akashi.hyogo.jp","ako.hyogo.jp","amagasaki.hyogo.jp","aogaki.hyogo.jp","asago.hyogo.jp","ashiya.hyogo.jp","awaji.hyogo.jp","fukusaki.hyogo.jp","goshiki.hyogo.jp","harima.hyogo.jp","himeji.hyogo.jp","ichikawa.hyogo.jp","inagawa.hyogo.jp","itami.hyogo.jp","kakogawa.hyogo.jp","kamigori.hyogo.jp","kamikawa.hyogo.jp","kasai.hyogo.jp","kasuga.hyogo.jp","kawanishi.hyogo.jp","miki.hyogo.jp","minamiawaji.hyogo.jp","nishinomiya.hyogo.jp","nishiwaki.hyogo.jp","ono.hyogo.jp","sanda.hyogo.jp","sannan.hyogo.jp","sasayama.hyogo.jp","sayo.hyogo.jp","shingu.hyogo.jp","shinonsen.hyogo.jp","shiso.hyogo.jp","sumoto.hyogo.jp","taishi.hyogo.jp","taka.hyogo.jp","takarazuka.hyogo.jp","takasago.hyogo.jp","takino.hyogo.jp","tamba.hyogo.jp","tatsuno.hyogo.jp","toyooka.hyogo.jp","yabu.hyogo.jp","yashiro.hyogo.jp","yoka.hyogo.jp","yokawa.hyogo.jp","ami.ibaraki.jp","asahi.ibaraki.jp","bando.ibaraki.jp","chikusei.ibaraki.jp","daigo.ibaraki.jp","fujishiro.ibaraki.jp","hitachi.ibaraki.jp","hitachinaka.ibaraki.jp","hitachiomiya.ibaraki.jp","hitachiota.ibaraki.jp","ibaraki.ibaraki.jp","ina.ibaraki.jp","inashiki.ibaraki.jp","itako.ibaraki.jp","iwama.ibaraki.jp","joso.ibaraki.jp","kamisu.ibaraki.jp","kasama.ibaraki.jp","kashima.ibaraki.jp","kasumigaura.ibaraki.jp","koga.ibaraki.jp","miho.ibaraki.jp","mito.ibaraki.jp","moriya.ibaraki.jp","naka.ibaraki.jp","namegata.ibaraki.jp","oarai.ibaraki.jp","ogawa.ibaraki.jp","omitama.ibaraki.jp","ryugasaki.ibaraki.jp","sakai.ibaraki.jp","sakuragawa.ibaraki.jp","shimodate.ibaraki.jp","shimotsuma.ibaraki.jp","shirosato.ibaraki.jp","sowa.ibaraki.jp","suifu.ibaraki.jp","takahagi.ibaraki.jp","tamatsukuri.ibaraki.jp","tokai.ibaraki.jp","tomobe.ibaraki.jp","tone.ibaraki.jp","toride.ibaraki.jp","tsuchiura.ibaraki.jp","tsukuba.ibaraki.jp","uchihara.ibaraki.jp","ushiku.ibaraki.jp","yachiyo.ibaraki.jp","yamagata.ibaraki.jp","yawara.ibaraki.jp","yuki.ibaraki.jp","anamizu.ishikawa.jp","hakui.ishikawa.jp","hakusan.ishikawa.jp","kaga.ishikawa.jp","kahoku.ishikawa.jp","kanazawa.ishikawa.jp","kawakita.ishikawa.jp","komatsu.ishikawa.jp","nakanoto.ishikawa.jp","nanao.ishikawa.jp","nomi.ishikawa.jp","nonoichi.ishikawa.jp","noto.ishikawa.jp","shika.ishikawa.jp","suzu.ishikawa.jp","tsubata.ishikawa.jp","tsurugi.ishikawa.jp","uchinada.ishikawa.jp","wajima.ishikawa.jp","fudai.iwate.jp","fujisawa.iwate.jp","hanamaki.iwate.jp","hiraizumi.iwate.jp","hirono.iwate.jp","ichinohe.iwate.jp","ichinoseki.iwate.jp","iwaizumi.iwate.jp","iwate.iwate.jp","joboji.iwate.jp","kamaishi.iwate.jp","kanegasaki.iwate.jp","karumai.iwate.jp","kawai.iwate.jp","kitakami.iwate.jp","kuji.iwate.jp","kunohe.iwate.jp","kuzumaki.iwate.jp","miyako.iwate.jp","mizusawa.iwate.jp","morioka.iwate.jp","ninohe.iwate.jp","noda.iwate.jp","ofunato.iwate.jp","oshu.iwate.jp","otsuchi.iwate.jp","rikuzentakata.iwate.jp","shiwa.iwate.jp","shizukuishi.iwate.jp","sumita.iwate.jp","tanohata.iwate.jp","tono.iwate.jp","yahaba.iwate.jp","yamada.iwate.jp","ayagawa.kagawa.jp","higashikagawa.kagawa.jp","kanonji.kagawa.jp","kotohira.kagawa.jp","manno.kagawa.jp","marugame.kagawa.jp","mitoyo.kagawa.jp","naoshima.kagawa.jp","sanuki.kagawa.jp","tadotsu.kagawa.jp","takamatsu.kagawa.jp","tonosho.kagawa.jp","uchinomi.kagawa.jp","utazu.kagawa.jp","zentsuji.kagawa.jp","akune.kagoshima.jp","amami.kagoshima.jp","hioki.kagoshima.jp","isa.kagoshima.jp","isen.kagoshima.jp","izumi.kagoshima.jp","kagoshima.kagoshima.jp","kanoya.kagoshima.jp","kawanabe.kagoshima.jp","kinko.kagoshima.jp","kouyama.kagoshima.jp","makurazaki.kagoshima.jp","matsumoto.kagoshima.jp","minamitane.kagoshima.jp","nakatane.kagoshima.jp","nishinoomote.kagoshima.jp","satsumasendai.kagoshima.jp","soo.kagoshima.jp","tarumizu.kagoshima.jp","yusui.kagoshima.jp","aikawa.kanagawa.jp","atsugi.kanagawa.jp","ayase.kanagawa.jp","chigasaki.kanagawa.jp","ebina.kanagawa.jp","fujisawa.kanagawa.jp","hadano.kanagawa.jp","hakone.kanagawa.jp","hiratsuka.kanagawa.jp","isehara.kanagawa.jp","kaisei.kanagawa.jp","kamakura.kanagawa.jp","kiyokawa.kanagawa.jp","matsuda.kanagawa.jp","minamiashigara.kanagawa.jp","miura.kanagawa.jp","nakai.kanagawa.jp","ninomiya.kanagawa.jp","odawara.kanagawa.jp","oi.kanagawa.jp","oiso.kanagawa.jp","sagamihara.kanagawa.jp","samukawa.kanagawa.jp","tsukui.kanagawa.jp","yamakita.kanagawa.jp","yamato.kanagawa.jp","yokosuka.kanagawa.jp","yugawara.kanagawa.jp","zama.kanagawa.jp","zushi.kanagawa.jp","aki.kochi.jp","geisei.kochi.jp","hidaka.kochi.jp","higashitsuno.kochi.jp","ino.kochi.jp","kagami.kochi.jp","kami.kochi.jp","kitagawa.kochi.jp","kochi.kochi.jp","mihara.kochi.jp","motoyama.kochi.jp","muroto.kochi.jp","nahari.kochi.jp","nakamura.kochi.jp","nankoku.kochi.jp","nishitosa.kochi.jp","niyodogawa.kochi.jp","ochi.kochi.jp","okawa.kochi.jp","otoyo.kochi.jp","otsuki.kochi.jp","sakawa.kochi.jp","sukumo.kochi.jp","susaki.kochi.jp","tosa.kochi.jp","tosashimizu.kochi.jp","toyo.kochi.jp","tsuno.kochi.jp","umaji.kochi.jp","yasuda.kochi.jp","yusuhara.kochi.jp","amakusa.kumamoto.jp","arao.kumamoto.jp","aso.kumamoto.jp","choyo.kumamoto.jp","gyokuto.kumamoto.jp","kamiamakusa.kumamoto.jp","kikuchi.kumamoto.jp","kumamoto.kumamoto.jp","mashiki.kumamoto.jp","mifune.kumamoto.jp","minamata.kumamoto.jp","minamioguni.kumamoto.jp","nagasu.kumamoto.jp","nishihara.kumamoto.jp","oguni.kumamoto.jp","ozu.kumamoto.jp","sumoto.kumamoto.jp","takamori.kumamoto.jp","uki.kumamoto.jp","uto.kumamoto.jp","yamaga.kumamoto.jp","yamato.kumamoto.jp","yatsushiro.kumamoto.jp","ayabe.kyoto.jp","fukuchiyama.kyoto.jp","higashiyama.kyoto.jp","ide.kyoto.jp","ine.kyoto.jp","joyo.kyoto.jp","kameoka.kyoto.jp","kamo.kyoto.jp","kita.kyoto.jp","kizu.kyoto.jp","kumiyama.kyoto.jp","kyotamba.kyoto.jp","kyotanabe.kyoto.jp","kyotango.kyoto.jp","maizuru.kyoto.jp","minami.kyoto.jp","minamiyamashiro.kyoto.jp","miyazu.kyoto.jp","muko.kyoto.jp","nagaokakyo.kyoto.jp","nakagyo.kyoto.jp","nantan.kyoto.jp","oyamazaki.kyoto.jp","sakyo.kyoto.jp","seika.kyoto.jp","tanabe.kyoto.jp","uji.kyoto.jp","ujitawara.kyoto.jp","wazuka.kyoto.jp","yamashina.kyoto.jp","yawata.kyoto.jp","asahi.mie.jp","inabe.mie.jp","ise.mie.jp","kameyama.mie.jp","kawagoe.mie.jp","kiho.mie.jp","kisosaki.mie.jp","kiwa.mie.jp","komono.mie.jp","kumano.mie.jp","kuwana.mie.jp","matsusaka.mie.jp","meiwa.mie.jp","mihama.mie.jp","minamiise.mie.jp","misugi.mie.jp","miyama.mie.jp","nabari.mie.jp","shima.mie.jp","suzuka.mie.jp","tado.mie.jp","taiki.mie.jp","taki.mie.jp","tamaki.mie.jp","toba.mie.jp","tsu.mie.jp","udono.mie.jp","ureshino.mie.jp","watarai.mie.jp","yokkaichi.mie.jp","furukawa.miyagi.jp","higashimatsushima.miyagi.jp","ishinomaki.miyagi.jp","iwanuma.miyagi.jp","kakuda.miyagi.jp","kami.miyagi.jp","kawasaki.miyagi.jp","marumori.miyagi.jp","matsushima.miyagi.jp","minamisanriku.miyagi.jp","misato.miyagi.jp","murata.miyagi.jp","natori.miyagi.jp","ogawara.miyagi.jp","ohira.miyagi.jp","onagawa.miyagi.jp","osaki.miyagi.jp","rifu.miyagi.jp","semine.miyagi.jp","shibata.miyagi.jp","shichikashuku.miyagi.jp","shikama.miyagi.jp","shiogama.miyagi.jp","shiroishi.miyagi.jp","tagajo.miyagi.jp","taiwa.miyagi.jp","tome.miyagi.jp","tomiya.miyagi.jp","wakuya.miyagi.jp","watari.miyagi.jp","yamamoto.miyagi.jp","zao.miyagi.jp","aya.miyazaki.jp","ebino.miyazaki.jp","gokase.miyazaki.jp","hyuga.miyazaki.jp","kadogawa.miyazaki.jp","kawaminami.miyazaki.jp","kijo.miyazaki.jp","kitagawa.miyazaki.jp","kitakata.miyazaki.jp","kitaura.miyazaki.jp","kobayashi.miyazaki.jp","kunitomi.miyazaki.jp","kushima.miyazaki.jp","mimata.miyazaki.jp","miyakonojo.miyazaki.jp","miyazaki.miyazaki.jp","morotsuka.miyazaki.jp","nichinan.miyazaki.jp","nishimera.miyazaki.jp","nobeoka.miyazaki.jp","saito.miyazaki.jp","shiiba.miyazaki.jp","shintomi.miyazaki.jp","takaharu.miyazaki.jp","takanabe.miyazaki.jp","takazaki.miyazaki.jp","tsuno.miyazaki.jp","achi.nagano.jp","agematsu.nagano.jp","anan.nagano.jp","aoki.nagano.jp","asahi.nagano.jp","azumino.nagano.jp","chikuhoku.nagano.jp","chikuma.nagano.jp","chino.nagano.jp","fujimi.nagano.jp","hakuba.nagano.jp","hara.nagano.jp","hiraya.nagano.jp","iida.nagano.jp","iijima.nagano.jp","iiyama.nagano.jp","iizuna.nagano.jp","ikeda.nagano.jp","ikusaka.nagano.jp","ina.nagano.jp","karuizawa.nagano.jp","kawakami.nagano.jp","kiso.nagano.jp","kisofukushima.nagano.jp","kitaaiki.nagano.jp","komagane.nagano.jp","komoro.nagano.jp","matsukawa.nagano.jp","matsumoto.nagano.jp","miasa.nagano.jp","minamiaiki.nagano.jp","minamimaki.nagano.jp","minamiminowa.nagano.jp","minowa.nagano.jp","miyada.nagano.jp","miyota.nagano.jp","mochizuki.nagano.jp","nagano.nagano.jp","nagawa.nagano.jp","nagiso.nagano.jp","nakagawa.nagano.jp","nakano.nagano.jp","nozawaonsen.nagano.jp","obuse.nagano.jp","ogawa.nagano.jp","okaya.nagano.jp","omachi.nagano.jp","omi.nagano.jp","ookuwa.nagano.jp","ooshika.nagano.jp","otaki.nagano.jp","otari.nagano.jp","sakae.nagano.jp","sakaki.nagano.jp","saku.nagano.jp","sakuho.nagano.jp","shimosuwa.nagano.jp","shinanomachi.nagano.jp","shiojiri.nagano.jp","suwa.nagano.jp","suzaka.nagano.jp","takagi.nagano.jp","takamori.nagano.jp","takayama.nagano.jp","tateshina.nagano.jp","tatsuno.nagano.jp","togakushi.nagano.jp","togura.nagano.jp","tomi.nagano.jp","ueda.nagano.jp","wada.nagano.jp","yamagata.nagano.jp","yamanouchi.nagano.jp","yasaka.nagano.jp","yasuoka.nagano.jp","chijiwa.nagasaki.jp","futsu.nagasaki.jp","goto.nagasaki.jp","hasami.nagasaki.jp","hirado.nagasaki.jp","iki.nagasaki.jp","isahaya.nagasaki.jp","kawatana.nagasaki.jp","kuchinotsu.nagasaki.jp","matsuura.nagasaki.jp","nagasaki.nagasaki.jp","obama.nagasaki.jp","omura.nagasaki.jp","oseto.nagasaki.jp","saikai.nagasaki.jp","sasebo.nagasaki.jp","seihi.nagasaki.jp","shimabara.nagasaki.jp","shinkamigoto.nagasaki.jp","togitsu.nagasaki.jp","tsushima.nagasaki.jp","unzen.nagasaki.jp","ando.nara.jp","gose.nara.jp","heguri.nara.jp","higashiyoshino.nara.jp","ikaruga.nara.jp","ikoma.nara.jp","kamikitayama.nara.jp","kanmaki.nara.jp","kashiba.nara.jp","kashihara.nara.jp","katsuragi.nara.jp","kawai.nara.jp","kawakami.nara.jp","kawanishi.nara.jp","koryo.nara.jp","kurotaki.nara.jp","mitsue.nara.jp","miyake.nara.jp","nara.nara.jp","nosegawa.nara.jp","oji.nara.jp","ouda.nara.jp","oyodo.nara.jp","sakurai.nara.jp","sango.nara.jp","shimoichi.nara.jp","shimokitayama.nara.jp","shinjo.nara.jp","soni.nara.jp","takatori.nara.jp","tawaramoto.nara.jp","tenkawa.nara.jp","tenri.nara.jp","uda.nara.jp","yamatokoriyama.nara.jp","yamatotakada.nara.jp","yamazoe.nara.jp","yoshino.nara.jp","aga.niigata.jp","agano.niigata.jp","gosen.niigata.jp","itoigawa.niigata.jp","izumozaki.niigata.jp","joetsu.niigata.jp","kamo.niigata.jp","kariwa.niigata.jp","kashiwazaki.niigata.jp","minamiuonuma.niigata.jp","mitsuke.niigata.jp","muika.niigata.jp","murakami.niigata.jp","myoko.niigata.jp","nagaoka.niigata.jp","niigata.niigata.jp","ojiya.niigata.jp","omi.niigata.jp","sado.niigata.jp","sanjo.niigata.jp","seiro.niigata.jp","seirou.niigata.jp","sekikawa.niigata.jp","shibata.niigata.jp","tagami.niigata.jp","tainai.niigata.jp","tochio.niigata.jp","tokamachi.niigata.jp","tsubame.niigata.jp","tsunan.niigata.jp","uonuma.niigata.jp","yahiko.niigata.jp","yoita.niigata.jp","yuzawa.niigata.jp","beppu.oita.jp","bungoono.oita.jp","bungotakada.oita.jp","hasama.oita.jp","hiji.oita.jp","himeshima.oita.jp","hita.oita.jp","kamitsue.oita.jp","kokonoe.oita.jp","kuju.oita.jp","kunisaki.oita.jp","kusu.oita.jp","oita.oita.jp","saiki.oita.jp","taketa.oita.jp","tsukumi.oita.jp","usa.oita.jp","usuki.oita.jp","yufu.oita.jp","akaiwa.okayama.jp","asakuchi.okayama.jp","bizen.okayama.jp","hayashima.okayama.jp","ibara.okayama.jp","kagamino.okayama.jp","kasaoka.okayama.jp","kibichuo.okayama.jp","kumenan.okayama.jp","kurashiki.okayama.jp","maniwa.okayama.jp","misaki.okayama.jp","nagi.okayama.jp","niimi.okayama.jp","nishiawakura.okayama.jp","okayama.okayama.jp","satosho.okayama.jp","setouchi.okayama.jp","shinjo.okayama.jp","shoo.okayama.jp","soja.okayama.jp","takahashi.okayama.jp","tamano.okayama.jp","tsuyama.okayama.jp","wake.okayama.jp","yakage.okayama.jp","aguni.okinawa.jp","ginowan.okinawa.jp","ginoza.okinawa.jp","gushikami.okinawa.jp","haebaru.okinawa.jp","higashi.okinawa.jp","hirara.okinawa.jp","iheya.okinawa.jp","ishigaki.okinawa.jp","ishikawa.okinawa.jp","itoman.okinawa.jp","izena.okinawa.jp","kadena.okinawa.jp","kin.okinawa.jp","kitadaito.okinawa.jp","kitanakagusuku.okinawa.jp","kumejima.okinawa.jp","kunigami.okinawa.jp","minamidaito.okinawa.jp","motobu.okinawa.jp","nago.okinawa.jp","naha.okinawa.jp","nakagusuku.okinawa.jp","nakijin.okinawa.jp","nanjo.okinawa.jp","nishihara.okinawa.jp","ogimi.okinawa.jp","okinawa.okinawa.jp","onna.okinawa.jp","shimoji.okinawa.jp","taketomi.okinawa.jp","tarama.okinawa.jp","tokashiki.okinawa.jp","tomigusuku.okinawa.jp","tonaki.okinawa.jp","urasoe.okinawa.jp","uruma.okinawa.jp","yaese.okinawa.jp","yomitan.okinawa.jp","yonabaru.okinawa.jp","yonaguni.okinawa.jp","zamami.okinawa.jp","abeno.osaka.jp","chihayaakasaka.osaka.jp","chuo.osaka.jp","daito.osaka.jp","fujiidera.osaka.jp","habikino.osaka.jp","hannan.osaka.jp","higashiosaka.osaka.jp","higashisumiyoshi.osaka.jp","higashiyodogawa.osaka.jp","hirakata.osaka.jp","ibaraki.osaka.jp","ikeda.osaka.jp","izumi.osaka.jp","izumiotsu.osaka.jp","izumisano.osaka.jp","kadoma.osaka.jp","kaizuka.osaka.jp","kanan.osaka.jp","kashiwara.osaka.jp","katano.osaka.jp","kawachinagano.osaka.jp","kishiwada.osaka.jp","kita.osaka.jp","kumatori.osaka.jp","matsubara.osaka.jp","minato.osaka.jp","minoh.osaka.jp","misaki.osaka.jp","moriguchi.osaka.jp","neyagawa.osaka.jp","nishi.osaka.jp","nose.osaka.jp","osakasayama.osaka.jp","sakai.osaka.jp","sayama.osaka.jp","sennan.osaka.jp","settsu.osaka.jp","shijonawate.osaka.jp","shimamoto.osaka.jp","suita.osaka.jp","tadaoka.osaka.jp","taishi.osaka.jp","tajiri.osaka.jp","takaishi.osaka.jp","takatsuki.osaka.jp","tondabayashi.osaka.jp","toyonaka.osaka.jp","toyono.osaka.jp","yao.osaka.jp","ariake.saga.jp","arita.saga.jp","fukudomi.saga.jp","genkai.saga.jp","hamatama.saga.jp","hizen.saga.jp","imari.saga.jp","kamimine.saga.jp","kanzaki.saga.jp","karatsu.saga.jp","kashima.saga.jp","kitagata.saga.jp","kitahata.saga.jp","kiyama.saga.jp","kouhoku.saga.jp","kyuragi.saga.jp","nishiarita.saga.jp","ogi.saga.jp","omachi.saga.jp","ouchi.saga.jp","saga.saga.jp","shiroishi.saga.jp","taku.saga.jp","tara.saga.jp","tosu.saga.jp","yoshinogari.saga.jp","arakawa.saitama.jp","asaka.saitama.jp","chichibu.saitama.jp","fujimi.saitama.jp","fujimino.saitama.jp","fukaya.saitama.jp","hanno.saitama.jp","hanyu.saitama.jp","hasuda.saitama.jp","hatogaya.saitama.jp","hatoyama.saitama.jp","hidaka.saitama.jp","higashichichibu.saitama.jp","higashimatsuyama.saitama.jp","honjo.saitama.jp","ina.saitama.jp","iruma.saitama.jp","iwatsuki.saitama.jp","kamiizumi.saitama.jp","kamikawa.saitama.jp","kamisato.saitama.jp","kasukabe.saitama.jp","kawagoe.saitama.jp","kawaguchi.saitama.jp","kawajima.saitama.jp","kazo.saitama.jp","kitamoto.saitama.jp","koshigaya.saitama.jp","kounosu.saitama.jp","kuki.saitama.jp","kumagaya.saitama.jp","matsubushi.saitama.jp","minano.saitama.jp","misato.saitama.jp","miyashiro.saitama.jp","miyoshi.saitama.jp","moroyama.saitama.jp","nagatoro.saitama.jp","namegawa.saitama.jp","niiza.saitama.jp","ogano.saitama.jp","ogawa.saitama.jp","ogose.saitama.jp","okegawa.saitama.jp","omiya.saitama.jp","otaki.saitama.jp","ranzan.saitama.jp","ryokami.saitama.jp","saitama.saitama.jp","sakado.saitama.jp","satte.saitama.jp","sayama.saitama.jp","shiki.saitama.jp","shiraoka.saitama.jp","soka.saitama.jp","sugito.saitama.jp","toda.saitama.jp","tokigawa.saitama.jp","tokorozawa.saitama.jp","tsurugashima.saitama.jp","urawa.saitama.jp","warabi.saitama.jp","yashio.saitama.jp","yokoze.saitama.jp","yono.saitama.jp","yorii.saitama.jp","yoshida.saitama.jp","yoshikawa.saitama.jp","yoshimi.saitama.jp","aisho.shiga.jp","gamo.shiga.jp","higashiomi.shiga.jp","hikone.shiga.jp","koka.shiga.jp","konan.shiga.jp","kosei.shiga.jp","koto.shiga.jp","kusatsu.shiga.jp","maibara.shiga.jp","moriyama.shiga.jp","nagahama.shiga.jp","nishiazai.shiga.jp","notogawa.shiga.jp","omihachiman.shiga.jp","otsu.shiga.jp","ritto.shiga.jp","ryuoh.shiga.jp","takashima.shiga.jp","takatsuki.shiga.jp","torahime.shiga.jp","toyosato.shiga.jp","yasu.shiga.jp","akagi.shimane.jp","ama.shimane.jp","gotsu.shimane.jp","hamada.shimane.jp","higashiizumo.shimane.jp","hikawa.shimane.jp","hikimi.shimane.jp","izumo.shimane.jp","kakinoki.shimane.jp","masuda.shimane.jp","matsue.shimane.jp","misato.shimane.jp","nishinoshima.shimane.jp","ohda.shimane.jp","okinoshima.shimane.jp","okuizumo.shimane.jp","shimane.shimane.jp","tamayu.shimane.jp","tsuwano.shimane.jp","unnan.shimane.jp","yakumo.shimane.jp","yasugi.shimane.jp","yatsuka.shimane.jp","arai.shizuoka.jp","atami.shizuoka.jp","fuji.shizuoka.jp","fujieda.shizuoka.jp","fujikawa.shizuoka.jp","fujinomiya.shizuoka.jp","fukuroi.shizuoka.jp","gotemba.shizuoka.jp","haibara.shizuoka.jp","hamamatsu.shizuoka.jp","higashiizu.shizuoka.jp","ito.shizuoka.jp","iwata.shizuoka.jp","izu.shizuoka.jp","izunokuni.shizuoka.jp","kakegawa.shizuoka.jp","kannami.shizuoka.jp","kawanehon.shizuoka.jp","kawazu.shizuoka.jp","kikugawa.shizuoka.jp","kosai.shizuoka.jp","makinohara.shizuoka.jp","matsuzaki.shizuoka.jp","minamiizu.shizuoka.jp","mishima.shizuoka.jp","morimachi.shizuoka.jp","nishiizu.shizuoka.jp","numazu.shizuoka.jp","omaezaki.shizuoka.jp","shimada.shizuoka.jp","shimizu.shizuoka.jp","shimoda.shizuoka.jp","shizuoka.shizuoka.jp","susono.shizuoka.jp","yaizu.shizuoka.jp","yoshida.shizuoka.jp","ashikaga.tochigi.jp","bato.tochigi.jp","haga.tochigi.jp","ichikai.tochigi.jp","iwafune.tochigi.jp","kaminokawa.tochigi.jp","kanuma.tochigi.jp","karasuyama.tochigi.jp","kuroiso.tochigi.jp","mashiko.tochigi.jp","mibu.tochigi.jp","moka.tochigi.jp","motegi.tochigi.jp","nasu.tochigi.jp","nasushiobara.tochigi.jp","nikko.tochigi.jp","nishikata.tochigi.jp","nogi.tochigi.jp","ohira.tochigi.jp","ohtawara.tochigi.jp","oyama.tochigi.jp","sakura.tochigi.jp","sano.tochigi.jp","shimotsuke.tochigi.jp","shioya.tochigi.jp","takanezawa.tochigi.jp","tochigi.tochigi.jp","tsuga.tochigi.jp","ujiie.tochigi.jp","utsunomiya.tochigi.jp","yaita.tochigi.jp","aizumi.tokushima.jp","anan.tokushima.jp","ichiba.tokushima.jp","itano.tokushima.jp","kainan.tokushima.jp","komatsushima.tokushima.jp","matsushige.tokushima.jp","mima.tokushima.jp","minami.tokushima.jp","miyoshi.tokushima.jp","mugi.tokushima.jp","nakagawa.tokushima.jp","naruto.tokushima.jp","sanagochi.tokushima.jp","shishikui.tokushima.jp","tokushima.tokushima.jp","wajiki.tokushima.jp","adachi.tokyo.jp","akiruno.tokyo.jp","akishima.tokyo.jp","aogashima.tokyo.jp","arakawa.tokyo.jp","bunkyo.tokyo.jp","chiyoda.tokyo.jp","chofu.tokyo.jp","chuo.tokyo.jp","edogawa.tokyo.jp","fuchu.tokyo.jp","fussa.tokyo.jp","hachijo.tokyo.jp","hachioji.tokyo.jp","hamura.tokyo.jp","higashikurume.tokyo.jp","higashimurayama.tokyo.jp","higashiyamato.tokyo.jp","hino.tokyo.jp","hinode.tokyo.jp","hinohara.tokyo.jp","inagi.tokyo.jp","itabashi.tokyo.jp","katsushika.tokyo.jp","kita.tokyo.jp","kiyose.tokyo.jp","kodaira.tokyo.jp","koganei.tokyo.jp","kokubunji.tokyo.jp","komae.tokyo.jp","koto.tokyo.jp","kouzushima.tokyo.jp","kunitachi.tokyo.jp","machida.tokyo.jp","meguro.tokyo.jp","minato.tokyo.jp","mitaka.tokyo.jp","mizuho.tokyo.jp","musashimurayama.tokyo.jp","musashino.tokyo.jp","nakano.tokyo.jp","nerima.tokyo.jp","ogasawara.tokyo.jp","okutama.tokyo.jp","ome.tokyo.jp","oshima.tokyo.jp","ota.tokyo.jp","setagaya.tokyo.jp","shibuya.tokyo.jp","shinagawa.tokyo.jp","shinjuku.tokyo.jp","suginami.tokyo.jp","sumida.tokyo.jp","tachikawa.tokyo.jp","taito.tokyo.jp","tama.tokyo.jp","toshima.tokyo.jp","chizu.tottori.jp","hino.tottori.jp","kawahara.tottori.jp","koge.tottori.jp","kotoura.tottori.jp","misasa.tottori.jp","nanbu.tottori.jp","nichinan.tottori.jp","sakaiminato.tottori.jp","tottori.tottori.jp","wakasa.tottori.jp","yazu.tottori.jp","yonago.tottori.jp","asahi.toyama.jp","fuchu.toyama.jp","fukumitsu.toyama.jp","funahashi.toyama.jp","himi.toyama.jp","imizu.toyama.jp","inami.toyama.jp","johana.toyama.jp","kamiichi.toyama.jp","kurobe.toyama.jp","nakaniikawa.toyama.jp","namerikawa.toyama.jp","nanto.toyama.jp","nyuzen.toyama.jp","oyabe.toyama.jp","taira.toyama.jp","takaoka.toyama.jp","tateyama.toyama.jp","toga.toyama.jp","tonami.toyama.jp","toyama.toyama.jp","unazuki.toyama.jp","uozu.toyama.jp","yamada.toyama.jp","arida.wakayama.jp","aridagawa.wakayama.jp","gobo.wakayama.jp","hashimoto.wakayama.jp","hidaka.wakayama.jp","hirogawa.wakayama.jp","inami.wakayama.jp","iwade.wakayama.jp","kainan.wakayama.jp","kamitonda.wakayama.jp","katsuragi.wakayama.jp","kimino.wakayama.jp","kinokawa.wakayama.jp","kitayama.wakayama.jp","koya.wakayama.jp","koza.wakayama.jp","kozagawa.wakayama.jp","kudoyama.wakayama.jp","kushimoto.wakayama.jp","mihama.wakayama.jp","misato.wakayama.jp","nachikatsuura.wakayama.jp","shingu.wakayama.jp","shirahama.wakayama.jp","taiji.wakayama.jp","tanabe.wakayama.jp","wakayama.wakayama.jp","yuasa.wakayama.jp","yura.wakayama.jp","asahi.yamagata.jp","funagata.yamagata.jp","higashine.yamagata.jp","iide.yamagata.jp","kahoku.yamagata.jp","kaminoyama.yamagata.jp","kaneyama.yamagata.jp","kawanishi.yamagata.jp","mamurogawa.yamagata.jp","mikawa.yamagata.jp","murayama.yamagata.jp","nagai.yamagata.jp","nakayama.yamagata.jp","nanyo.yamagata.jp","nishikawa.yamagata.jp","obanazawa.yamagata.jp","oe.yamagata.jp","oguni.yamagata.jp","ohkura.yamagata.jp","oishida.yamagata.jp","sagae.yamagata.jp","sakata.yamagata.jp","sakegawa.yamagata.jp","shinjo.yamagata.jp","shirataka.yamagata.jp","shonai.yamagata.jp","takahata.yamagata.jp","tendo.yamagata.jp","tozawa.yamagata.jp","tsuruoka.yamagata.jp","yamagata.yamagata.jp","yamanobe.yamagata.jp","yonezawa.yamagata.jp","yuza.yamagata.jp","abu.yamaguchi.jp","hagi.yamaguchi.jp","hikari.yamaguchi.jp","hofu.yamaguchi.jp","iwakuni.yamaguchi.jp","kudamatsu.yamaguchi.jp","mitou.yamaguchi.jp","nagato.yamaguchi.jp","oshima.yamaguchi.jp","shimonoseki.yamaguchi.jp","shunan.yamaguchi.jp","tabuse.yamaguchi.jp","tokuyama.yamaguchi.jp","toyota.yamaguchi.jp","ube.yamaguchi.jp","yuu.yamaguchi.jp","chuo.yamanashi.jp","doshi.yamanashi.jp","fuefuki.yamanashi.jp","fujikawa.yamanashi.jp","fujikawaguchiko.yamanashi.jp","fujiyoshida.yamanashi.jp","hayakawa.yamanashi.jp","hokuto.yamanashi.jp","ichikawamisato.yamanashi.jp","kai.yamanashi.jp","kofu.yamanashi.jp","koshu.yamanashi.jp","kosuge.yamanashi.jp","minami-alps.yamanashi.jp","minobu.yamanashi.jp","nakamichi.yamanashi.jp","nanbu.yamanashi.jp","narusawa.yamanashi.jp","nirasaki.yamanashi.jp","nishikatsura.yamanashi.jp","oshino.yamanashi.jp","otsuki.yamanashi.jp","showa.yamanashi.jp","tabayama.yamanashi.jp","tsuru.yamanashi.jp","uenohara.yamanashi.jp","yamanakako.yamanashi.jp","yamanashi.yamanashi.jp","ke","ac.ke","co.ke","go.ke","info.ke","me.ke","mobi.ke","ne.ke","or.ke","sc.ke","kg","org.kg","net.kg","com.kg","edu.kg","gov.kg","mil.kg","*.kh","ki","edu.ki","biz.ki","net.ki","org.ki","gov.ki","info.ki","com.ki","km","org.km","nom.km","gov.km","prd.km","tm.km","edu.km","mil.km","ass.km","com.km","coop.km","asso.km","presse.km","medecin.km","notaires.km","pharmaciens.km","veterinaire.km","gouv.km","kn","net.kn","org.kn","edu.kn","gov.kn","kp","com.kp","edu.kp","gov.kp","org.kp","rep.kp","tra.kp","kr","ac.kr","co.kr","es.kr","go.kr","hs.kr","kg.kr","mil.kr","ms.kr","ne.kr","or.kr","pe.kr","re.kr","sc.kr","busan.kr","chungbuk.kr","chungnam.kr","daegu.kr","daejeon.kr","gangwon.kr","gwangju.kr","gyeongbuk.kr","gyeonggi.kr","gyeongnam.kr","incheon.kr","jeju.kr","jeonbuk.kr","jeonnam.kr","seoul.kr","ulsan.kr","kw","com.kw","edu.kw","emb.kw","gov.kw","ind.kw","net.kw","org.kw","ky","edu.ky","gov.ky","com.ky","org.ky","net.ky","kz","org.kz","edu.kz","net.kz","gov.kz","mil.kz","com.kz","la","int.la","net.la","info.la","edu.la","gov.la","per.la","com.la","org.la","lb","com.lb","edu.lb","gov.lb","net.lb","org.lb","lc","com.lc","net.lc","co.lc","org.lc","edu.lc","gov.lc","li","lk","gov.lk","sch.lk","net.lk","int.lk","com.lk","org.lk","edu.lk","ngo.lk","soc.lk","web.lk","ltd.lk","assn.lk","grp.lk","hotel.lk","ac.lk","lr","com.lr","edu.lr","gov.lr","org.lr","net.lr","ls","ac.ls","biz.ls","co.ls","edu.ls","gov.ls","info.ls","net.ls","org.ls","sc.ls","lt","gov.lt","lu","lv","com.lv","edu.lv","gov.lv","org.lv","mil.lv","id.lv","net.lv","asn.lv","conf.lv","ly","com.ly","net.ly","gov.ly","plc.ly","edu.ly","sch.ly","med.ly","org.ly","id.ly","ma","co.ma","net.ma","gov.ma","org.ma","ac.ma","press.ma","mc","tm.mc","asso.mc","md","me","co.me","net.me","org.me","edu.me","ac.me","gov.me","its.me","priv.me","mg","org.mg","nom.mg","gov.mg","prd.mg","tm.mg","edu.mg","mil.mg","com.mg","co.mg","mh","mil","mk","com.mk","org.mk","net.mk","edu.mk","gov.mk","inf.mk","name.mk","ml","com.ml","edu.ml","gouv.ml","gov.ml","net.ml","org.ml","presse.ml","*.mm","mn","gov.mn","edu.mn","org.mn","mo","com.mo","net.mo","org.mo","edu.mo","gov.mo","mobi","mp","mq","mr","gov.mr","ms","com.ms","edu.ms","gov.ms","net.ms","org.ms","mt","com.mt","edu.mt","net.mt","org.mt","mu","com.mu","net.mu","org.mu","gov.mu","ac.mu","co.mu","or.mu","museum","academy.museum","agriculture.museum","air.museum","airguard.museum","alabama.museum","alaska.museum","amber.museum","ambulance.museum","american.museum","americana.museum","americanantiques.museum","americanart.museum","amsterdam.museum","and.museum","annefrank.museum","anthro.museum","anthropology.museum","antiques.museum","aquarium.museum","arboretum.museum","archaeological.museum","archaeology.museum","architecture.museum","art.museum","artanddesign.museum","artcenter.museum","artdeco.museum","arteducation.museum","artgallery.museum","arts.museum","artsandcrafts.museum","asmatart.museum","assassination.museum","assisi.museum","association.museum","astronomy.museum","atlanta.museum","austin.museum","australia.museum","automotive.museum","aviation.museum","axis.museum","badajoz.museum","baghdad.museum","bahn.museum","bale.museum","baltimore.museum","barcelona.museum","baseball.museum","basel.museum","baths.museum","bauern.museum","beauxarts.museum","beeldengeluid.museum","bellevue.museum","bergbau.museum","berkeley.museum","berlin.museum","bern.museum","bible.museum","bilbao.museum","bill.museum","birdart.museum","birthplace.museum","bonn.museum","boston.museum","botanical.museum","botanicalgarden.museum","botanicgarden.museum","botany.museum","brandywinevalley.museum","brasil.museum","bristol.museum","british.museum","britishcolumbia.museum","broadcast.museum","brunel.museum","brussel.museum","brussels.museum","bruxelles.museum","building.museum","burghof.museum","bus.museum","bushey.museum","cadaques.museum","california.museum","cambridge.museum","can.museum","canada.museum","capebreton.museum","carrier.museum","cartoonart.museum","casadelamoneda.museum","castle.museum","castres.museum","celtic.museum","center.museum","chattanooga.museum","cheltenham.museum","chesapeakebay.museum","chicago.museum","children.museum","childrens.museum","childrensgarden.museum","chiropractic.museum","chocolate.museum","christiansburg.museum","cincinnati.museum","cinema.museum","circus.museum","civilisation.museum","civilization.museum","civilwar.museum","clinton.museum","clock.museum","coal.museum","coastaldefence.museum","cody.museum","coldwar.museum","collection.museum","colonialwilliamsburg.museum","coloradoplateau.museum","columbia.museum","columbus.museum","communication.museum","communications.museum","community.museum","computer.museum","computerhistory.museum","comunicações.museum","contemporary.museum","contemporaryart.museum","convent.museum","copenhagen.museum","corporation.museum","correios-e-telecomunicações.museum","corvette.museum","costume.museum","countryestate.museum","county.museum","crafts.museum","cranbrook.museum","creation.museum","cultural.museum","culturalcenter.museum","culture.museum","cyber.museum","cymru.museum","dali.museum","dallas.museum","database.museum","ddr.museum","decorativearts.museum","delaware.museum","delmenhorst.museum","denmark.museum","depot.museum","design.museum","detroit.museum","dinosaur.museum","discovery.museum","dolls.museum","donostia.museum","durham.museum","eastafrica.museum","eastcoast.museum","education.museum","educational.museum","egyptian.museum","eisenbahn.museum","elburg.museum","elvendrell.museum","embroidery.museum","encyclopedic.museum","england.museum","entomology.museum","environment.museum","environmentalconservation.museum","epilepsy.museum","essex.museum","estate.museum","ethnology.museum","exeter.museum","exhibition.museum","family.museum","farm.museum","farmequipment.museum","farmers.museum","farmstead.museum","field.museum","figueres.museum","filatelia.museum","film.museum","fineart.museum","finearts.museum","finland.museum","flanders.museum","florida.museum","force.museum","fortmissoula.museum","fortworth.museum","foundation.museum","francaise.museum","frankfurt.museum","franziskaner.museum","freemasonry.museum","freiburg.museum","fribourg.museum","frog.museum","fundacio.museum","furniture.museum","gallery.museum","garden.museum","gateway.museum","geelvinck.museum","gemological.museum","geology.museum","georgia.museum","giessen.museum","glas.museum","glass.museum","gorge.museum","grandrapids.museum","graz.museum","guernsey.museum","halloffame.museum","hamburg.museum","handson.museum","harvestcelebration.museum","hawaii.museum","health.museum","heimatunduhren.museum","hellas.museum","helsinki.museum","hembygdsforbund.museum","heritage.museum","histoire.museum","historical.museum","historicalsociety.museum","historichouses.museum","historisch.museum","historisches.museum","history.museum","historyofscience.museum","horology.museum","house.museum","humanities.museum","illustration.museum","imageandsound.museum","indian.museum","indiana.museum","indianapolis.museum","indianmarket.museum","intelligence.museum","interactive.museum","iraq.museum","iron.museum","isleofman.museum","jamison.museum","jefferson.museum","jerusalem.museum","jewelry.museum","jewish.museum","jewishart.museum","jfk.museum","journalism.museum","judaica.museum","judygarland.museum","juedisches.museum","juif.museum","karate.museum","karikatur.museum","kids.museum","koebenhavn.museum","koeln.museum","kunst.museum","kunstsammlung.museum","kunstunddesign.museum","labor.museum","labour.museum","lajolla.museum","lancashire.museum","landes.museum","lans.museum","läns.museum","larsson.museum","lewismiller.museum","lincoln.museum","linz.museum","living.museum","livinghistory.museum","localhistory.museum","london.museum","losangeles.museum","louvre.museum","loyalist.museum","lucerne.museum","luxembourg.museum","luzern.museum","mad.museum","madrid.museum","mallorca.museum","manchester.museum","mansion.museum","mansions.museum","manx.museum","marburg.museum","maritime.museum","maritimo.museum","maryland.museum","marylhurst.museum","media.museum","medical.museum","medizinhistorisches.museum","meeres.museum","memorial.museum","mesaverde.museum","michigan.museum","midatlantic.museum","military.museum","mill.museum","miners.museum","mining.museum","minnesota.museum","missile.museum","missoula.museum","modern.museum","moma.museum","money.museum","monmouth.museum","monticello.museum","montreal.museum","moscow.museum","motorcycle.museum","muenchen.museum","muenster.museum","mulhouse.museum","muncie.museum","museet.museum","museumcenter.museum","museumvereniging.museum","music.museum","national.museum","nationalfirearms.museum","nationalheritage.museum","nativeamerican.museum","naturalhistory.museum","naturalhistorymuseum.museum","naturalsciences.museum","nature.museum","naturhistorisches.museum","natuurwetenschappen.museum","naumburg.museum","naval.museum","nebraska.museum","neues.museum","newhampshire.museum","newjersey.museum","newmexico.museum","newport.museum","newspaper.museum","newyork.museum","niepce.museum","norfolk.museum","north.museum","nrw.museum","nyc.museum","nyny.museum","oceanographic.museum","oceanographique.museum","omaha.museum","online.museum","ontario.museum","openair.museum","oregon.museum","oregontrail.museum","otago.museum","oxford.museum","pacific.museum","paderborn.museum","palace.museum","paleo.museum","palmsprings.museum","panama.museum","paris.museum","pasadena.museum","pharmacy.museum","philadelphia.museum","philadelphiaarea.museum","philately.museum","phoenix.museum","photography.museum","pilots.museum","pittsburgh.museum","planetarium.museum","plantation.museum","plants.museum","plaza.museum","portal.museum","portland.museum","portlligat.museum","posts-and-telecommunications.museum","preservation.museum","presidio.museum","press.museum","project.museum","public.museum","pubol.museum","quebec.museum","railroad.museum","railway.museum","research.museum","resistance.museum","riodejaneiro.museum","rochester.museum","rockart.museum","roma.museum","russia.museum","saintlouis.museum","salem.museum","salvadordali.museum","salzburg.museum","sandiego.museum","sanfrancisco.museum","santabarbara.museum","santacruz.museum","santafe.museum","saskatchewan.museum","satx.museum","savannahga.museum","schlesisches.museum","schoenbrunn.museum","schokoladen.museum","school.museum","schweiz.museum","science.museum","scienceandhistory.museum","scienceandindustry.museum","sciencecenter.museum","sciencecenters.museum","science-fiction.museum","sciencehistory.museum","sciences.museum","sciencesnaturelles.museum","scotland.museum","seaport.museum","settlement.museum","settlers.museum","shell.museum","sherbrooke.museum","sibenik.museum","silk.museum","ski.museum","skole.museum","society.museum","sologne.museum","soundandvision.museum","southcarolina.museum","southwest.museum","space.museum","spy.museum","square.museum","stadt.museum","stalbans.museum","starnberg.museum","state.museum","stateofdelaware.museum","station.museum","steam.museum","steiermark.museum","stjohn.museum","stockholm.museum","stpetersburg.museum","stuttgart.museum","suisse.museum","surgeonshall.museum","surrey.museum","svizzera.museum","sweden.museum","sydney.museum","tank.museum","tcm.museum","technology.museum","telekommunikation.museum","television.museum","texas.museum","textile.museum","theater.museum","time.museum","timekeeping.museum","topology.museum","torino.museum","touch.museum","town.museum","transport.museum","tree.museum","trolley.museum","trust.museum","trustee.museum","uhren.museum","ulm.museum","undersea.museum","university.museum","usa.museum","usantiques.museum","usarts.museum","uscountryestate.museum","usculture.museum","usdecorativearts.museum","usgarden.museum","ushistory.museum","ushuaia.museum","uslivinghistory.museum","utah.museum","uvic.museum","valley.museum","vantaa.museum","versailles.museum","viking.museum","village.museum","virginia.museum","virtual.museum","virtuel.museum","vlaanderen.museum","volkenkunde.museum","wales.museum","wallonie.museum","war.museum","washingtondc.museum","watchandclock.museum","watch-and-clock.museum","western.museum","westfalen.museum","whaling.museum","wildlife.museum","williamsburg.museum","windmill.museum","workshop.museum","york.museum","yorkshire.museum","yosemite.museum","youth.museum","zoological.museum","zoology.museum","ירושלים.museum","иком.museum","mv","aero.mv","biz.mv","com.mv","coop.mv","edu.mv","gov.mv","info.mv","int.mv","mil.mv","museum.mv","name.mv","net.mv","org.mv","pro.mv","mw","ac.mw","biz.mw","co.mw","com.mw","coop.mw","edu.mw","gov.mw","int.mw","museum.mw","net.mw","org.mw","mx","com.mx","org.mx","gob.mx","edu.mx","net.mx","my","com.my","net.my","org.my","gov.my","edu.my","mil.my","name.my","mz","ac.mz","adv.mz","co.mz","edu.mz","gov.mz","mil.mz","net.mz","org.mz","na","info.na","pro.na","name.na","school.na","or.na","dr.na","us.na","mx.na","ca.na","in.na","cc.na","tv.na","ws.na","mobi.na","co.na","com.na","org.na","name","nc","asso.nc","nom.nc","ne","net","nf","com.nf","net.nf","per.nf","rec.nf","web.nf","arts.nf","firm.nf","info.nf","other.nf","store.nf","ng","com.ng","edu.ng","gov.ng","i.ng","mil.ng","mobi.ng","name.ng","net.ng","org.ng","sch.ng","ni","ac.ni","biz.ni","co.ni","com.ni","edu.ni","gob.ni","in.ni","info.ni","int.ni","mil.ni","net.ni","nom.ni","org.ni","web.ni","nl","no","fhs.no","vgs.no","fylkesbibl.no","folkebibl.no","museum.no","idrett.no","priv.no","mil.no","stat.no","dep.no","kommune.no","herad.no","aa.no","ah.no","bu.no","fm.no","hl.no","hm.no","jan-mayen.no","mr.no","nl.no","nt.no","of.no","ol.no","oslo.no","rl.no","sf.no","st.no","svalbard.no","tm.no","tr.no","va.no","vf.no","gs.aa.no","gs.ah.no","gs.bu.no","gs.fm.no","gs.hl.no","gs.hm.no","gs.jan-mayen.no","gs.mr.no","gs.nl.no","gs.nt.no","gs.of.no","gs.ol.no","gs.oslo.no","gs.rl.no","gs.sf.no","gs.st.no","gs.svalbard.no","gs.tm.no","gs.tr.no","gs.va.no","gs.vf.no","akrehamn.no","åkrehamn.no","algard.no","ålgård.no","arna.no","brumunddal.no","bryne.no","bronnoysund.no","brønnøysund.no","drobak.no","drøbak.no","egersund.no","fetsund.no","floro.no","florø.no","fredrikstad.no","hokksund.no","honefoss.no","hønefoss.no","jessheim.no","jorpeland.no","jørpeland.no","kirkenes.no","kopervik.no","krokstadelva.no","langevag.no","langevåg.no","leirvik.no","mjondalen.no","mjøndalen.no","mo-i-rana.no","mosjoen.no","mosjøen.no","nesoddtangen.no","orkanger.no","osoyro.no","osøyro.no","raholt.no","råholt.no","sandnessjoen.no","sandnessjøen.no","skedsmokorset.no","slattum.no","spjelkavik.no","stathelle.no","stavern.no","stjordalshalsen.no","stjørdalshalsen.no","tananger.no","tranby.no","vossevangen.no","afjord.no","åfjord.no","agdenes.no","al.no","ål.no","alesund.no","ålesund.no","alstahaug.no","alta.no","áltá.no","alaheadju.no","álaheadju.no","alvdal.no","amli.no","åmli.no","amot.no","åmot.no","andebu.no","andoy.no","andøy.no","andasuolo.no","ardal.no","årdal.no","aremark.no","arendal.no","ås.no","aseral.no","åseral.no","asker.no","askim.no","askvoll.no","askoy.no","askøy.no","asnes.no","åsnes.no","audnedaln.no","aukra.no","aure.no","aurland.no","aurskog-holand.no","aurskog-høland.no","austevoll.no","austrheim.no","averoy.no","averøy.no","balestrand.no","ballangen.no","balat.no","bálát.no","balsfjord.no","bahccavuotna.no","báhccavuotna.no","bamble.no","bardu.no","beardu.no","beiarn.no","bajddar.no","bájddar.no","baidar.no","báidár.no","berg.no","bergen.no","berlevag.no","berlevåg.no","bearalvahki.no","bearalváhki.no","bindal.no","birkenes.no","bjarkoy.no","bjarkøy.no","bjerkreim.no","bjugn.no","bodo.no","bodø.no","badaddja.no","bådåddjå.no","budejju.no","bokn.no","bremanger.no","bronnoy.no","brønnøy.no","bygland.no","bykle.no","barum.no","bærum.no","bo.telemark.no","bø.telemark.no","bo.nordland.no","bø.nordland.no","bievat.no","bievát.no","bomlo.no","bømlo.no","batsfjord.no","båtsfjord.no","bahcavuotna.no","báhcavuotna.no","dovre.no","drammen.no","drangedal.no","dyroy.no","dyrøy.no","donna.no","dønna.no","eid.no","eidfjord.no","eidsberg.no","eidskog.no","eidsvoll.no","eigersund.no","elverum.no","enebakk.no","engerdal.no","etne.no","etnedal.no","evenes.no","evenassi.no","evenášši.no","evje-og-hornnes.no","farsund.no","fauske.no","fuossko.no","fuoisku.no","fedje.no","fet.no","finnoy.no","finnøy.no","fitjar.no","fjaler.no","fjell.no","flakstad.no","flatanger.no","flekkefjord.no","flesberg.no","flora.no","fla.no","flå.no","folldal.no","forsand.no","fosnes.no","frei.no","frogn.no","froland.no","frosta.no","frana.no","fræna.no","froya.no","frøya.no","fusa.no","fyresdal.no","forde.no","førde.no","gamvik.no","gangaviika.no","gáŋgaviika.no","gaular.no","gausdal.no","gildeskal.no","gildeskål.no","giske.no","gjemnes.no","gjerdrum.no","gjerstad.no","gjesdal.no","gjovik.no","gjøvik.no","gloppen.no","gol.no","gran.no","grane.no","granvin.no","gratangen.no","grimstad.no","grong.no","kraanghke.no","kråanghke.no","grue.no","gulen.no","hadsel.no","halden.no","halsa.no","hamar.no","hamaroy.no","habmer.no","hábmer.no","hapmir.no","hápmir.no","hammerfest.no","hammarfeasta.no","hámmárfeasta.no","haram.no","hareid.no","harstad.no","hasvik.no","aknoluokta.no","ákŋoluokta.no","hattfjelldal.no","aarborte.no","haugesund.no","hemne.no","hemnes.no","hemsedal.no","heroy.more-og-romsdal.no","herøy.møre-og-romsdal.no","heroy.nordland.no","herøy.nordland.no","hitra.no","hjartdal.no","hjelmeland.no","hobol.no","hobøl.no","hof.no","hol.no","hole.no","holmestrand.no","holtalen.no","holtålen.no","hornindal.no","horten.no","hurdal.no","hurum.no","hvaler.no","hyllestad.no","hagebostad.no","hægebostad.no","hoyanger.no","høyanger.no","hoylandet.no","høylandet.no","ha.no","hå.no","ibestad.no","inderoy.no","inderøy.no","iveland.no","jevnaker.no","jondal.no","jolster.no","jølster.no","karasjok.no","karasjohka.no","kárášjohka.no","karlsoy.no","galsa.no","gálsá.no","karmoy.no","karmøy.no","kautokeino.no","guovdageaidnu.no","klepp.no","klabu.no","klæbu.no","kongsberg.no","kongsvinger.no","kragero.no","kragerø.no","kristiansand.no","kristiansund.no","krodsherad.no","krødsherad.no","kvalsund.no","rahkkeravju.no","ráhkkerávju.no","kvam.no","kvinesdal.no","kvinnherad.no","kviteseid.no","kvitsoy.no","kvitsøy.no","kvafjord.no","kvæfjord.no","giehtavuoatna.no","kvanangen.no","kvænangen.no","navuotna.no","návuotna.no","kafjord.no","kåfjord.no","gaivuotna.no","gáivuotna.no","larvik.no","lavangen.no","lavagis.no","loabat.no","loabát.no","lebesby.no","davvesiida.no","leikanger.no","leirfjord.no","leka.no","leksvik.no","lenvik.no","leangaviika.no","leaŋgaviika.no","lesja.no","levanger.no","lier.no","lierne.no","lillehammer.no","lillesand.no","lindesnes.no","lindas.no","lindås.no","lom.no","loppa.no","lahppi.no","láhppi.no","lund.no","lunner.no","luroy.no","lurøy.no","luster.no","lyngdal.no","lyngen.no","ivgu.no","lardal.no","lerdal.no","lærdal.no","lodingen.no","lødingen.no","lorenskog.no","lørenskog.no","loten.no","løten.no","malvik.no","masoy.no","måsøy.no","muosat.no","muosát.no","mandal.no","marker.no","marnardal.no","masfjorden.no","meland.no","meldal.no","melhus.no","meloy.no","meløy.no","meraker.no","meråker.no","moareke.no","moåreke.no","midsund.no","midtre-gauldal.no","modalen.no","modum.no","molde.no","moskenes.no","moss.no","mosvik.no","malselv.no","målselv.no","malatvuopmi.no","málatvuopmi.no","namdalseid.no","aejrie.no","namsos.no","namsskogan.no","naamesjevuemie.no","nååmesjevuemie.no","laakesvuemie.no","nannestad.no","narvik.no","narviika.no","naustdal.no","nedre-eiker.no","nes.akershus.no","nes.buskerud.no","nesna.no","nesodden.no","nesseby.no","unjarga.no","unjárga.no","nesset.no","nissedal.no","nittedal.no","nord-aurdal.no","nord-fron.no","nord-odal.no","norddal.no","nordkapp.no","davvenjarga.no","davvenjárga.no","nordre-land.no","nordreisa.no","raisa.no","ráisa.no","nore-og-uvdal.no","notodden.no","naroy.no","nærøy.no","notteroy.no","nøtterøy.no","odda.no","oksnes.no","øksnes.no","oppdal.no","oppegard.no","oppegård.no","orkdal.no","orland.no","ørland.no","orskog.no","ørskog.no","orsta.no","ørsta.no","os.hedmark.no","os.hordaland.no","osen.no","osteroy.no","osterøy.no","ostre-toten.no","østre-toten.no","overhalla.no","ovre-eiker.no","øvre-eiker.no","oyer.no","øyer.no","oygarden.no","øygarden.no","oystre-slidre.no","øystre-slidre.no","porsanger.no","porsangu.no","porsáŋgu.no","porsgrunn.no","radoy.no","radøy.no","rakkestad.no","rana.no","ruovat.no","randaberg.no","rauma.no","rendalen.no","rennebu.no","rennesoy.no","rennesøy.no","rindal.no","ringebu.no","ringerike.no","ringsaker.no","rissa.no","risor.no","risør.no","roan.no","rollag.no","rygge.no","ralingen.no","rælingen.no","rodoy.no","rødøy.no","romskog.no","rømskog.no","roros.no","røros.no","rost.no","røst.no","royken.no","røyken.no","royrvik.no","røyrvik.no","rade.no","råde.no","salangen.no","siellak.no","saltdal.no","salat.no","sálát.no","sálat.no","samnanger.no","sande.more-og-romsdal.no","sande.møre-og-romsdal.no","sande.vestfold.no","sandefjord.no","sandnes.no","sandoy.no","sandøy.no","sarpsborg.no","sauda.no","sauherad.no","sel.no","selbu.no","selje.no","seljord.no","sigdal.no","siljan.no","sirdal.no","skaun.no","skedsmo.no","ski.no","skien.no","skiptvet.no","skjervoy.no","skjervøy.no","skierva.no","skiervá.no","skjak.no","skjåk.no","skodje.no","skanland.no","skånland.no","skanit.no","skánit.no","smola.no","smøla.no","snillfjord.no","snasa.no","snåsa.no","snoasa.no","snaase.no","snåase.no","sogndal.no","sokndal.no","sola.no","solund.no","songdalen.no","sortland.no","spydeberg.no","stange.no","stavanger.no","steigen.no","steinkjer.no","stjordal.no","stjørdal.no","stokke.no","stor-elvdal.no","stord.no","stordal.no","storfjord.no","omasvuotna.no","strand.no","stranda.no","stryn.no","sula.no","suldal.no","sund.no","sunndal.no","surnadal.no","sveio.no","svelvik.no","sykkylven.no","sogne.no","søgne.no","somna.no","sømna.no","sondre-land.no","søndre-land.no","sor-aurdal.no","sør-aurdal.no","sor-fron.no","sør-fron.no","sor-odal.no","sør-odal.no","sor-varanger.no","sør-varanger.no","matta-varjjat.no","mátta-várjjat.no","sorfold.no","sørfold.no","sorreisa.no","sørreisa.no","sorum.no","sørum.no","tana.no","deatnu.no","time.no","tingvoll.no","tinn.no","tjeldsund.no","dielddanuorri.no","tjome.no","tjøme.no","tokke.no","tolga.no","torsken.no","tranoy.no","tranøy.no","tromso.no","tromsø.no","tromsa.no","romsa.no","trondheim.no","troandin.no","trysil.no","trana.no","træna.no","trogstad.no","trøgstad.no","tvedestrand.no","tydal.no","tynset.no","tysfjord.no","divtasvuodna.no","divttasvuotna.no","tysnes.no","tysvar.no","tysvær.no","tonsberg.no","tønsberg.no","ullensaker.no","ullensvang.no","ulvik.no","utsira.no","vadso.no","vadsø.no","cahcesuolo.no","čáhcesuolo.no","vaksdal.no","valle.no","vang.no","vanylven.no","vardo.no","vardø.no","varggat.no","várggát.no","vefsn.no","vaapste.no","vega.no","vegarshei.no","vegårshei.no","vennesla.no","verdal.no","verran.no","vestby.no","vestnes.no","vestre-slidre.no","vestre-toten.no","vestvagoy.no","vestvågøy.no","vevelstad.no","vik.no","vikna.no","vindafjord.no","volda.no","voss.no","varoy.no","værøy.no","vagan.no","vågan.no","voagat.no","vagsoy.no","vågsøy.no","vaga.no","vågå.no","valer.ostfold.no","våler.østfold.no","valer.hedmark.no","våler.hedmark.no","*.np","nr","biz.nr","info.nr","gov.nr","edu.nr","org.nr","net.nr","com.nr","nu","nz","ac.nz","co.nz","cri.nz","geek.nz","gen.nz","govt.nz","health.nz","iwi.nz","kiwi.nz","maori.nz","mil.nz","māori.nz","net.nz","org.nz","parliament.nz","school.nz","om","co.om","com.om","edu.om","gov.om","med.om","museum.om","net.om","org.om","pro.om","onion","org","pa","ac.pa","gob.pa","com.pa","org.pa","sld.pa","edu.pa","net.pa","ing.pa","abo.pa","med.pa","nom.pa","pe","edu.pe","gob.pe","nom.pe","mil.pe","org.pe","com.pe","net.pe","pf","com.pf","org.pf","edu.pf","*.pg","ph","com.ph","net.ph","org.ph","gov.ph","edu.ph","ngo.ph","mil.ph","i.ph","pk","com.pk","net.pk","edu.pk","org.pk","fam.pk","biz.pk","web.pk","gov.pk","gob.pk","gok.pk","gon.pk","gop.pk","gos.pk","info.pk","pl","com.pl","net.pl","org.pl","aid.pl","agro.pl","atm.pl","auto.pl","biz.pl","edu.pl","gmina.pl","gsm.pl","info.pl","mail.pl","miasta.pl","media.pl","mil.pl","nieruchomosci.pl","nom.pl","pc.pl","powiat.pl","priv.pl","realestate.pl","rel.pl","sex.pl","shop.pl","sklep.pl","sos.pl","szkola.pl","targi.pl","tm.pl","tourism.pl","travel.pl","turystyka.pl","gov.pl","ap.gov.pl","ic.gov.pl","is.gov.pl","us.gov.pl","kmpsp.gov.pl","kppsp.gov.pl","kwpsp.gov.pl","psp.gov.pl","wskr.gov.pl","kwp.gov.pl","mw.gov.pl","ug.gov.pl","um.gov.pl","umig.gov.pl","ugim.gov.pl","upow.gov.pl","uw.gov.pl","starostwo.gov.pl","pa.gov.pl","po.gov.pl","psse.gov.pl","pup.gov.pl","rzgw.gov.pl","sa.gov.pl","so.gov.pl","sr.gov.pl","wsa.gov.pl","sko.gov.pl","uzs.gov.pl","wiih.gov.pl","winb.gov.pl","pinb.gov.pl","wios.gov.pl","witd.gov.pl","wzmiuw.gov.pl","piw.gov.pl","wiw.gov.pl","griw.gov.pl","wif.gov.pl","oum.gov.pl","sdn.gov.pl","zp.gov.pl","uppo.gov.pl","mup.gov.pl","wuoz.gov.pl","konsulat.gov.pl","oirm.gov.pl","augustow.pl","babia-gora.pl","bedzin.pl","beskidy.pl","bialowieza.pl","bialystok.pl","bielawa.pl","bieszczady.pl","boleslawiec.pl","bydgoszcz.pl","bytom.pl","cieszyn.pl","czeladz.pl","czest.pl","dlugoleka.pl","elblag.pl","elk.pl","glogow.pl","gniezno.pl","gorlice.pl","grajewo.pl","ilawa.pl","jaworzno.pl","jelenia-gora.pl","jgora.pl","kalisz.pl","kazimierz-dolny.pl","karpacz.pl","kartuzy.pl","kaszuby.pl","katowice.pl","kepno.pl","ketrzyn.pl","klodzko.pl","kobierzyce.pl","kolobrzeg.pl","konin.pl","konskowola.pl","kutno.pl","lapy.pl","lebork.pl","legnica.pl","lezajsk.pl","limanowa.pl","lomza.pl","lowicz.pl","lubin.pl","lukow.pl","malbork.pl","malopolska.pl","mazowsze.pl","mazury.pl","mielec.pl","mielno.pl","mragowo.pl","naklo.pl","nowaruda.pl","nysa.pl","olawa.pl","olecko.pl","olkusz.pl","olsztyn.pl","opoczno.pl","opole.pl","ostroda.pl","ostroleka.pl","ostrowiec.pl","ostrowwlkp.pl","pila.pl","pisz.pl","podhale.pl","podlasie.pl","polkowice.pl","pomorze.pl","pomorskie.pl","prochowice.pl","pruszkow.pl","przeworsk.pl","pulawy.pl","radom.pl","rawa-maz.pl","rybnik.pl","rzeszow.pl","sanok.pl","sejny.pl","slask.pl","slupsk.pl","sosnowiec.pl","stalowa-wola.pl","skoczow.pl","starachowice.pl","stargard.pl","suwalki.pl","swidnica.pl","swiebodzin.pl","swinoujscie.pl","szczecin.pl","szczytno.pl","tarnobrzeg.pl","tgory.pl","turek.pl","tychy.pl","ustka.pl","walbrzych.pl","warmia.pl","warszawa.pl","waw.pl","wegrow.pl","wielun.pl","wlocl.pl","wloclawek.pl","wodzislaw.pl","wolomin.pl","wroclaw.pl","zachpomor.pl","zagan.pl","zarow.pl","zgora.pl","zgorzelec.pl","pm","pn","gov.pn","co.pn","org.pn","edu.pn","net.pn","post","pr","com.pr","net.pr","org.pr","gov.pr","edu.pr","isla.pr","pro.pr","biz.pr","info.pr","name.pr","est.pr","prof.pr","ac.pr","pro","aaa.pro","aca.pro","acct.pro","avocat.pro","bar.pro","cpa.pro","eng.pro","jur.pro","law.pro","med.pro","recht.pro","ps","edu.ps","gov.ps","sec.ps","plo.ps","com.ps","org.ps","net.ps","pt","net.pt","gov.pt","org.pt","edu.pt","int.pt","publ.pt","com.pt","nome.pt","pw","co.pw","ne.pw","or.pw","ed.pw","go.pw","belau.pw","py","com.py","coop.py","edu.py","gov.py","mil.py","net.py","org.py","qa","com.qa","edu.qa","gov.qa","mil.qa","name.qa","net.qa","org.qa","sch.qa","re","asso.re","com.re","nom.re","ro","arts.ro","com.ro","firm.ro","info.ro","nom.ro","nt.ro","org.ro","rec.ro","store.ro","tm.ro","www.ro","rs","ac.rs","co.rs","edu.rs","gov.rs","in.rs","org.rs","ru","rw","ac.rw","co.rw","coop.rw","gov.rw","mil.rw","net.rw","org.rw","sa","com.sa","net.sa","org.sa","gov.sa","med.sa","pub.sa","edu.sa","sch.sa","sb","com.sb","edu.sb","gov.sb","net.sb","org.sb","sc","com.sc","gov.sc","net.sc","org.sc","edu.sc","sd","com.sd","net.sd","org.sd","edu.sd","med.sd","tv.sd","gov.sd","info.sd","se","a.se","ac.se","b.se","bd.se","brand.se","c.se","d.se","e.se","f.se","fh.se","fhsk.se","fhv.se","g.se","h.se","i.se","k.se","komforb.se","kommunalforbund.se","komvux.se","l.se","lanbib.se","m.se","n.se","naturbruksgymn.se","o.se","org.se","p.se","parti.se","pp.se","press.se","r.se","s.se","t.se","tm.se","u.se","w.se","x.se","y.se","z.se","sg","com.sg","net.sg","org.sg","gov.sg","edu.sg","per.sg","sh","com.sh","net.sh","gov.sh","org.sh","mil.sh","si","sj","sk","sl","com.sl","net.sl","edu.sl","gov.sl","org.sl","sm","sn","art.sn","com.sn","edu.sn","gouv.sn","org.sn","perso.sn","univ.sn","so","com.so","edu.so","gov.so","me.so","net.so","org.so","sr","ss","biz.ss","com.ss","edu.ss","gov.ss","net.ss","org.ss","st","co.st","com.st","consulado.st","edu.st","embaixada.st","gov.st","mil.st","net.st","org.st","principe.st","saotome.st","store.st","su","sv","com.sv","edu.sv","gob.sv","org.sv","red.sv","sx","gov.sx","sy","edu.sy","gov.sy","net.sy","mil.sy","com.sy","org.sy","sz","co.sz","ac.sz","org.sz","tc","td","tel","tf","tg","th","ac.th","co.th","go.th","in.th","mi.th","net.th","or.th","tj","ac.tj","biz.tj","co.tj","com.tj","edu.tj","go.tj","gov.tj","int.tj","mil.tj","name.tj","net.tj","nic.tj","org.tj","test.tj","web.tj","tk","tl","gov.tl","tm","com.tm","co.tm","org.tm","net.tm","nom.tm","gov.tm","mil.tm","edu.tm","tn","com.tn","ens.tn","fin.tn","gov.tn","ind.tn","intl.tn","nat.tn","net.tn","org.tn","info.tn","perso.tn","tourism.tn","edunet.tn","rnrt.tn","rns.tn","rnu.tn","mincom.tn","agrinet.tn","defense.tn","turen.tn","to","com.to","gov.to","net.to","org.to","edu.to","mil.to","tr","av.tr","bbs.tr","bel.tr","biz.tr","com.tr","dr.tr","edu.tr","gen.tr","gov.tr","info.tr","mil.tr","k12.tr","kep.tr","name.tr","net.tr","org.tr","pol.tr","tel.tr","tsk.tr","tv.tr","web.tr","nc.tr","gov.nc.tr","tt","co.tt","com.tt","org.tt","net.tt","biz.tt","info.tt","pro.tt","int.tt","coop.tt","jobs.tt","mobi.tt","travel.tt","museum.tt","aero.tt","name.tt","gov.tt","edu.tt","tv","tw","edu.tw","gov.tw","mil.tw","com.tw","net.tw","org.tw","idv.tw","game.tw","ebiz.tw","club.tw","網路.tw","組織.tw","商業.tw","tz","ac.tz","co.tz","go.tz","hotel.tz","info.tz","me.tz","mil.tz","mobi.tz","ne.tz","or.tz","sc.tz","tv.tz","ua","com.ua","edu.ua","gov.ua","in.ua","net.ua","org.ua","cherkassy.ua","cherkasy.ua","chernigov.ua","chernihiv.ua","chernivtsi.ua","chernovtsy.ua","ck.ua","cn.ua","cr.ua","crimea.ua","cv.ua","dn.ua","dnepropetrovsk.ua","dnipropetrovsk.ua","dominic.ua","donetsk.ua","dp.ua","if.ua","ivano-frankivsk.ua","kh.ua","kharkiv.ua","kharkov.ua","kherson.ua","khmelnitskiy.ua","khmelnytskyi.ua","kiev.ua","kirovograd.ua","km.ua","kr.ua","krym.ua","ks.ua","kv.ua","kyiv.ua","lg.ua","lt.ua","lugansk.ua","lutsk.ua","lv.ua","lviv.ua","mk.ua","mykolaiv.ua","nikolaev.ua","od.ua","odesa.ua","odessa.ua","pl.ua","poltava.ua","rivne.ua","rovno.ua","rv.ua","sb.ua","sebastopol.ua","sevastopol.ua","sm.ua","sumy.ua","te.ua","ternopil.ua","uz.ua","uzhgorod.ua","vinnica.ua","vinnytsia.ua","vn.ua","volyn.ua","yalta.ua","zaporizhzhe.ua","zaporizhzhia.ua","zhitomir.ua","zhytomyr.ua","zp.ua","zt.ua","ug","co.ug","or.ug","ac.ug","sc.ug","go.ug","ne.ug","com.ug","org.ug","uk","ac.uk","co.uk","gov.uk","ltd.uk","me.uk","net.uk","nhs.uk","org.uk","plc.uk","police.uk","*.sch.uk","us","dni.us","fed.us","isa.us","kids.us","nsn.us","ak.us","al.us","ar.us","as.us","az.us","ca.us","co.us","ct.us","dc.us","de.us","fl.us","ga.us","gu.us","hi.us","ia.us","id.us","il.us","in.us","ks.us","ky.us","la.us","ma.us","md.us","me.us","mi.us","mn.us","mo.us","ms.us","mt.us","nc.us","nd.us","ne.us","nh.us","nj.us","nm.us","nv.us","ny.us","oh.us","ok.us","or.us","pa.us","pr.us","ri.us","sc.us","sd.us","tn.us","tx.us","ut.us","vi.us","vt.us","va.us","wa.us","wi.us","wv.us","wy.us","k12.ak.us","k12.al.us","k12.ar.us","k12.as.us","k12.az.us","k12.ca.us","k12.co.us","k12.ct.us","k12.dc.us","k12.de.us","k12.fl.us","k12.ga.us","k12.gu.us","k12.ia.us","k12.id.us","k12.il.us","k12.in.us","k12.ks.us","k12.ky.us","k12.la.us","k12.ma.us","k12.md.us","k12.me.us","k12.mi.us","k12.mn.us","k12.mo.us","k12.ms.us","k12.mt.us","k12.nc.us","k12.ne.us","k12.nh.us","k12.nj.us","k12.nm.us","k12.nv.us","k12.ny.us","k12.oh.us","k12.ok.us","k12.or.us","k12.pa.us","k12.pr.us","k12.ri.us","k12.sc.us","k12.tn.us","k12.tx.us","k12.ut.us","k12.vi.us","k12.vt.us","k12.va.us","k12.wa.us","k12.wi.us","k12.wy.us","cc.ak.us","cc.al.us","cc.ar.us","cc.as.us","cc.az.us","cc.ca.us","cc.co.us","cc.ct.us","cc.dc.us","cc.de.us","cc.fl.us","cc.ga.us","cc.gu.us","cc.hi.us","cc.ia.us","cc.id.us","cc.il.us","cc.in.us","cc.ks.us","cc.ky.us","cc.la.us","cc.ma.us","cc.md.us","cc.me.us","cc.mi.us","cc.mn.us","cc.mo.us","cc.ms.us","cc.mt.us","cc.nc.us","cc.nd.us","cc.ne.us","cc.nh.us","cc.nj.us","cc.nm.us","cc.nv.us","cc.ny.us","cc.oh.us","cc.ok.us","cc.or.us","cc.pa.us","cc.pr.us","cc.ri.us","cc.sc.us","cc.sd.us","cc.tn.us","cc.tx.us","cc.ut.us","cc.vi.us","cc.vt.us","cc.va.us","cc.wa.us","cc.wi.us","cc.wv.us","cc.wy.us","lib.ak.us","lib.al.us","lib.ar.us","lib.as.us","lib.az.us","lib.ca.us","lib.co.us","lib.ct.us","lib.dc.us","lib.fl.us","lib.ga.us","lib.gu.us","lib.hi.us","lib.ia.us","lib.id.us","lib.il.us","lib.in.us","lib.ks.us","lib.ky.us","lib.la.us","lib.ma.us","lib.md.us","lib.me.us","lib.mi.us","lib.mn.us","lib.mo.us","lib.ms.us","lib.mt.us","lib.nc.us","lib.nd.us","lib.ne.us","lib.nh.us","lib.nj.us","lib.nm.us","lib.nv.us","lib.ny.us","lib.oh.us","lib.ok.us","lib.or.us","lib.pa.us","lib.pr.us","lib.ri.us","lib.sc.us","lib.sd.us","lib.tn.us","lib.tx.us","lib.ut.us","lib.vi.us","lib.vt.us","lib.va.us","lib.wa.us","lib.wi.us","lib.wy.us","pvt.k12.ma.us","chtr.k12.ma.us","paroch.k12.ma.us","ann-arbor.mi.us","cog.mi.us","dst.mi.us","eaton.mi.us","gen.mi.us","mus.mi.us","tec.mi.us","washtenaw.mi.us","uy","com.uy","edu.uy","gub.uy","mil.uy","net.uy","org.uy","uz","co.uz","com.uz","net.uz","org.uz","va","vc","com.vc","net.vc","org.vc","gov.vc","mil.vc","edu.vc","ve","arts.ve","co.ve","com.ve","e12.ve","edu.ve","firm.ve","gob.ve","gov.ve","info.ve","int.ve","mil.ve","net.ve","org.ve","rec.ve","store.ve","tec.ve","web.ve","vg","vi","co.vi","com.vi","k12.vi","net.vi","org.vi","vn","com.vn","net.vn","org.vn","edu.vn","gov.vn","int.vn","ac.vn","biz.vn","info.vn","name.vn","pro.vn","health.vn","vu","com.vu","edu.vu","net.vu","org.vu","wf","ws","com.ws","net.ws","org.ws","gov.ws","edu.ws","yt","امارات","հայ","বাংলা","бг","бел","中国","中國","الجزائر","مصر","ею","موريتانيا","გე","ελ","香港","公司.香港","教育.香港","政府.香港","個人.香港","網絡.香港","組織.香港","ಭಾರತ","ଭାରତ","ভাৰত","भारतम्","भारोत","ڀارت","ഭാരതം","भारत","بارت","بھارت","భారత్","ભારત","ਭਾਰਤ","ভারত","இந்தியா","ایران","ايران","عراق","الاردن","한국","қаз","ලංකා","இலங்கை","المغرب","мкд","мон","澳門","澳门","مليسيا","عمان","پاکستان","پاكستان","فلسطين","срб","пр.срб","орг.срб","обр.срб","од.срб","упр.срб","ак.срб","рф","قطر","السعودية","السعودیة","السعودیۃ","السعوديه","سودان","新加坡","சிங்கப்பூர்","سورية","سوريا","ไทย","ศึกษา.ไทย","ธุรกิจ.ไทย","รัฐบาล.ไทย","ทหาร.ไทย","เน็ต.ไทย","องค์กร.ไทย","تونس","台灣","台湾","臺灣","укр","اليمن","xxx","*.ye","ac.za","agric.za","alt.za","co.za","edu.za","gov.za","grondar.za","law.za","mil.za","net.za","ngo.za","nic.za","nis.za","nom.za","org.za","school.za","tm.za","web.za","zm","ac.zm","biz.zm","co.zm","com.zm","edu.zm","gov.zm","info.zm","mil.zm","net.zm","org.zm","sch.zm","zw","ac.zw","co.zw","gov.zw","mil.zw","org.zw","aaa","aarp","abarth","abb","abbott","abbvie","abc","able","abogado","abudhabi","academy","accenture","accountant","accountants","aco","actor","adac","ads","adult","aeg","aetna","afamilycompany","afl","africa","agakhan","agency","aig","aigo","airbus","airforce","airtel","akdn","alfaromeo","alibaba","alipay","allfinanz","allstate","ally","alsace","alstom","amazon","americanexpress","americanfamily","amex","amfam","amica","amsterdam","analytics","android","anquan","anz","aol","apartments","app","apple","aquarelle","arab","aramco","archi","army","art","arte","asda","associates","athleta","attorney","auction","audi","audible","audio","auspost","author","auto","autos","avianca","aws","axa","azure","baby","baidu","banamex","bananarepublic","band","bank","bar","barcelona","barclaycard","barclays","barefoot","bargains","baseball","basketball","bauhaus","bayern","bbc","bbt","bbva","bcg","bcn","beats","beauty","beer","bentley","berlin","best","bestbuy","bet","bharti","bible","bid","bike","bing","bingo","bio","black","blackfriday","blockbuster","blog","bloomberg","blue","bms","bmw","bnpparibas","boats","boehringer","bofa","bom","bond","boo","book","booking","bosch","bostik","boston","bot","boutique","box","bradesco","bridgestone","broadway","broker","brother","brussels","budapest","bugatti","build","builders","business","buy","buzz","bzh","cab","cafe","cal","call","calvinklein","cam","camera","camp","cancerresearch","canon","capetown","capital","capitalone","car","caravan","cards","care","career","careers","cars","casa","case","caseih","cash","casino","catering","catholic","cba","cbn","cbre","cbs","ceb","center","ceo","cern","cfa","cfd","chanel","channel","charity","chase","chat","cheap","chintai","christmas","chrome","church","cipriani","circle","cisco","citadel","citi","citic","city","cityeats","claims","cleaning","click","clinic","clinique","clothing","cloud","club","clubmed","coach","codes","coffee","college","cologne","comcast","commbank","community","company","compare","computer","comsec","condos","construction","consulting","contact","contractors","cooking","cookingchannel","cool","corsica","country","coupon","coupons","courses","cpa","credit","creditcard","creditunion","cricket","crown","crs","cruise","cruises","csc","cuisinella","cymru","cyou","dabur","dad","dance","data","date","dating","datsun","day","dclk","dds","deal","dealer","deals","degree","delivery","dell","deloitte","delta","democrat","dental","dentist","desi","design","dev","dhl","diamonds","diet","digital","direct","directory","discount","discover","dish","diy","dnp","docs","doctor","dog","domains","dot","download","drive","dtv","dubai","duck","dunlop","dupont","durban","dvag","dvr","earth","eat","eco","edeka","education","email","emerck","energy","engineer","engineering","enterprises","epson","equipment","ericsson","erni","esq","estate","esurance","etisalat","eurovision","eus","events","exchange","expert","exposed","express","extraspace","fage","fail","fairwinds","faith","family","fan","fans","farm","farmers","fashion","fast","fedex","feedback","ferrari","ferrero","fiat","fidelity","fido","film","final","finance","financial","fire","firestone","firmdale","fish","fishing","fit","fitness","flickr","flights","flir","florist","flowers","fly","foo","food","foodnetwork","football","ford","forex","forsale","forum","foundation","fox","free","fresenius","frl","frogans","frontdoor","frontier","ftr","fujitsu","fujixerox","fun","fund","furniture","futbol","fyi","gal","gallery","gallo","gallup","game","games","gap","garden","gay","gbiz","gdn","gea","gent","genting","george","ggee","gift","gifts","gives","giving","glade","glass","gle","global","globo","gmail","gmbh","gmo","gmx","godaddy","gold","goldpoint","golf","goo","goodyear","goog","google","gop","got","grainger","graphics","gratis","green","gripe","grocery","group","guardian","gucci","guge","guide","guitars","guru","hair","hamburg","hangout","haus","hbo","hdfc","hdfcbank","health","healthcare","help","helsinki","here","hermes","hgtv","hiphop","hisamitsu","hitachi","hiv","hkt","hockey","holdings","holiday","homedepot","homegoods","homes","homesense","honda","horse","hospital","host","hosting","hot","hoteles","hotels","hotmail","house","how","hsbc","hughes","hyatt","hyundai","ibm","icbc","ice","icu","ieee","ifm","ikano","imamat","imdb","immo","immobilien","inc","industries","infiniti","ing","ink","institute","insurance","insure","intel","international","intuit","investments","ipiranga","irish","ismaili","ist","istanbul","itau","itv","iveco","jaguar","java","jcb","jcp","jeep","jetzt","jewelry","jio","jll","jmp","jnj","joburg","jot","joy","jpmorgan","jprs","juegos","juniper","kaufen","kddi","kerryhotels","kerrylogistics","kerryproperties","kfh","kia","kim","kinder","kindle","kitchen","kiwi","koeln","komatsu","kosher","kpmg","kpn","krd","kred","kuokgroup","kyoto","lacaixa","lamborghini","lamer","lancaster","lancia","land","landrover","lanxess","lasalle","lat","latino","latrobe","law","lawyer","lds","lease","leclerc","lefrak","legal","lego","lexus","lgbt","liaison","lidl","life","lifeinsurance","lifestyle","lighting","like","lilly","limited","limo","lincoln","linde","link","lipsy","live","living","lixil","llc","llp","loan","loans","locker","locus","loft","lol","london","lotte","lotto","love","lpl","lplfinancial","ltd","ltda","lundbeck","lupin","luxe","luxury","macys","madrid","maif","maison","makeup","man","management","mango","map","market","marketing","markets","marriott","marshalls","maserati","mattel","mba","mckinsey","med","media","meet","melbourne","meme","memorial","men","menu","merckmsd","metlife","miami","microsoft","mini","mint","mit","mitsubishi","mlb","mls","mma","mobile","moda","moe","moi","mom","monash","money","monster","mormon","mortgage","moscow","moto","motorcycles","mov","movie","msd","mtn","mtr","mutual","nab","nadex","nagoya","nationwide","natura","navy","nba","nec","netbank","netflix","network","neustar","new","newholland","news","next","nextdirect","nexus","nfl","ngo","nhk","nico","nike","nikon","ninja","nissan","nissay","nokia","northwesternmutual","norton","now","nowruz","nowtv","nra","nrw","ntt","nyc","obi","observer","off","office","okinawa","olayan","olayangroup","oldnavy","ollo","omega","one","ong","onl","online","onyourside","ooo","open","oracle","orange","organic","origins","osaka","otsuka","ott","ovh","page","panasonic","paris","pars","partners","parts","party","passagens","pay","pccw","pet","pfizer","pharmacy","phd","philips","phone","photo","photography","photos","physio","pics","pictet","pictures","pid","pin","ping","pink","pioneer","pizza","place","play","playstation","plumbing","plus","pnc","pohl","poker","politie","porn","pramerica","praxi","press","prime","prod","productions","prof","progressive","promo","properties","property","protection","pru","prudential","pub","pwc","qpon","quebec","quest","qvc","racing","radio","raid","read","realestate","realtor","realty","recipes","red","redstone","redumbrella","rehab","reise","reisen","reit","reliance","ren","rent","rentals","repair","report","republican","rest","restaurant","review","reviews","rexroth","rich","richardli","ricoh","rightathome","ril","rio","rip","rmit","rocher","rocks","rodeo","rogers","room","rsvp","rugby","ruhr","run","rwe","ryukyu","saarland","safe","safety","sakura","sale","salon","samsclub","samsung","sandvik","sandvikcoromant","sanofi","sap","sarl","sas","save","saxo","sbi","sbs","sca","scb","schaeffler","schmidt","scholarships","school","schule","schwarz","science","scjohnson","scor","scot","search","seat","secure","security","seek","select","sener","services","ses","seven","sew","sex","sexy","sfr","shangrila","sharp","shaw","shell","shia","shiksha","shoes","shop","shopping","shouji","show","showtime","shriram","silk","sina","singles","site","ski","skin","sky","skype","sling","smart","smile","sncf","soccer","social","softbank","software","sohu","solar","solutions","song","sony","soy","spa","space","sport","spot","spreadbetting","srl","stada","staples","star","statebank","statefarm","stc","stcgroup","stockholm","storage","store","stream","studio","study","style","sucks","supplies","supply","support","surf","surgery","suzuki","swatch","swiftcover","swiss","sydney","symantec","systems","tab","taipei","talk","taobao","target","tatamotors","tatar","tattoo","tax","taxi","tci","tdk","team","tech","technology","temasek","tennis","teva","thd","theater","theatre","tiaa","tickets","tienda","tiffany","tips","tires","tirol","tjmaxx","tjx","tkmaxx","tmall","today","tokyo","tools","top","toray","toshiba","total","tours","town","toyota","toys","trade","trading","training","travel","travelchannel","travelers","travelersinsurance","trust","trv","tube","tui","tunes","tushu","tvs","ubank","ubs","unicom","university","uno","uol","ups","vacations","vana","vanguard","vegas","ventures","verisign","versicherung","vet","viajes","video","vig","viking","villas","vin","vip","virgin","visa","vision","vistaprint","viva","vivo","vlaanderen","vodka","volkswagen","volvo","vote","voting","voto","voyage","vuelos","wales","walmart","walter","wang","wanggou","watch","watches","weather","weatherchannel","webcam","weber","website","wed","wedding","weibo","weir","whoswho","wien","wiki","williamhill","win","windows","wine","winners","wme","wolterskluwer","woodside","work","works","world","wow","wtc","wtf","xbox","xerox","xfinity","xihuan","xin","कॉम","セール","佛山","慈善","集团","在线","大众汽车","点看","คอม","八卦","موقع","公益","公司","香格里拉","网站","移动","我爱你","москва","католик","онлайн","сайт","联通","קום","时尚","微博","淡马锡","ファッション","орг","नेट","ストア","アマゾン","삼성","商标","商店","商城","дети","ポイント","新闻","工行","家電","كوم","中文网","中信","娱乐","谷歌","電訊盈科","购物","クラウド","通販","网店","संगठन","餐厅","网络","ком","亚马逊","诺基亚","食品","飞利浦","手表","手机","ارامكو","العليان","اتصالات","بازار","ابوظبي","كاثوليك","همراه","닷컴","政府","شبكة","بيتك","عرب","机构","组织机构","健康","招聘","рус","珠宝","大拿","みんな","グーグル","世界","書籍","网址","닷넷","コム","天主教","游戏","vermögensberater","vermögensberatung","企业","信息","嘉里大酒店","嘉里","广东","政务","xyz","yachts","yahoo","yamaxun","yandex","yodobashi","yoga","yokohama","you","youtube","yun","zappos","zara","zero","zip","zone","zuerich","cc.ua","inf.ua","ltd.ua","adobeaemcloud.com","adobeaemcloud.net","*.dev.adobeaemcloud.com","beep.pl","barsy.ca","*.compute.estate","*.alces.network","altervista.org","alwaysdata.net","cloudfront.net","*.compute.amazonaws.com","*.compute-1.amazonaws.com","*.compute.amazonaws.com.cn","us-east-1.amazonaws.com","cn-north-1.eb.amazonaws.com.cn","cn-northwest-1.eb.amazonaws.com.cn","elasticbeanstalk.com","ap-northeast-1.elasticbeanstalk.com","ap-northeast-2.elasticbeanstalk.com","ap-northeast-3.elasticbeanstalk.com","ap-south-1.elasticbeanstalk.com","ap-southeast-1.elasticbeanstalk.com","ap-southeast-2.elasticbeanstalk.com","ca-central-1.elasticbeanstalk.com","eu-central-1.elasticbeanstalk.com","eu-west-1.elasticbeanstalk.com","eu-west-2.elasticbeanstalk.com","eu-west-3.elasticbeanstalk.com","sa-east-1.elasticbeanstalk.com","us-east-1.elasticbeanstalk.com","us-east-2.elasticbeanstalk.com","us-gov-west-1.elasticbeanstalk.com","us-west-1.elasticbeanstalk.com","us-west-2.elasticbeanstalk.com","*.elb.amazonaws.com","*.elb.amazonaws.com.cn","s3.amazonaws.com","s3-ap-northeast-1.amazonaws.com","s3-ap-northeast-2.amazonaws.com","s3-ap-south-1.amazonaws.com","s3-ap-southeast-1.amazonaws.com","s3-ap-southeast-2.amazonaws.com","s3-ca-central-1.amazonaws.com","s3-eu-central-1.amazonaws.com","s3-eu-west-1.amazonaws.com","s3-eu-west-2.amazonaws.com","s3-eu-west-3.amazonaws.com","s3-external-1.amazonaws.com","s3-fips-us-gov-west-1.amazonaws.com","s3-sa-east-1.amazonaws.com","s3-us-gov-west-1.amazonaws.com","s3-us-east-2.amazonaws.com","s3-us-west-1.amazonaws.com","s3-us-west-2.amazonaws.com","s3.ap-northeast-2.amazonaws.com","s3.ap-south-1.amazonaws.com","s3.cn-north-1.amazonaws.com.cn","s3.ca-central-1.amazonaws.com","s3.eu-central-1.amazonaws.com","s3.eu-west-2.amazonaws.com","s3.eu-west-3.amazonaws.com","s3.us-east-2.amazonaws.com","s3.dualstack.ap-northeast-1.amazonaws.com","s3.dualstack.ap-northeast-2.amazonaws.com","s3.dualstack.ap-south-1.amazonaws.com","s3.dualstack.ap-southeast-1.amazonaws.com","s3.dualstack.ap-southeast-2.amazonaws.com","s3.dualstack.ca-central-1.amazonaws.com","s3.dualstack.eu-central-1.amazonaws.com","s3.dualstack.eu-west-1.amazonaws.com","s3.dualstack.eu-west-2.amazonaws.com","s3.dualstack.eu-west-3.amazonaws.com","s3.dualstack.sa-east-1.amazonaws.com","s3.dualstack.us-east-1.amazonaws.com","s3.dualstack.us-east-2.amazonaws.com","s3-website-us-east-1.amazonaws.com","s3-website-us-west-1.amazonaws.com","s3-website-us-west-2.amazonaws.com","s3-website-ap-northeast-1.amazonaws.com","s3-website-ap-southeast-1.amazonaws.com","s3-website-ap-southeast-2.amazonaws.com","s3-website-eu-west-1.amazonaws.com","s3-website-sa-east-1.amazonaws.com","s3-website.ap-northeast-2.amazonaws.com","s3-website.ap-south-1.amazonaws.com","s3-website.ca-central-1.amazonaws.com","s3-website.eu-central-1.amazonaws.com","s3-website.eu-west-2.amazonaws.com","s3-website.eu-west-3.amazonaws.com","s3-website.us-east-2.amazonaws.com","amsw.nl","t3l3p0rt.net","tele.amune.org","apigee.io","on-aptible.com","user.aseinet.ne.jp","gv.vc","d.gv.vc","user.party.eus","pimienta.org","poivron.org","potager.org","sweetpepper.org","myasustor.com","myfritz.net","*.awdev.ca","*.advisor.ws","b-data.io","backplaneapp.io","balena-devices.com","app.banzaicloud.io","betainabox.com","bnr.la","blackbaudcdn.net","boomla.net","boxfuse.io","square7.ch","bplaced.com","bplaced.de","square7.de","bplaced.net","square7.net","browsersafetymark.io","uk0.bigv.io","dh.bytemark.co.uk","vm.bytemark.co.uk","mycd.eu","carrd.co","crd.co","uwu.ai","ae.org","ar.com","br.com","cn.com","com.de","com.se","de.com","eu.com","gb.com","gb.net","hu.com","hu.net","jp.net","jpn.com","kr.com","mex.com","no.com","qc.com","ru.com","sa.com","se.net","uk.com","uk.net","us.com","uy.com","za.bz","za.com","africa.com","gr.com","in.net","us.org","co.com","c.la","certmgr.org","xenapponazure.com","discourse.group","virtueeldomein.nl","cleverapps.io","*.lcl.dev","*.stg.dev","c66.me","cloud66.ws","cloud66.zone","jdevcloud.com","wpdevcloud.com","cloudaccess.host","freesite.host","cloudaccess.net","cloudcontrolled.com","cloudcontrolapp.com","cloudera.site","trycloudflare.com","workers.dev","wnext.app","co.ca","*.otap.co","co.cz","c.cdn77.org","cdn77-ssl.net","r.cdn77.net","rsc.cdn77.org","ssl.origin.cdn77-secure.org","cloudns.asia","cloudns.biz","cloudns.club","cloudns.cc","cloudns.eu","cloudns.in","cloudns.info","cloudns.org","cloudns.pro","cloudns.pw","cloudns.us","cloudeity.net","cnpy.gdn","co.nl","co.no","webhosting.be","hosting-cluster.nl","ac.ru","edu.ru","gov.ru","int.ru","mil.ru","test.ru","dyn.cosidns.de","dynamisches-dns.de","dnsupdater.de","internet-dns.de","l-o-g-i-n.de","dynamic-dns.info","feste-ip.net","knx-server.net","static-access.net","realm.cz","*.cryptonomic.net","cupcake.is","*.customer-oci.com","*.oci.customer-oci.com","*.ocp.customer-oci.com","*.ocs.customer-oci.com","cyon.link","cyon.site","daplie.me","localhost.daplie.me","dattolocal.com","dattorelay.com","dattoweb.com","mydatto.com","dattolocal.net","mydatto.net","biz.dk","co.dk","firm.dk","reg.dk","store.dk","*.dapps.earth","*.bzz.dapps.earth","builtwithdark.com","edgestack.me","debian.net","dedyn.io","dnshome.de","online.th","shop.th","drayddns.com","dreamhosters.com","mydrobo.com","drud.io","drud.us","duckdns.org","dy.fi","tunk.org","dyndns-at-home.com","dyndns-at-work.com","dyndns-blog.com","dyndns-free.com","dyndns-home.com","dyndns-ip.com","dyndns-mail.com","dyndns-office.com","dyndns-pics.com","dyndns-remote.com","dyndns-server.com","dyndns-web.com","dyndns-wiki.com","dyndns-work.com","dyndns.biz","dyndns.info","dyndns.org","dyndns.tv","at-band-camp.net","ath.cx","barrel-of-knowledge.info","barrell-of-knowledge.info","better-than.tv","blogdns.com","blogdns.net","blogdns.org","blogsite.org","boldlygoingnowhere.org","broke-it.net","buyshouses.net","cechire.com","dnsalias.com","dnsalias.net","dnsalias.org","dnsdojo.com","dnsdojo.net","dnsdojo.org","does-it.net","doesntexist.com","doesntexist.org","dontexist.com","dontexist.net","dontexist.org","doomdns.com","doomdns.org","dvrdns.org","dyn-o-saur.com","dynalias.com","dynalias.net","dynalias.org","dynathome.net","dyndns.ws","endofinternet.net","endofinternet.org","endoftheinternet.org","est-a-la-maison.com","est-a-la-masion.com","est-le-patron.com","est-mon-blogueur.com","for-better.biz","for-more.biz","for-our.info","for-some.biz","for-the.biz","forgot.her.name","forgot.his.name","from-ak.com","from-al.com","from-ar.com","from-az.net","from-ca.com","from-co.net","from-ct.com","from-dc.com","from-de.com","from-fl.com","from-ga.com","from-hi.com","from-ia.com","from-id.com","from-il.com","from-in.com","from-ks.com","from-ky.com","from-la.net","from-ma.com","from-md.com","from-me.org","from-mi.com","from-mn.com","from-mo.com","from-ms.com","from-mt.com","from-nc.com","from-nd.com","from-ne.com","from-nh.com","from-nj.com","from-nm.com","from-nv.com","from-ny.net","from-oh.com","from-ok.com","from-or.com","from-pa.com","from-pr.com","from-ri.com","from-sc.com","from-sd.com","from-tn.com","from-tx.com","from-ut.com","from-va.com","from-vt.com","from-wa.com","from-wi.com","from-wv.com","from-wy.com","ftpaccess.cc","fuettertdasnetz.de","game-host.org","game-server.cc","getmyip.com","gets-it.net","go.dyndns.org","gotdns.com","gotdns.org","groks-the.info","groks-this.info","ham-radio-op.net","here-for-more.info","hobby-site.com","hobby-site.org","home.dyndns.org","homedns.org","homeftp.net","homeftp.org","homeip.net","homelinux.com","homelinux.net","homelinux.org","homeunix.com","homeunix.net","homeunix.org","iamallama.com","in-the-band.net","is-a-anarchist.com","is-a-blogger.com","is-a-bookkeeper.com","is-a-bruinsfan.org","is-a-bulls-fan.com","is-a-candidate.org","is-a-caterer.com","is-a-celticsfan.org","is-a-chef.com","is-a-chef.net","is-a-chef.org","is-a-conservative.com","is-a-cpa.com","is-a-cubicle-slave.com","is-a-democrat.com","is-a-designer.com","is-a-doctor.com","is-a-financialadvisor.com","is-a-geek.com","is-a-geek.net","is-a-geek.org","is-a-green.com","is-a-guru.com","is-a-hard-worker.com","is-a-hunter.com","is-a-knight.org","is-a-landscaper.com","is-a-lawyer.com","is-a-liberal.com","is-a-libertarian.com","is-a-linux-user.org","is-a-llama.com","is-a-musician.com","is-a-nascarfan.com","is-a-nurse.com","is-a-painter.com","is-a-patsfan.org","is-a-personaltrainer.com","is-a-photographer.com","is-a-player.com","is-a-republican.com","is-a-rockstar.com","is-a-socialist.com","is-a-soxfan.org","is-a-student.com","is-a-teacher.com","is-a-techie.com","is-a-therapist.com","is-an-accountant.com","is-an-actor.com","is-an-actress.com","is-an-anarchist.com","is-an-artist.com","is-an-engineer.com","is-an-entertainer.com","is-by.us","is-certified.com","is-found.org","is-gone.com","is-into-anime.com","is-into-cars.com","is-into-cartoons.com","is-into-games.com","is-leet.com","is-lost.org","is-not-certified.com","is-saved.org","is-slick.com","is-uberleet.com","is-very-bad.org","is-very-evil.org","is-very-good.org","is-very-nice.org","is-very-sweet.org","is-with-theband.com","isa-geek.com","isa-geek.net","isa-geek.org","isa-hockeynut.com","issmarterthanyou.com","isteingeek.de","istmein.de","kicks-ass.net","kicks-ass.org","knowsitall.info","land-4-sale.us","lebtimnetz.de","leitungsen.de","likes-pie.com","likescandy.com","merseine.nu","mine.nu","misconfused.org","mypets.ws","myphotos.cc","neat-url.com","office-on-the.net","on-the-web.tv","podzone.net","podzone.org","readmyblog.org","saves-the-whales.com","scrapper-site.net","scrapping.cc","selfip.biz","selfip.com","selfip.info","selfip.net","selfip.org","sells-for-less.com","sells-for-u.com","sells-it.net","sellsyourhome.org","servebbs.com","servebbs.net","servebbs.org","serveftp.net","serveftp.org","servegame.org","shacknet.nu","simple-url.com","space-to-rent.com","stuff-4-sale.org","stuff-4-sale.us","teaches-yoga.com","thruhere.net","traeumtgerade.de","webhop.biz","webhop.info","webhop.net","webhop.org","worse-than.tv","writesthisblog.com","ddnss.de","dyn.ddnss.de","dyndns.ddnss.de","dyndns1.de","dyn-ip24.de","home-webserver.de","dyn.home-webserver.de","myhome-server.de","ddnss.org","definima.net","definima.io","bci.dnstrace.pro","ddnsfree.com","ddnsgeek.com","giize.com","gleeze.com","kozow.com","loseyourip.com","ooguy.com","theworkpc.com","casacam.net","dynu.net","accesscam.org","camdvr.org","freeddns.org","mywire.org","webredirect.org","myddns.rocks","blogsite.xyz","dynv6.net","e4.cz","en-root.fr","mytuleap.com","onred.one","staging.onred.one","enonic.io","customer.enonic.io","eu.org","al.eu.org","asso.eu.org","at.eu.org","au.eu.org","be.eu.org","bg.eu.org","ca.eu.org","cd.eu.org","ch.eu.org","cn.eu.org","cy.eu.org","cz.eu.org","de.eu.org","dk.eu.org","edu.eu.org","ee.eu.org","es.eu.org","fi.eu.org","fr.eu.org","gr.eu.org","hr.eu.org","hu.eu.org","ie.eu.org","il.eu.org","in.eu.org","int.eu.org","is.eu.org","it.eu.org","jp.eu.org","kr.eu.org","lt.eu.org","lu.eu.org","lv.eu.org","mc.eu.org","me.eu.org","mk.eu.org","mt.eu.org","my.eu.org","net.eu.org","ng.eu.org","nl.eu.org","no.eu.org","nz.eu.org","paris.eu.org","pl.eu.org","pt.eu.org","q-a.eu.org","ro.eu.org","ru.eu.org","se.eu.org","si.eu.org","sk.eu.org","tr.eu.org","uk.eu.org","us.eu.org","eu-1.evennode.com","eu-2.evennode.com","eu-3.evennode.com","eu-4.evennode.com","us-1.evennode.com","us-2.evennode.com","us-3.evennode.com","us-4.evennode.com","twmail.cc","twmail.net","twmail.org","mymailer.com.tw","url.tw","apps.fbsbx.com","ru.net","adygeya.ru","bashkiria.ru","bir.ru","cbg.ru","com.ru","dagestan.ru","grozny.ru","kalmykia.ru","kustanai.ru","marine.ru","mordovia.ru","msk.ru","mytis.ru","nalchik.ru","nov.ru","pyatigorsk.ru","spb.ru","vladikavkaz.ru","vladimir.ru","abkhazia.su","adygeya.su","aktyubinsk.su","arkhangelsk.su","armenia.su","ashgabad.su","azerbaijan.su","balashov.su","bashkiria.su","bryansk.su","bukhara.su","chimkent.su","dagestan.su","east-kazakhstan.su","exnet.su","georgia.su","grozny.su","ivanovo.su","jambyl.su","kalmykia.su","kaluga.su","karacol.su","karaganda.su","karelia.su","khakassia.su","krasnodar.su","kurgan.su","kustanai.su","lenug.su","mangyshlak.su","mordovia.su","msk.su","murmansk.su","nalchik.su","navoi.su","north-kazakhstan.su","nov.su","obninsk.su","penza.su","pokrovsk.su","sochi.su","spb.su","tashkent.su","termez.su","togliatti.su","troitsk.su","tselinograd.su","tula.su","tuva.su","vladikavkaz.su","vladimir.su","vologda.su","channelsdvr.net","fastly-terrarium.com","fastlylb.net","map.fastlylb.net","freetls.fastly.net","map.fastly.net","a.prod.fastly.net","global.prod.fastly.net","a.ssl.fastly.net","b.ssl.fastly.net","global.ssl.fastly.net","fastpanel.direct","fastvps-server.com","fhapp.xyz","fedorainfracloud.org","fedorapeople.org","cloud.fedoraproject.org","app.os.fedoraproject.org","app.os.stg.fedoraproject.org","mydobiss.com","filegear.me","filegear-au.me","filegear-de.me","filegear-gb.me","filegear-ie.me","filegear-jp.me","filegear-sg.me","firebaseapp.com","flynnhub.com","flynnhosting.net","0e.vc","freebox-os.com","freeboxos.com","fbx-os.fr","fbxos.fr","freebox-os.fr","freeboxos.fr","freedesktop.org","*.futurecms.at","*.ex.futurecms.at","*.in.futurecms.at","futurehosting.at","futuremailing.at","*.ex.ortsinfo.at","*.kunden.ortsinfo.at","*.statics.cloud","service.gov.uk","gehirn.ne.jp","usercontent.jp","gentapps.com","lab.ms","github.io","githubusercontent.com","gitlab.io","glitch.me","lolipop.io","cloudapps.digital","london.cloudapps.digital","homeoffice.gov.uk","ro.im","shop.ro","goip.de","run.app","a.run.app","web.app","*.0emm.com","appspot.com","*.r.appspot.com","blogspot.ae","blogspot.al","blogspot.am","blogspot.ba","blogspot.be","blogspot.bg","blogspot.bj","blogspot.ca","blogspot.cf","blogspot.ch","blogspot.cl","blogspot.co.at","blogspot.co.id","blogspot.co.il","blogspot.co.ke","blogspot.co.nz","blogspot.co.uk","blogspot.co.za","blogspot.com","blogspot.com.ar","blogspot.com.au","blogspot.com.br","blogspot.com.by","blogspot.com.co","blogspot.com.cy","blogspot.com.ee","blogspot.com.eg","blogspot.com.es","blogspot.com.mt","blogspot.com.ng","blogspot.com.tr","blogspot.com.uy","blogspot.cv","blogspot.cz","blogspot.de","blogspot.dk","blogspot.fi","blogspot.fr","blogspot.gr","blogspot.hk","blogspot.hr","blogspot.hu","blogspot.ie","blogspot.in","blogspot.is","blogspot.it","blogspot.jp","blogspot.kr","blogspot.li","blogspot.lt","blogspot.lu","blogspot.md","blogspot.mk","blogspot.mr","blogspot.mx","blogspot.my","blogspot.nl","blogspot.no","blogspot.pe","blogspot.pt","blogspot.qa","blogspot.re","blogspot.ro","blogspot.rs","blogspot.ru","blogspot.se","blogspot.sg","blogspot.si","blogspot.sk","blogspot.sn","blogspot.td","blogspot.tw","blogspot.ug","blogspot.vn","cloudfunctions.net","cloud.goog","codespot.com","googleapis.com","googlecode.com","pagespeedmobilizer.com","publishproxy.com","withgoogle.com","withyoutube.com","awsmppl.com","fin.ci","free.hr","caa.li","ua.rs","conf.se","hs.zone","hs.run","hashbang.sh","hasura.app","hasura-app.io","hepforge.org","herokuapp.com","herokussl.com","myravendb.com","ravendb.community","ravendb.me","development.run","ravendb.run","bpl.biz","orx.biz","ng.city","biz.gl","ng.ink","col.ng","firm.ng","gen.ng","ltd.ng","ngo.ng","ng.school","sch.so","häkkinen.fi","*.moonscale.io","moonscale.net","iki.fi","dyn-berlin.de","in-berlin.de","in-brb.de","in-butter.de","in-dsl.de","in-dsl.net","in-dsl.org","in-vpn.de","in-vpn.net","in-vpn.org","biz.at","info.at","info.cx","ac.leg.br","al.leg.br","am.leg.br","ap.leg.br","ba.leg.br","ce.leg.br","df.leg.br","es.leg.br","go.leg.br","ma.leg.br","mg.leg.br","ms.leg.br","mt.leg.br","pa.leg.br","pb.leg.br","pe.leg.br","pi.leg.br","pr.leg.br","rj.leg.br","rn.leg.br","ro.leg.br","rr.leg.br","rs.leg.br","sc.leg.br","se.leg.br","sp.leg.br","to.leg.br","pixolino.com","ipifony.net","mein-iserv.de","test-iserv.de","iserv.dev","iobb.net","myjino.ru","*.hosting.myjino.ru","*.landing.myjino.ru","*.spectrum.myjino.ru","*.vps.myjino.ru","*.triton.zone","*.cns.joyent.com","js.org","kaas.gg","khplay.nl","keymachine.de","kinghost.net","uni5.net","knightpoint.systems","oya.to","co.krd","edu.krd","git-repos.de","lcube-server.de","svn-repos.de","leadpages.co","lpages.co","lpusercontent.com","lelux.site","co.business","co.education","co.events","co.financial","co.network","co.place","co.technology","app.lmpm.com","linkitools.space","linkyard.cloud","linkyard-cloud.ch","members.linode.com","nodebalancer.linode.com","we.bs","loginline.app","loginline.dev","loginline.io","loginline.services","loginline.site","krasnik.pl","leczna.pl","lubartow.pl","lublin.pl","poniatowa.pl","swidnik.pl","uklugs.org","glug.org.uk","lug.org.uk","lugs.org.uk","barsy.bg","barsy.co.uk","barsyonline.co.uk","barsycenter.com","barsyonline.com","barsy.club","barsy.de","barsy.eu","barsy.in","barsy.info","barsy.io","barsy.me","barsy.menu","barsy.mobi","barsy.net","barsy.online","barsy.org","barsy.pro","barsy.pub","barsy.shop","barsy.site","barsy.support","barsy.uk","*.magentosite.cloud","mayfirst.info","mayfirst.org","hb.cldmail.ru","miniserver.com","memset.net","cloud.metacentrum.cz","custom.metacentrum.cz","flt.cloud.muni.cz","usr.cloud.muni.cz","meteorapp.com","eu.meteorapp.com","co.pl","azurecontainer.io","azurewebsites.net","azure-mobile.net","cloudapp.net","mozilla-iot.org","bmoattachments.org","net.ru","org.ru","pp.ru","ui.nabu.casa","pony.club","of.fashion","on.fashion","of.football","in.london","of.london","for.men","and.mom","for.mom","for.one","for.sale","of.work","to.work","nctu.me","bitballoon.com","netlify.com","4u.com","ngrok.io","nh-serv.co.uk","nfshost.com","dnsking.ch","mypi.co","n4t.co","001www.com","ddnslive.com","myiphost.com","forumz.info","16-b.it","32-b.it","64-b.it","soundcast.me","tcp4.me","dnsup.net","hicam.net","now-dns.net","ownip.net","vpndns.net","dynserv.org","now-dns.org","x443.pw","now-dns.top","ntdll.top","freeddns.us","crafting.xyz","zapto.xyz","nsupdate.info","nerdpol.ovh","blogsyte.com","brasilia.me","cable-modem.org","ciscofreak.com","collegefan.org","couchpotatofries.org","damnserver.com","ddns.me","ditchyourip.com","dnsfor.me","dnsiskinky.com","dvrcam.info","dynns.com","eating-organic.net","fantasyleague.cc","geekgalaxy.com","golffan.us","health-carereform.com","homesecuritymac.com","homesecuritypc.com","hopto.me","ilovecollege.info","loginto.me","mlbfan.org","mmafan.biz","myactivedirectory.com","mydissent.net","myeffect.net","mymediapc.net","mypsx.net","mysecuritycamera.com","mysecuritycamera.net","mysecuritycamera.org","net-freaks.com","nflfan.org","nhlfan.net","no-ip.ca","no-ip.co.uk","no-ip.net","noip.us","onthewifi.com","pgafan.net","point2this.com","pointto.us","privatizehealthinsurance.net","quicksytes.com","read-books.org","securitytactics.com","serveexchange.com","servehumour.com","servep2p.com","servesarcasm.com","stufftoread.com","ufcfan.org","unusualperson.com","workisboring.com","3utilities.com","bounceme.net","ddns.net","ddnsking.com","gotdns.ch","hopto.org","myftp.biz","myftp.org","myvnc.com","no-ip.biz","no-ip.info","no-ip.org","noip.me","redirectme.net","servebeer.com","serveblog.net","servecounterstrike.com","serveftp.com","servegame.com","servehalflife.com","servehttp.com","serveirc.com","serveminecraft.net","servemp3.com","servepics.com","servequake.com","sytes.net","webhop.me","zapto.org","stage.nodeart.io","nodum.co","nodum.io","pcloud.host","nyc.mn","nom.ae","nom.af","nom.ai","nom.al","nym.by","nym.bz","nom.cl","nym.ec","nom.gd","nom.ge","nom.gl","nym.gr","nom.gt","nym.gy","nym.hk","nom.hn","nym.ie","nom.im","nom.ke","nym.kz","nym.la","nym.lc","nom.li","nym.li","nym.lt","nym.lu","nym.me","nom.mk","nym.mn","nym.mx","nom.nu","nym.nz","nym.pe","nym.pt","nom.pw","nom.qa","nym.ro","nom.rs","nom.si","nym.sk","nom.st","nym.su","nym.sx","nom.tj","nym.tw","nom.ug","nom.uy","nom.vc","nom.vg","static.observableusercontent.com","cya.gg","cloudycluster.net","nid.io","opencraft.hosting","operaunite.com","skygearapp.com","outsystemscloud.com","ownprovider.com","own.pm","ox.rs","oy.lc","pgfog.com","pagefrontapp.com","art.pl","gliwice.pl","krakow.pl","poznan.pl","wroc.pl","zakopane.pl","pantheonsite.io","gotpantheon.com","mypep.link","perspecta.cloud","on-web.fr","*.platform.sh","*.platformsh.site","dyn53.io","co.bn","xen.prgmr.com","priv.at","prvcy.page","*.dweb.link","protonet.io","chirurgiens-dentistes-en-france.fr","byen.site","pubtls.org","qualifioapp.com","instantcloud.cn","ras.ru","qa2.com","qcx.io","*.sys.qcx.io","dev-myqnapcloud.com","alpha-myqnapcloud.com","myqnapcloud.com","*.quipelements.com","vapor.cloud","vaporcloud.io","rackmaze.com","rackmaze.net","*.on-k3s.io","*.on-rancher.cloud","*.on-rio.io","readthedocs.io","rhcloud.com","app.render.com","onrender.com","repl.co","repl.run","resindevice.io","devices.resinstaging.io","hzc.io","wellbeingzone.eu","ptplus.fit","wellbeingzone.co.uk","git-pages.rit.edu","sandcats.io","logoip.de","logoip.com","schokokeks.net","gov.scot","scrysec.com","firewall-gateway.com","firewall-gateway.de","my-gateway.de","my-router.de","spdns.de","spdns.eu","firewall-gateway.net","my-firewall.org","myfirewall.org","spdns.org","biz.ua","co.ua","pp.ua","shiftedit.io","myshopblocks.com","shopitsite.com","mo-siemens.io","1kapp.com","appchizi.com","applinzi.com","sinaapp.com","vipsinaapp.com","siteleaf.net","bounty-full.com","alpha.bounty-full.com","beta.bounty-full.com","stackhero-network.com","static.land","dev.static.land","sites.static.land","apps.lair.io","*.stolos.io","spacekit.io","customer.speedpartner.de","api.stdlib.com","storj.farm","utwente.io","soc.srcf.net","user.srcf.net","temp-dns.com","applicationcloud.io","scapp.io","*.s5y.io","*.sensiosite.cloud","syncloud.it","diskstation.me","dscloud.biz","dscloud.me","dscloud.mobi","dsmynas.com","dsmynas.net","dsmynas.org","familyds.com","familyds.net","familyds.org","i234.me","myds.me","synology.me","vpnplus.to","direct.quickconnect.to","taifun-dns.de","gda.pl","gdansk.pl","gdynia.pl","med.pl","sopot.pl","edugit.org","telebit.app","telebit.io","*.telebit.xyz","gwiddle.co.uk","thingdustdata.com","cust.dev.thingdust.io","cust.disrec.thingdust.io","cust.prod.thingdust.io","cust.testing.thingdust.io","arvo.network","azimuth.network","bloxcms.com","townnews-staging.com","12hp.at","2ix.at","4lima.at","lima-city.at","12hp.ch","2ix.ch","4lima.ch","lima-city.ch","trafficplex.cloud","de.cool","12hp.de","2ix.de","4lima.de","lima-city.de","1337.pictures","clan.rip","lima-city.rocks","webspace.rocks","lima.zone","*.transurl.be","*.transurl.eu","*.transurl.nl","tuxfamily.org","dd-dns.de","diskstation.eu","diskstation.org","dray-dns.de","draydns.de","dyn-vpn.de","dynvpn.de","mein-vigor.de","my-vigor.de","my-wan.de","syno-ds.de","synology-diskstation.de","synology-ds.de","uber.space","*.uberspace.de","hk.com","hk.org","ltd.hk","inc.hk","virtualuser.de","virtual-user.de","lib.de.us","2038.io","router.management","v-info.info","voorloper.cloud","v.ua","wafflecell.com","*.webhare.dev","wedeploy.io","wedeploy.me","wedeploy.sh","remotewd.com","wmflabs.org","half.host","xnbay.com","u2.xnbay.com","u2-local.xnbay.com","cistron.nl","demon.nl","xs4all.space","yandexcloud.net","storage.yandexcloud.net","website.yandexcloud.net","official.academy","yolasite.com","ybo.faith","yombo.me","homelink.one","ybo.party","ybo.review","ybo.science","ybo.trade","nohost.me","noho.st","za.net","za.org","now.sh","bss.design","basicserver.io","virtualserver.io","site.builder.nu","enterprisecloud.nu"] + +/***/ }), +/* 17 */ +/***/ (function(module, exports) { + + /*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + 'use strict'; + /*jshint unused:false */ + + function Store() { + } + exports.Store = Store; + + // Stores may be synchronous, but are still required to use a + // Continuation-Passing Style API. The CookieJar itself will expose a "*Sync" + // API that converts from synchronous-callbacks to imperative style. + Store.prototype.synchronous = false; + + Store.prototype.findCookie = function(domain, path, key, cb) { + throw new Error('findCookie is not implemented'); + }; + + Store.prototype.findCookies = function(domain, path, cb) { + throw new Error('findCookies is not implemented'); + }; + + Store.prototype.putCookie = function(cookie, cb) { + throw new Error('putCookie is not implemented'); + }; + + Store.prototype.updateCookie = function(oldCookie, newCookie, cb) { + // recommended default implementation: + // return this.putCookie(newCookie, cb); + throw new Error('updateCookie is not implemented'); + }; + + Store.prototype.removeCookie = function(domain, path, key, cb) { + throw new Error('removeCookie is not implemented'); + }; + + Store.prototype.removeCookies = function(domain, path, cb) { + throw new Error('removeCookies is not implemented'); + }; + + Store.prototype.removeAllCookies = function(cb) { + throw new Error('removeAllCookies is not implemented'); + } + + Store.prototype.getAllCookies = function(cb) { + throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)'); + }; + + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + + /*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + 'use strict'; + var Store = __webpack_require__(17).Store; + var permuteDomain = __webpack_require__(19).permuteDomain; + var pathMatch = __webpack_require__(20).pathMatch; + var util = __webpack_require__(8); + + function MemoryCookieStore() { + Store.call(this); + this.idx = {}; + } + util.inherits(MemoryCookieStore, Store); + exports.MemoryCookieStore = MemoryCookieStore; + MemoryCookieStore.prototype.idx = null; + + // Since it's just a struct in RAM, this Store is synchronous + MemoryCookieStore.prototype.synchronous = true; + + // force a default depth: + MemoryCookieStore.prototype.inspect = function() { + return "{ idx: "+util.inspect(this.idx, false, 2)+' }'; + }; + + // Use the new custom inspection symbol to add the custom inspect function if + // available. + if (util.inspect.custom) { + MemoryCookieStore.prototype[util.inspect.custom] = MemoryCookieStore.prototype.inspect; + } + + MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) { + if (!this.idx[domain]) { + return cb(null,undefined); + } + if (!this.idx[domain][path]) { + return cb(null,undefined); + } + return cb(null,this.idx[domain][path][key]||null); + }; + + MemoryCookieStore.prototype.findCookies = function(domain, path, cb) { + var results = []; + if (!domain) { + return cb(null,[]); + } + + var pathMatcher; + if (!path) { + // null means "all paths" + pathMatcher = function matchAll(domainIndex) { + for (var curPath in domainIndex) { + var pathIndex = domainIndex[curPath]; + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + } + }; + + } else { + pathMatcher = function matchRFC(domainIndex) { + //NOTE: we should use path-match algorithm from S5.1.4 here + //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299) + Object.keys(domainIndex).forEach(function (cookiePath) { + if (pathMatch(path, cookiePath)) { + var pathIndex = domainIndex[cookiePath]; + + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + } + }); + }; + } + + var domains = permuteDomain(domain) || [domain]; + var idx = this.idx; + domains.forEach(function(curDomain) { + var domainIndex = idx[curDomain]; + if (!domainIndex) { + return; + } + pathMatcher(domainIndex); + }); + + cb(null,results); + }; + + MemoryCookieStore.prototype.putCookie = function(cookie, cb) { + if (!this.idx[cookie.domain]) { + this.idx[cookie.domain] = {}; + } + if (!this.idx[cookie.domain][cookie.path]) { + this.idx[cookie.domain][cookie.path] = {}; + } + this.idx[cookie.domain][cookie.path][cookie.key] = cookie; + cb(null); + }; + + MemoryCookieStore.prototype.updateCookie = function(oldCookie, newCookie, cb) { + // updateCookie() may avoid updating cookies that are identical. For example, + // lastAccessed may not be important to some stores and an equality + // comparison could exclude that field. + this.putCookie(newCookie,cb); + }; + + MemoryCookieStore.prototype.removeCookie = function(domain, path, key, cb) { + if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) { + delete this.idx[domain][path][key]; + } + cb(null); + }; + + MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) { + if (this.idx[domain]) { + if (path) { + delete this.idx[domain][path]; + } else { + delete this.idx[domain]; + } + } + return cb(null); + }; + + MemoryCookieStore.prototype.removeAllCookies = function(cb) { + this.idx = {}; + return cb(null); + } + + MemoryCookieStore.prototype.getAllCookies = function(cb) { + var cookies = []; + var idx = this.idx; + + var domains = Object.keys(idx); + domains.forEach(function(domain) { + var paths = Object.keys(idx[domain]); + paths.forEach(function(path) { + var keys = Object.keys(idx[domain][path]); + keys.forEach(function(key) { + if (key !== null) { + cookies.push(idx[domain][path][key]); + } + }); + }); + }); + + // Sort by creationIndex so deserializing retains the creation order. + // When implementing your own store, this SHOULD retain the order too + cookies.sort(function(a,b) { + return (a.creationIndex||0) - (b.creationIndex||0); + }); + + cb(null, cookies); + }; + + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + + /*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + "use strict"; + var pubsuffix = __webpack_require__(13); + + // Gives the permutation of all possible domainMatch()es of a given domain. The + // array is in shortest-to-longest order. Handy for indexing. + function permuteDomain (domain) { + var pubSuf = pubsuffix.getPublicSuffix(domain); + if (!pubSuf) { + return null; + } + if (pubSuf == domain) { + return [domain]; + } + + var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" + var parts = prefix.split('.').reverse(); + var cur = pubSuf; + var permutations = [cur]; + while (parts.length) { + cur = parts.shift() + '.' + cur; + permutations.push(cur); + } + return permutations; + } + + exports.permuteDomain = permuteDomain; + + +/***/ }), +/* 20 */ +/***/ (function(module, exports) { + + /*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + "use strict"; + /* + * "A request-path path-matches a given cookie-path if at least one of the + * following conditions holds:" + */ + function pathMatch (reqPath, cookiePath) { + // "o The cookie-path and the request-path are identical." + if (cookiePath === reqPath) { + return true; + } + + var idx = reqPath.indexOf(cookiePath); + if (idx === 0) { + // "o The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/")." + if (cookiePath.substr(-1) === "/") { + return true; + } + + // " o The cookie-path is a prefix of the request-path, and the first + // character of the request-path that is not included in the cookie- path + // is a %x2F ("/") character." + if (reqPath.substr(cookiePath.length, 1) === "/") { + return true; + } + } + + return false; + } + + exports.pathMatch = pathMatch; + + +/***/ }), +/* 21 */ +/***/ (function(module, exports) { + + // generated by genversion + module.exports = '3.0.0' + + +/***/ }) +/******/ ]) +}); +; \ No newline at end of file diff --git a/src/plugins/cordova-plugin-advanced-http/www/url-util.js b/src/plugins/cordova-plugin-advanced-http/www/url-util.js new file mode 100644 index 0000000000..043d94ce52 --- /dev/null +++ b/src/plugins/cordova-plugin-advanced-http/www/url-util.js @@ -0,0 +1,103 @@ +module.exports = function init(jsUtil) { + return { + parseUrl: parseUrl, + appendQueryParamsString: appendQueryParamsString, + serializeQueryParams: serializeQueryParams + } + + function parseUrl(url) { + var match = url.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/); + + return match && { + protocol: match[1], + host: match[2], + hostname: match[3], + port: match[4] || '', + pathname: match[5], + search: match[6], + hash: match[7] + } + } + + function appendQueryParamsString(url, params) { + if (!url.length || !params.length) { + return url; + } + + var parsed = parseUrl(url); + + return parsed.protocol + + '//' + + parsed.host + + parsed.pathname + + (parsed.search.length ? parsed.search + '&' + params : '?' + params) + + parsed.hash; + } + + function serializeQueryParams(params, encode) { + return serializeObject('', params, encode); + } + + function serializeObject(parentKey, object, encode) { + var parts = []; + + for (var key in object) { + if (!object.hasOwnProperty(key)) { + continue; + } + + var identifier = parentKey.length ? parentKey + '[' + key + ']' : key; + + if (jsUtil.getTypeOf(object[key]) === 'Array') { + parts.push(serializeArray(identifier, object[key], encode)); + continue; + } else if (jsUtil.getTypeOf(object[key]) === 'Object') { + parts.push(serializeObject(identifier, object[key], encode)); + continue; + } + + parts.push(serializeIdentifier(parentKey, key, encode) + '=' + serializeValue(object[key], encode)); + } + + return parts.join('&'); + } + + function serializeArray(parentKey, array, encode) { + var parts = []; + + for (var i = 0; i < array.length; ++i) { + if (jsUtil.getTypeOf(array[i]) === 'Array') { + parts.push(serializeArray(parentKey + '[]', array[i], encode)); + continue; + } else if (jsUtil.getTypeOf(array[i]) === 'Object') { + parts.push(serializeObject(parentKey + '[]' + array[i], encode)); + continue; + } + + parts.push(serializeIdentifier(parentKey, '', encode) + '=' + serializeValue(array[i], encode)); + } + + return parts.join('&'); + } + + function serializeIdentifier(parentKey, key, encode) { + if (!parentKey.length) { + return encode ? encodeURIComponent(key) : key; + } + + if (encode) { + return encodeURIComponent(parentKey) + '[' + encodeURIComponent(key) + ']'; + } else { + return parentKey + '[' + key + ']'; + } + } + + function serializeValue(value, encode) { + if (encode) { + return encodeURIComponent(value); + } else { + return value; + } + } +}; + diff --git a/src/plugins/cordova-plugin-buildinfo/scripts/after_install.js b/src/plugins/cordova-plugin-buildinfo/scripts/after_install.js index 472b5873ba..77cb5f2857 100644 --- a/src/plugins/cordova-plugin-buildinfo/scripts/after_install.js +++ b/src/plugins/cordova-plugin-buildinfo/scripts/after_install.js @@ -35,7 +35,7 @@ function installWindows(windowsPath) { // Replace to if (projitems.match(/[\s]*?[\s]*?/m; + const search = /[\s]*?/m; const replace = "\r\n" diff --git a/src/plugins/cordova-plugin-buildinfo/scripts/before_uninstall.js b/src/plugins/cordova-plugin-buildinfo/scripts/before_uninstall.js index d692b26f9b..dffa5e305e 100644 --- a/src/plugins/cordova-plugin-buildinfo/scripts/before_uninstall.js +++ b/src/plugins/cordova-plugin-buildinfo/scripts/before_uninstall.js @@ -35,7 +35,7 @@ function uninstallWindows(context, windowsPath) { // Replace to if (projitems.match(/[\s]*?[\s]*?/m; + const search = /[\s]*?/m; const replace = "\r\n" @@ -47,9 +47,9 @@ function uninstallWindows(context, windowsPath) { } // Remove - if (projitems.match(//gm; + const search = /[\r\n ]*/gm; projitems = projitems.replace(search, ''); changed = true; diff --git a/src/plugins/cordova-plugin-crashhandler/package.json b/src/plugins/cordova-plugin-crashhandler/package.json new file mode 100644 index 0000000000..15accad6f1 --- /dev/null +++ b/src/plugins/cordova-plugin-crashhandler/package.json @@ -0,0 +1,19 @@ +{ + "name": "cordova-plugin-crashhandler", + "version": "1.0.0", + "description": "Dedicated Cordova plugin for crash handling in Acode, supporting native and JS crashes even when the app is completely unrecoverable.", + "cordova": { + "id": "cordova-plugin-crashhandler", + "platforms": [ + "android" + ] + }, + "keywords": [ + "ecosystem:cordova", + "cordova-android", + "crash", + "handler" + ], + "author": "Rohit Kushvaha", + "license": "MIT" +} diff --git a/src/plugins/cordova-plugin-crashhandler/plugin.xml b/src/plugins/cordova-plugin-crashhandler/plugin.xml new file mode 100644 index 0000000000..89ea176ba0 --- /dev/null +++ b/src/plugins/cordova-plugin-crashhandler/plugin.xml @@ -0,0 +1,32 @@ + + + CrashHandler + Dedicated crash handling plugin for Android + MIT + + + + + + + + + + + + + + + + + + diff --git a/src/plugins/cordova-plugin-crashhandler/src/android/CrashActivity.java b/src/plugins/cordova-plugin-crashhandler/src/android/CrashActivity.java new file mode 100644 index 0000000000..e9cd989e92 --- /dev/null +++ b/src/plugins/cordova-plugin-crashhandler/src/android/CrashActivity.java @@ -0,0 +1,525 @@ +package com.foxdebug.crashhandler; + +import android.app.Activity; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageInfo; +import android.graphics.Color; +import android.graphics.Typeface; +import android.graphics.drawable.GradientDrawable; +import android.os.Build; +import android.os.Bundle; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.widget.HorizontalScrollView; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; +import android.widget.Toast; +import android.webkit.WebView; +import java.io.File; +import java.io.FileInputStream; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import org.json.JSONObject; + +public class CrashActivity extends Activity { + + private String errorType; + private String errorMessage; + private String stackTrace; + private String fullReport; + + private int colorPrimaryBg; + private int colorSecondaryBg; + private int colorPrimaryText; + private int colorSecondaryText; + private int colorLinkText; + private int colorBorder; + private int colorTraceBg; + private int colorMetaLabel; + private int colorMetaValue; + private int colorButtonPrimaryBg; + private int colorButtonPrimaryText; + private int colorButtonSecondaryBg; + private int colorButtonSecondaryText; + private boolean isDarkTheme; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + loadThemeColors(); + applySystemBarColors(); + + Intent intent = getIntent(); + errorType = intent.getStringExtra("error_type"); + if (errorType == null) errorType = "Unexpected Crash"; + errorMessage = intent.getStringExtra("error_message"); + if (errorMessage == null) errorMessage = "No error message provided"; + stackTrace = intent.getStringExtra("stack_trace"); + if (stackTrace == null) stackTrace = "No stack trace details available."; + + String appVersion = "Unknown"; + String appBuild = "Unknown"; + try { + PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); + appVersion = pInfo.versionName; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + appBuild = String.valueOf(pInfo.getLongVersionCode()); + } else { + appBuild = String.valueOf(pInfo.versionCode); + } + } catch (Exception e) { + // Ignore + } + + String deviceName = Build.MANUFACTURER + " " + Build.MODEL; + String androidVersion = Build.VERSION.RELEASE + " (SDK " + Build.VERSION.SDK_INT + ")"; + String webViewVersion = getWebViewVersion(); + String appLanguage = getAppLanguage(); + + fullReport = "Acode Crash Report\n" + + "==================\n" + + "WebView Version: " + webViewVersion + "\n" + + "App Language: " + appLanguage + "\n" + + "Error Message: " + errorMessage + "\n" + + "App Version: " + appVersion + " (" + appBuild + ")\n" + + "Device: " + deviceName + "\n" + + "Android Version: " + androidVersion + "\n\n" + + "Stack Trace:\n" + + stackTrace; + + ScrollView mainScrollView = new ScrollView(this); + mainScrollView.setLayoutParams(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT)); + mainScrollView.setBackgroundColor(colorPrimaryBg); + mainScrollView.setFillViewport(true); + + LinearLayout rootLayout = new LinearLayout(this); + rootLayout.setOrientation(LinearLayout.VERTICAL); + LinearLayout.LayoutParams rootParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + int padding = dp(20); + rootLayout.setPadding(padding, padding, padding, padding); + rootLayout.setLayoutParams(rootParams); + + TextView titleView = new TextView(this); + titleView.setText("Acode Crashed"); + titleView.setTextSize(24); + titleView.setTextColor(colorPrimaryText); + titleView.setTypeface(Typeface.create("sans-serif-medium", Typeface.BOLD)); + LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + titleParams.setMargins(0, dp(10), 0, dp(8)); + titleView.setLayoutParams(titleParams); + rootLayout.addView(titleView); + + TextView descView = new TextView(this); + descView.setText("An unrecoverable exception occurred in Acode's native system. The application details and exception logs have been recorded below."); + descView.setTextSize(14); + descView.setTextColor(colorSecondaryText); + LinearLayout.LayoutParams descParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + descParams.setMargins(0, 0, 0, dp(20)); + descView.setLayoutParams(descParams); + rootLayout.addView(descView); + + TextView metaTitleView = new TextView(this); + metaTitleView.setText("DEVICE & APP INFO"); + metaTitleView.setTextSize(11); + metaTitleView.setTextColor(colorLinkText); + metaTitleView.setTypeface(Typeface.create("sans-serif", Typeface.BOLD)); + LinearLayout.LayoutParams metaTitleParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + metaTitleParams.setMargins(0, 0, 0, dp(6)); + metaTitleView.setLayoutParams(metaTitleParams); + rootLayout.addView(metaTitleView); + + LinearLayout metaCard = new LinearLayout(this); + metaCard.setOrientation(LinearLayout.VERTICAL); + metaCard.setPadding(dp(16), dp(16), dp(16), dp(16)); + + GradientDrawable cardBg = new GradientDrawable(); + cardBg.setColor(colorSecondaryBg); + cardBg.setCornerRadius(dp(4)); + cardBg.setStroke(dp(1), colorBorder); + metaCard.setBackground(cardBg); + + LinearLayout.LayoutParams cardParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + cardParams.setMargins(0, 0, 0, dp(20)); + metaCard.setLayoutParams(cardParams); + + metaCard.addView(createMetaRow("App Version", appVersion + " (" + appBuild + ")")); + metaCard.addView(createMetaRow("Device", deviceName)); + metaCard.addView(createMetaRow("Android OS", androidVersion)); + metaCard.addView(createMetaRow("WebView", webViewVersion)); + metaCard.addView(createMetaRow("App Language", appLanguage)); + rootLayout.addView(metaCard); + + TextView logsTitleView = new TextView(this); + logsTitleView.setText("STACK TRACE"); + logsTitleView.setTextSize(11); + logsTitleView.setTextColor(colorLinkText); + logsTitleView.setTypeface(Typeface.create("sans-serif", Typeface.BOLD)); + LinearLayout.LayoutParams logsTitleParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + logsTitleParams.setMargins(0, 0, 0, dp(6)); + logsTitleView.setLayoutParams(logsTitleParams); + rootLayout.addView(logsTitleView); + + LinearLayout traceCard = new LinearLayout(this); + traceCard.setOrientation(LinearLayout.VERTICAL); + traceCard.setPadding(dp(12), dp(12), dp(12), dp(12)); + GradientDrawable traceBg = new GradientDrawable(); + traceBg.setColor(colorTraceBg); + traceBg.setCornerRadius(dp(4)); + traceBg.setStroke(dp(1), colorBorder); + traceCard.setBackground(traceBg); + + LinearLayout.LayoutParams traceCardParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + dp(280)); + traceCardParams.setMargins(0, 0, 0, dp(24)); + traceCard.setLayoutParams(traceCardParams); + + ScrollView traceVerticalScroll = new ScrollView(this); + HorizontalScrollView traceHorizontalScroll = new HorizontalScrollView(this); + + TextView traceView = new TextView(this); + traceView.setText(stackTrace); + traceView.setTextSize(12); + traceView.setTextColor(colorSecondaryText); + traceView.setTypeface(Typeface.MONOSPACE); + traceView.setHorizontallyScrolling(true); + traceView.setTextIsSelectable(true); + + traceHorizontalScroll.addView(traceView); + traceVerticalScroll.addView(traceHorizontalScroll); + traceCard.addView(traceVerticalScroll); + rootLayout.addView(traceCard); + + LinearLayout buttonsLayout = new LinearLayout(this); + buttonsLayout.setOrientation(LinearLayout.VERTICAL); + LinearLayout.LayoutParams buttonsParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + buttonsLayout.setLayoutParams(buttonsParams); + + TextView btnRestart = createButton("Restart Acode", colorButtonPrimaryText, colorButtonPrimaryBg, false); + btnRestart.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent restartIntent = getPackageManager().getLaunchIntentForPackage(getPackageName()); + if (restartIntent != null) { + restartIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + startActivity(restartIntent); + } + finish(); + System.exit(0); + } + }); + buttonsLayout.addView(btnRestart); + + TextView btnCopy = createButton("Copy Error Details", colorButtonSecondaryText, colorButtonSecondaryBg, true); + btnCopy.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clip = ClipData.newPlainText("Acode Crash Log", fullReport); + clipboard.setPrimaryClip(clip); + Toast.makeText(CrashActivity.this, "Copied report to clipboard!", Toast.LENGTH_SHORT).show(); + } + }); + buttonsLayout.addView(btnCopy); + + TextView btnClose = createButton("Close", colorButtonSecondaryText, colorButtonSecondaryBg, true); + btnClose.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + finish(); + System.exit(0); + } + }); + buttonsLayout.addView(btnClose); + + rootLayout.addView(buttonsLayout); + mainScrollView.addView(rootLayout); + setContentView(mainScrollView); + } + + private void loadThemeColors() { + SharedPreferences prefs = null; + try { + prefs = getApplicationContext() + .getSharedPreferences("acode_theme", Context.MODE_PRIVATE); + } catch (Exception ignored) {} + + colorPrimaryBg = getThemeColor(prefs, "primaryColor", "#23272a"); + colorSecondaryBg = getThemeColor(prefs, "secondaryColor", "#2d3134"); + colorPrimaryText = getThemeColor(prefs, "primaryTextColor", "#f5f5f5"); + colorSecondaryText = getThemeColor(prefs, "secondaryTextColor", "#e4e4e4"); + colorLinkText = getThemeColor(prefs, "linkTextColor", "#8ab4f8"); + colorButtonPrimaryBg = getThemeColor(prefs, "activeColor", "#4285f4"); + colorButtonPrimaryText = getThemeColor(prefs, "buttonTextColor", "#ffffff"); + colorButtonSecondaryBg = colorSecondaryBg; + colorButtonSecondaryText = colorSecondaryText; + + String themeType = "dark"; + if (prefs != null) { + try { + themeType = prefs.getString("type", "dark"); + } catch (Exception ignored) {} + } + isDarkTheme = !"light".equals(themeType); + + colorBorder = deriveBorderColor(colorPrimaryBg, colorSecondaryBg); + colorTraceBg = deriveTraceBg(colorPrimaryBg); + colorMetaLabel = deriveMetaLabelColor(colorSecondaryText); + colorMetaValue = colorPrimaryText; + } + + private int getThemeColor(SharedPreferences prefs, String key, String fallback) { + if (prefs == null) return safeParseColor(fallback); + try { + String value = prefs.getString(key, null); + if (value != null && !value.isEmpty()) { + return safeParseColor(value, fallback); + } + } catch (Exception ignored) {} + return safeParseColor(fallback); + } + + private int safeParseColor(String colorStr) { + return safeParseColor(colorStr, "#000000"); + } + + private int safeParseColor(String colorStr, String fallback) { + try { + return Color.parseColor(colorStr); + } catch (Exception e) { + try { + return Color.parseColor(fallback); + } catch (Exception e2) { + return Color.BLACK; + } + } + } + + private int deriveBorderColor(int primary, int secondary) { + int r = (Color.red(primary) + Color.red(secondary)) / 2; + int g = (Color.green(primary) + Color.green(secondary)) / 2; + int b = (Color.blue(primary) + Color.blue(secondary)) / 2; + if (isDarkTheme) { + r = Math.min(255, r + 20); + g = Math.min(255, g + 20); + b = Math.min(255, b + 20); + } else { + r = Math.max(0, r - 20); + g = Math.max(0, g - 20); + b = Math.max(0, b - 20); + } + return Color.rgb(r, g, b); + } + + private int deriveTraceBg(int primaryBg) { + if (isDarkTheme) { + return Color.rgb( + Math.max(0, Color.red(primaryBg) - 12), + Math.max(0, Color.green(primaryBg) - 12), + Math.max(0, Color.blue(primaryBg) - 12)); + } + return Color.rgb( + Math.min(255, Color.red(primaryBg) + 8), + Math.min(255, Color.green(primaryBg) + 8), + Math.min(255, Color.blue(primaryBg) + 8)); + } + + private int deriveMetaLabelColor(int secondaryText) { + return Color.argb( + 180, + Color.red(secondaryText), + Color.green(secondaryText), + Color.blue(secondaryText)); + } + + private void applySystemBarColors() { + try { + Window window = getWindow(); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + window.setStatusBarColor(colorPrimaryBg); + window.setNavigationBarColor(colorPrimaryBg); + } + if (!isDarkTheme && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + View decorView = window.getDecorView(); + decorView.setSystemUiVisibility( + decorView.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); + } + } catch (Exception ignored) {} + } + + private View createMetaRow(String label, String value) { + LinearLayout row = new LinearLayout(this); + row.setOrientation(LinearLayout.HORIZONTAL); + LinearLayout.LayoutParams rowParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + rowParams.setMargins(0, 0, 0, dp(6)); + row.setLayoutParams(rowParams); + + TextView labelView = new TextView(this); + labelView.setText(label + ": "); + labelView.setTextSize(13); + labelView.setTextColor(colorMetaLabel); + labelView.setTypeface(Typeface.DEFAULT_BOLD); + LinearLayout.LayoutParams labelParams = new LinearLayout.LayoutParams( + dp(100), + LinearLayout.LayoutParams.WRAP_CONTENT); + labelView.setLayoutParams(labelParams); + + TextView valView = new TextView(this); + valView.setText(value); + valView.setTextSize(13); + valView.setTextColor(colorMetaValue); + LinearLayout.LayoutParams valParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + valView.setLayoutParams(valParams); + + row.addView(labelView); + row.addView(valView); + return row; + } + + private TextView createButton(String text, int textColor, int bgColor, boolean hasBorder) { + final TextView btn = new TextView(this); + btn.setText(text); + btn.setTextSize(15); + btn.setTextColor(textColor); + btn.setGravity(Gravity.CENTER); + btn.setPadding(dp(16), dp(14), dp(16), dp(14)); + btn.setTypeface(Typeface.create("sans-serif-medium", Typeface.BOLD)); + + final GradientDrawable normalBg = new GradientDrawable(); + normalBg.setColor(bgColor); + normalBg.setCornerRadius(dp(4)); + + if (hasBorder) { + normalBg.setStroke(dp(1), colorBorder); + } + + btn.setBackground(normalBg); + + LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + btnParams.setMargins(0, 0, 0, dp(12)); + btn.setLayoutParams(btnParams); + + btn.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + if (event.getAction() == MotionEvent.ACTION_DOWN) { + btn.setAlpha(0.7f); + } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) { + btn.setAlpha(1.0f); + } + return false; + } + }); + + return btn; + } + + private String getWebViewVersion() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + try { + PackageInfo info = WebView.getCurrentWebViewPackage(); + if (info != null) { + return info.versionName; + } + } catch (Exception e) { + // Ignore + } + } + + try { + String[] packages = { + "com.google.android.webview", + "com.android.chrome", + "com.android.webview" + }; + for (String pkg : packages) { + try { + PackageInfo info = getPackageManager().getPackageInfo(pkg, 0); + if (info != null) { + return info.versionName; + } + } catch (Exception ignored) {} + } + } catch (Exception e) { + // Ignore + } + + try { + return System.getProperty("http.agent"); + } catch (Exception e) { + // Ignore + } + + return "Unknown"; + } + + private String getAppLanguage() { + String langCode = "en-us"; + try { + File settingsFile = new File(getExternalFilesDir(null), "settings.json"); + if (!settingsFile.exists()) { + settingsFile = new File(getFilesDir(), "settings.json"); + } + if (settingsFile.exists()) { + FileInputStream fis = new FileInputStream(settingsFile); + BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "UTF-8")); + StringBuilder sb = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + sb.append(line); + } + reader.close(); + fis.close(); + + JSONObject json = new JSONObject(sb.toString()); + if (json.has("lang")) { + langCode = json.getString("lang"); + } + } + } catch (Exception e) { + // Ignore + } + + return langCode; + } + + private int dp(float value) { + return (int) TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, + value, + getResources().getDisplayMetrics() + ); + } +} diff --git a/src/plugins/cordova-plugin-crashhandler/src/android/CrashHandler.java b/src/plugins/cordova-plugin-crashhandler/src/android/CrashHandler.java new file mode 100644 index 0000000000..cc02d1cc55 --- /dev/null +++ b/src/plugins/cordova-plugin-crashhandler/src/android/CrashHandler.java @@ -0,0 +1,66 @@ +package com.foxdebug.crashhandler; + +import android.content.Context; +import android.content.Intent; +import android.util.Log; +import java.io.PrintWriter; +import java.io.StringWriter; +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.CordovaWebView; + +public class CrashHandler extends CordovaPlugin { + + private static final String TAG = "CrashHandler"; + + @Override + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); + Log.d(TAG, "Initializing CrashHandler..."); + + Thread.setDefaultUncaughtExceptionHandler( + new Thread.UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread thread, Throwable ex) { + try { + Log.e(TAG, "Uncaught native exception detected!", ex); + + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + ex.printStackTrace(pw); + String stackTrace = sw.toString(); + + Context context = cordova + .getActivity() + .getApplicationContext(); + Intent intent = new Intent( + context, + CrashActivity.class + ); + intent.putExtra("error_type", "Native Crash"); + intent.putExtra( + "error_message", + ex.getMessage() != null + ? ex.getMessage() + : ex.toString() + ); + intent.putExtra("stack_trace", stackTrace); + intent.addFlags( + Intent.FLAG_ACTIVITY_NEW_TASK | + Intent.FLAG_ACTIVITY_CLEAR_TASK + ); + context.startActivity(intent); + } catch (Throwable e) { + Log.e(TAG, "Failed to launch CrashActivity", e); + } finally { + //Should we terminate the app? or let it run with faulty state? + android.os.Process.killProcess( + android.os.Process.myPid() + ); + System.exit(10); + } + } + } + ); + } +} diff --git a/src/plugins/custom-tabs/package.json b/src/plugins/custom-tabs/package.json new file mode 100644 index 0000000000..eeea20401e --- /dev/null +++ b/src/plugins/custom-tabs/package.json @@ -0,0 +1,17 @@ +{ + "name": "com.foxdebug.acode.rk.customtabs", + "version": "1.0.0", + "description": "Custom tabs api", + "cordova": { + "id": "com.foxdebug.acode.rk.customtabs", + "platforms": [ + "android" + ] + }, + "keywords": [ + "ecosystem:cordova", + "cordova-android" + ], + "author": "@RohitKushvaha01", + "license": "MIT" +} \ No newline at end of file diff --git a/src/plugins/custom-tabs/plugin.xml b/src/plugins/custom-tabs/plugin.xml new file mode 100644 index 0000000000..c0ccc4fde2 --- /dev/null +++ b/src/plugins/custom-tabs/plugin.xml @@ -0,0 +1,35 @@ + + + Custom Tabs + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/plugins/custom-tabs/src/CustomTabsPlugin.java b/src/plugins/custom-tabs/src/CustomTabsPlugin.java new file mode 100644 index 0000000000..a7ee4cc2ac --- /dev/null +++ b/src/plugins/custom-tabs/src/CustomTabsPlugin.java @@ -0,0 +1,79 @@ +package com.foxdebug.acode.rk.customtabs; + +import android.content.ActivityNotFoundException; +import android.content.Intent; +import android.net.Uri; +import android.graphics.Color; + +import androidx.browser.customtabs.CustomTabsIntent; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaPlugin; +import org.json.JSONArray; +import org.json.JSONObject; + +public class CustomTabsPlugin extends CordovaPlugin { + + @Override + public boolean execute( + String action, + JSONArray args, + CallbackContext callbackContext + ) { + + if ("open".equals(action)) { + try { + final String url = args.getString(0); + final JSONObject options = args.optJSONObject(1) != null + ? args.optJSONObject(1) + : new JSONObject(); + + cordova.getActivity().runOnUiThread(() -> { + try { + openCustomTab(url, options); + callbackContext.success(); + } catch (Exception e) { + callbackContext.error(e.getMessage()); + } + }); + + return true; + + } catch (Exception e) { + callbackContext.error(e.getMessage()); + return true; + } + } + + return false; + } + + private void openCustomTab(String url, JSONObject options) { + CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); + + String toolbarColor = options.optString("toolbarColor", null); + if (toolbarColor != null && !toolbarColor.isEmpty()) { + builder.setToolbarColor(Color.parseColor(toolbarColor)); + } + + CustomTabsIntent customTabsIntent = builder.build(); + + if (options.optBoolean("showTitle", true)) { + customTabsIntent.intent.putExtra(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE, CustomTabsIntent.SHOW_PAGE_TITLE); + } + + try { + customTabsIntent.launchUrl( + cordova.getActivity(), + Uri.parse(url) + ); + } catch (ActivityNotFoundException e) { + // Fallback to default browser + Intent fallback = new Intent( + Intent.ACTION_VIEW, + Uri.parse(url) + ); + cordova.getActivity().startActivity(fallback); + } + } +} diff --git a/src/plugins/custom-tabs/www/customtabs.js b/src/plugins/custom-tabs/www/customtabs.js new file mode 100644 index 0000000000..2c020c2282 --- /dev/null +++ b/src/plugins/custom-tabs/www/customtabs.js @@ -0,0 +1,11 @@ +var exec = require('cordova/exec'); + +exports.open = function (url, options, success, error) { + exec( + success, + error, + 'CustomTabs', + 'open', + [url, options || {}] + ); +}; \ No newline at end of file diff --git a/src/plugins/ftp/src/android/com/foxdebug/ftp/Ftp.java b/src/plugins/ftp/src/android/com/foxdebug/ftp/Ftp.java index 92c5a2f194..b2de25446a 100644 --- a/src/plugins/ftp/src/android/com/foxdebug/ftp/Ftp.java +++ b/src/plugins/ftp/src/android/com/foxdebug/ftp/Ftp.java @@ -595,24 +595,33 @@ public void run() { ftp.setFileType(FTP.BINARY_FILE_TYPE); - InputStream inputStream = ftp.retrieveFileStream(path); - if (inputStream == null) { - Log.d( - "FTP", - "FTPClient (" + ftpId + ") path: " + path + " - not found" - ); - callback.error("File not found."); - return; + // Delete existing cache file to prevent stale content + if (localFile.exists()) { + localFile.delete(); } - FileOutputStream outputStream = new FileOutputStream(localFile); - byte[] buffer = new byte[1024]; - int bytesRead = -1; - while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead); + try ( + InputStream inputStream = ftp.retrieveFileStream(path) + ) { + if (inputStream == null) { + Log.d( + "FTP", + "FTPClient (" + ftpId + ") path: " + path + " - not found" + ); + callback.error("File not found."); + return; + } + + try ( + FileOutputStream outputStream = new FileOutputStream(localFile) + ) { + byte[] buffer = new byte[1024]; + int bytesRead = -1; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + } } - outputStream.close(); - inputStream.close(); if (!ftp.completePendingCommand()) { ftp.logout(); @@ -675,20 +684,22 @@ public void run() { ftp.setFileType(FTP.BINARY_FILE_TYPE); Log.d("FTPUpload", "Destination " + remoteFilePath); - OutputStream outputStream = ftp.storeFileStream(remoteFilePath); - if (outputStream == null) { - callback.error("File not found."); - return; - } - InputStream inputStream = new FileInputStream(localFile); - byte[] buffer = new byte[1024]; - int bytesRead = -1; - while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead); + try ( + InputStream inputStream = new FileInputStream(localFile); + OutputStream outputStream = ftp.storeFileStream(remoteFilePath) + ) { + if (outputStream == null) { + callback.error("File not found."); + return; + } + + byte[] buffer = new byte[1024]; + int bytesRead = -1; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } } - outputStream.close(); - inputStream.close(); if (!ftp.completePendingCommand()) { ftp.logout(); diff --git a/src/plugins/iap/www/plugin.js b/src/plugins/iap/www/plugin.js index a83ff9d97c..885a6d8fb4 100644 --- a/src/plugins/iap/www/plugin.js +++ b/src/plugins/iap/www/plugin.js @@ -1,3 +1,4 @@ +var __iap_plugin_isIapAvailable = true; module.exports = { getProducts: function (productIds, onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'Iap', 'getProducts', [productIds]); @@ -6,7 +7,10 @@ module.exports = { cordova.exec(onSuccess, onFail, 'Iap', 'setPurchaseUpdatedListener', []); }, startConnection: function (onSuccess, onFail) { - cordova.exec(onSuccess, onFail, 'Iap', 'startConnection', []); + cordova.exec(onSuccess, function (error) { + onFail(error); + __iap_plugin_isIapAvailable = error !== 3; + }, 'Iap', 'startConnection', []); }, consume: function (purchaseToken, onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'Iap', 'consume', [purchaseToken]); @@ -20,6 +24,9 @@ module.exports = { acknowledgePurchase: function (purchaseToken, onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'Iap', 'acknowledgePurchase', [purchaseToken]); }, + isIapAvailable(){ + return __iap_plugin_isIapAvailable; + }, BILLING_UNAVAILABLE: 3, DEVELOPER_ERROR: 5, ERROR: 6, diff --git a/src/plugins/pluginContext/package.json b/src/plugins/pluginContext/package.json new file mode 100644 index 0000000000..301d27b998 --- /dev/null +++ b/src/plugins/pluginContext/package.json @@ -0,0 +1,17 @@ +{ + "name": "com.foxdebug.acode.rk.plugin.plugincontext", + "version": "1.0.0", + "description": "PluginContext", + "cordova": { + "id": "com.foxdebug.acode.rk.plugin.plugincontext", + "platforms": [ + "android" + ] + }, + "keywords": [ + "ecosystem:cordova", + "cordova-android" + ], + "author": "@RohitKushvaha01", + "license": "MIT" +} diff --git a/src/plugins/pluginContext/plugin.xml b/src/plugins/pluginContext/plugin.xml new file mode 100644 index 0000000000..1f5ca131cf --- /dev/null +++ b/src/plugins/pluginContext/plugin.xml @@ -0,0 +1,17 @@ + + + PluginContext + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/plugins/pluginContext/src/android/Tee.java b/src/plugins/pluginContext/src/android/Tee.java new file mode 100644 index 0000000000..22e5bdea36 --- /dev/null +++ b/src/plugins/pluginContext/src/android/Tee.java @@ -0,0 +1,321 @@ +package com.foxdebug.acode.rk.plugin; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaPlugin; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import android.content.Context; +import org.apache.cordova.*; + +//auth plugin +import com.foxdebug.acode.rk.auth.EncryptedPreferenceManager; + +public class Tee extends CordovaPlugin { + + // pluginId : token + private final Map tokenStore = new ConcurrentHashMap<>(); + + // token : list of permissions + private final Map> permissionStore = new ConcurrentHashMap<>(); + + // Trusted session established by the plugin loader before any plugin runs. + // Only requests carrying this secret are allowed to request tokens. + private volatile String sessionId = null; + + // Cryptographically secure source for all secrets. Tokens must never be + // predictable or derivable, otherwise a malicious plugin could forge them. + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + + private Context context; + + + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); + this.context = cordova.getContext(); + } + + @Override + public void onReset() { + // The WebView navigated/refreshed: the JS world was rebuilt, so the + // previous trusted session is no longer meaningful. Drop it and let the + // loader establish a fresh one during the next bootstrap. + this.sessionId = null; + } + + @Override + public boolean execute(String action, JSONArray args, CallbackContext callback) + throws JSONException { + + if ("establishConnection".equals(action)) { + synchronized (this) { + if (sessionId != null) { + callback.error("CONNECTION_ALREADY_ESTABLISHED"); + } else { + sessionId = generateSecret(); + callback.success(sessionId); + } + } + return true; + } + + if ("requestToken".equals(action)) { + String session = args.getString(0); + String pluginId = args.getString(1); + String pluginJson = args.getString(2); + + if (!isValidSession(session)) { + callback.error("INVALID_SESSION"); + return true; + } + + handleTokenRequest(pluginId, pluginJson, callback); + return true; + } + + if ("get_secret".equals(action)) { + String token = args.getString(0); + String key = args.getString(1); + String defaultValue = args.getString(2); + + String pluginId = getPluginIdFromToken(token); + + if (pluginId == null) { + callback.error("INVALID_TOKEN"); + return true; + } + + EncryptedPreferenceManager prefs = + new EncryptedPreferenceManager(context, pluginId); + + String value = prefs.getString(key, defaultValue); + callback.success(value); + return true; + } + + if ("set_secret".equals(action)) { + String token = args.getString(0); + String key = args.getString(1); + String value = args.getString(2); + + String pluginId = getPluginIdFromToken(token); + + if (pluginId == null) { + callback.error("INVALID_TOKEN"); + return true; + } + + EncryptedPreferenceManager prefs = + new EncryptedPreferenceManager(context, pluginId); + + prefs.setString(key, value); + callback.success(); + return true; + } + + if ("delete_secret".equals(action)) { + String token = args.getString(0); + String key = args.getString(1); + + String pluginId = getPluginIdFromToken(token); + + if (pluginId == null) { + callback.error("INVALID_TOKEN"); + return true; + } + + EncryptedPreferenceManager prefs = + new EncryptedPreferenceManager(context, pluginId); + + prefs.remove(key); + callback.success(); + return true; + } + + if ("clear_all_secrets".equals(action)) { + String token = args.getString(0); + + String pluginId = getPluginIdFromToken(token); + + if (pluginId == null) { + callback.error("INVALID_TOKEN"); + return true; + } + + EncryptedPreferenceManager prefs = + new EncryptedPreferenceManager(context, pluginId); + + prefs.clear(); + callback.success(); + return true; + } + + + if ("invalidate".equals(action)) { + String token = args.getString(0); + + String pluginId = getPluginIdFromToken(token); + + if (pluginId == null) { + callback.error("INVALID_TOKEN"); + return true; + } + + invalidateToken(token, pluginId); + callback.success(); + return true; + } + + if ("grantedPermission".equals(action)) { + String token = args.getString(0); + String permission = args.getString(1); + + if (!permissionStore.containsKey(token)) { + callback.error("INVALID_TOKEN"); + return true; + } + + boolean granted = grantedPermission(token, permission); + callback.success(granted ? 1 : 0); + return true; + } + + if ("listAllPermissions".equals(action)) { + String token = args.getString(0); + + if (!permissionStore.containsKey(token)) { + callback.error("INVALID_TOKEN"); + return true; + } + + List permissions = listAllPermissions(token); + JSONArray result = new JSONArray(permissions); + + callback.success(result); + return true; + } + + return false; + } + + + private String getPluginIdFromToken(String token) { + for (Map.Entry entry : tokenStore.entrySet()) { + if (constantTimeEquals(token, entry.getValue())) { + return entry.getKey(); + } + } + return null; + } + + private void invalidateToken(String token, String pluginId) { + String storedToken = tokenStore.get(pluginId); + if (storedToken != null && constantTimeEquals(token, storedToken)) { + tokenStore.remove(pluginId); + } + permissionStore.remove(token); + } + + private boolean isValidSession(String session) { + String current = sessionId; + return current != null && constantTimeEquals(session, current); + } + + //============================================================ + //do not change function signatures + public boolean isTokenValid(String token, String pluginId) { + String storedToken = tokenStore.get(pluginId); + return storedToken != null && constantTimeEquals(token, storedToken); + } + + + public boolean grantedPermission(String token, String permission) { + List permissions = permissionStore.get(token); + return permissions != null && permissions.contains(permission); + } + + public List listAllPermissions(String token) { + List permissions = permissionStore.get(token); + + if (permissions == null) { + return new ArrayList<>(); + } + + return new ArrayList<>(permissions); // return copy (safe) + } + //============================================================ + + + private synchronized void handleTokenRequest( + String pluginId, + String pluginJson, + CallbackContext callback + ) { + + String token = tokenStore.get(pluginId); + + if (token == null) { + token = generateSecret(); + tokenStore.put(pluginId, token); + } + + try { + JSONObject json = new JSONObject(pluginJson); + JSONArray permissions = json.optJSONArray("permissions"); + + List permissionList = new ArrayList<>(); + + if (permissions != null) { + for (int i = 0; i < permissions.length(); i++) { + permissionList.add(permissions.getString(i)); + } + } + + // Bind permissions to token + permissionStore.put(token, permissionList); + + } catch (JSONException e) { + callback.error("INVALID_PLUGIN_JSON"); + return; + } + + callback.success(token); + } + + /** + * Generates a 256-bit (32-byte) secret encoded as hex. Uses SecureRandom so + * tokens and session ids are never predictable, derivable or forgeable. + */ + private static String generateSecret() { + byte[] bytes = new byte[32]; + SECURE_RANDOM.nextBytes(bytes); + return toHex(bytes); + } + + private static String toHex(byte[] bytes) { + StringBuilder sb = new StringBuilder(bytes.length * 2); + for (byte b : bytes) { + sb.append(Character.forDigit((b >> 4) & 0xF, 16)); + sb.append(Character.forDigit(b & 0xF, 16)); + } + return sb.toString(); + } + + private static boolean constantTimeEquals(String a, String b) { + if (a == null || b == null) { + return false; + } + return MessageDigest.isEqual( + a.getBytes(StandardCharsets.UTF_8), + b.getBytes(StandardCharsets.UTF_8) + ); + } +} diff --git a/src/plugins/proot/assets/alpine_assets/arm32/alpine.rootfs b/src/plugins/proot/assets/alpine_assets/arm32/alpine.rootfs new file mode 100755 index 0000000000..1ad5e69f9f Binary files /dev/null and b/src/plugins/proot/assets/alpine_assets/arm32/alpine.rootfs differ diff --git a/src/plugins/proot/assets/alpine_assets/arm64/alpine.rootfs b/src/plugins/proot/assets/alpine_assets/arm64/alpine.rootfs new file mode 100755 index 0000000000..0adc1737ca Binary files /dev/null and b/src/plugins/proot/assets/alpine_assets/arm64/alpine.rootfs differ diff --git a/src/plugins/proot/assets/alpine_assets/x64/alpine.rootfs b/src/plugins/proot/assets/alpine_assets/x64/alpine.rootfs new file mode 100755 index 0000000000..9c524717b8 Binary files /dev/null and b/src/plugins/proot/assets/alpine_assets/x64/alpine.rootfs differ diff --git a/src/plugins/proot/libs/arm32/libaxs.so b/src/plugins/proot/libs/arm32/libaxs.so new file mode 100644 index 0000000000..33f91390c2 Binary files /dev/null and b/src/plugins/proot/libs/arm32/libaxs.so differ diff --git a/src/plugins/proot/libs/arm32/libproot-xed.so b/src/plugins/proot/libs/arm32/libproot-xed.so old mode 100644 new mode 100755 index 398f676214..182e02d015 Binary files a/src/plugins/proot/libs/arm32/libproot-xed.so and b/src/plugins/proot/libs/arm32/libproot-xed.so differ diff --git a/src/plugins/proot/libs/arm32/libproot.so b/src/plugins/proot/libs/arm32/libproot.so old mode 100644 new mode 100755 index 170cb6b8fd..2357584b84 Binary files a/src/plugins/proot/libs/arm32/libproot.so and b/src/plugins/proot/libs/arm32/libproot.so differ diff --git a/src/plugins/proot/libs/arm32/libtalloc.so b/src/plugins/proot/libs/arm32/libtalloc.so old mode 100644 new mode 100755 index c8d6c13fa3..2e19234746 Binary files a/src/plugins/proot/libs/arm32/libtalloc.so and b/src/plugins/proot/libs/arm32/libtalloc.so differ diff --git a/src/plugins/proot/libs/arm64/libaxs.so b/src/plugins/proot/libs/arm64/libaxs.so new file mode 100755 index 0000000000..e7da3b71f3 Binary files /dev/null and b/src/plugins/proot/libs/arm64/libaxs.so differ diff --git a/src/plugins/proot/libs/arm64/libproot-xed.so b/src/plugins/proot/libs/arm64/libproot-xed.so old mode 100644 new mode 100755 index 33761eca76..e9f9105a50 Binary files a/src/plugins/proot/libs/arm64/libproot-xed.so and b/src/plugins/proot/libs/arm64/libproot-xed.so differ diff --git a/src/plugins/proot/libs/arm64/libproot.so b/src/plugins/proot/libs/arm64/libproot.so old mode 100644 new mode 100755 index 9e414e872a..9a67199167 Binary files a/src/plugins/proot/libs/arm64/libproot.so and b/src/plugins/proot/libs/arm64/libproot.so differ diff --git a/src/plugins/proot/libs/arm64/libproot32.so b/src/plugins/proot/libs/arm64/libproot32.so old mode 100644 new mode 100755 index 27b95417c2..e353a6c35b Binary files a/src/plugins/proot/libs/arm64/libproot32.so and b/src/plugins/proot/libs/arm64/libproot32.so differ diff --git a/src/plugins/proot/libs/arm64/libtalloc.so b/src/plugins/proot/libs/arm64/libtalloc.so old mode 100644 new mode 100755 index b564e19de5..b058a56189 Binary files a/src/plugins/proot/libs/arm64/libtalloc.so and b/src/plugins/proot/libs/arm64/libtalloc.so differ diff --git a/src/plugins/proot/libs/x64/libaxs.so b/src/plugins/proot/libs/x64/libaxs.so new file mode 100644 index 0000000000..6f293cbbbb Binary files /dev/null and b/src/plugins/proot/libs/x64/libaxs.so differ diff --git a/src/plugins/proot/libs/x64/libproot-xed.so b/src/plugins/proot/libs/x64/libproot-xed.so old mode 100644 new mode 100755 index 89952891ab..807f1587da Binary files a/src/plugins/proot/libs/x64/libproot-xed.so and b/src/plugins/proot/libs/x64/libproot-xed.so differ diff --git a/src/plugins/proot/libs/x64/libproot.so b/src/plugins/proot/libs/x64/libproot.so old mode 100644 new mode 100755 index b54862e9d4..f6364b46ce Binary files a/src/plugins/proot/libs/x64/libproot.so and b/src/plugins/proot/libs/x64/libproot.so differ diff --git a/src/plugins/proot/libs/x64/libproot32.so b/src/plugins/proot/libs/x64/libproot32.so old mode 100644 new mode 100755 index 8bbcc6dd47..7c5ffc519d Binary files a/src/plugins/proot/libs/x64/libproot32.so and b/src/plugins/proot/libs/x64/libproot32.so differ diff --git a/src/plugins/proot/libs/x64/libtalloc.so b/src/plugins/proot/libs/x64/libtalloc.so old mode 100644 new mode 100755 index 19cbc7f511..3e87f9aaf4 Binary files a/src/plugins/proot/libs/x64/libtalloc.so and b/src/plugins/proot/libs/x64/libtalloc.so differ diff --git a/src/plugins/proot/plugin.xml b/src/plugins/proot/plugin.xml index 3eb98d6236..01cfc35cbc 100644 --- a/src/plugins/proot/plugin.xml +++ b/src/plugins/proot/plugin.xml @@ -11,6 +11,9 @@ + + + @@ -18,12 +21,18 @@ + + + + + + \ No newline at end of file diff --git a/src/plugins/sdcard/index.d.ts b/src/plugins/sdcard/index.d.ts index 41b4484fb4..fd6a6b7db8 100644 --- a/src/plugins/sdcard/index.d.ts +++ b/src/plugins/sdcard/index.d.ts @@ -35,10 +35,36 @@ interface DocumentFile { canWrite: boolean; filename: string; length: number; + persistedUriPermission: boolean; type: string; uri: string; } +interface WorkspaceFileEntry { + rootUrl: string; + parent: string; + parentUrl: string; + name: string; + path: string; + url: string; + uri: string; + mime?: string; + type?: string; + isDirectory: boolean; + isFile: boolean; + size: number; + modifiedDate: number; +} + +type WorkspaceEvent = + | { id: string; type: 'status'; action: 'status'; state: string; message: string; progress: number } + | { id: string; type: 'batch'; action: 'batch'; entries: WorkspaceFileEntry[] } + | { id: string; type: 'search-result'; action: 'search-result'; data: any } + | { id: string; type: 'search-results'; action: 'search-results'; data: any[] } + | { id: string; type: 'replace-result'; action: 'replace-result'; file: WorkspaceFileEntry; text: string } + | { id: string; type: 'progress'; action: 'progress'; data: number } + | { id: string; type: 'done' | 'done-searching' | 'done-replacing' | 'error'; action: string; [key: string]: any }; + interface SDcard { /** * Copy file/directory to given destination @@ -183,12 +209,14 @@ interface SDcard { ): void; /** * Opens gallery to select image - * @param onSuccess Callback function on success returns url of selected file + * Returns a temporary URI grant for the selected image. + * Use read/stats on the returned URI if you need to inspect or preview it. + * @param onSuccess Callback function on success returns URI of selected image * @param onFail Callback function on error returns error object * @param mimeType MimeType of file to be selected */ getImage( - onSuccess: (url: DocumentFile) => void, + onSuccess: (url: string) => void, onFail: (err: any) => void, mimeType: string, ): void; @@ -255,6 +283,48 @@ interface SDcard { ): { unwatch: () => void; }; + workspaceScan( + options: any, + onEvent: (event: WorkspaceEvent) => void, + onFail: (err: any) => void, + ): void; + workspaceUpdate( + options: any, + onSuccess: (result: { + added: number; + removed: number; + }) => void, + onFail: (err: any) => void, + ): void; + workspaceSearch( + options: any, + onEvent: (event: WorkspaceEvent) => void, + onFail: (err: any) => void, + ): void; + workspaceQuery( + options: any, + onSuccess: (result: { + entries: any[]; + cursor: number | null; + hasMore: boolean; + }) => void, + onFail: (err: any) => void, + ): void; + workspaceCancel( + id: string, + onSuccess?: (res: 'OK') => void, + onFail?: (err: any) => void, + ): void; + workspaceMarkDirty( + urls: string[], + onSuccess?: (res: 'OK') => void, + onFail?: (err: any) => void, + ): void; + workspaceClear( + roots: string[], + onSuccess?: (res: 'OK') => void, + onFail?: (err: any) => void, + ): void; } declare var sdcard: SDcard; diff --git a/src/plugins/sdcard/plugin.xml b/src/plugins/sdcard/plugin.xml index 19dda5cf50..85de5d63ab 100644 --- a/src/plugins/sdcard/plugin.xml +++ b/src/plugins/sdcard/plugin.xml @@ -21,6 +21,7 @@ + - \ No newline at end of file + diff --git a/src/plugins/sdcard/readme.md b/src/plugins/sdcard/readme.md index fda642ea8d..4af2dcc89b 100644 --- a/src/plugins/sdcard/readme.md +++ b/src/plugins/sdcard/readme.md @@ -89,17 +89,26 @@ interface SDcard { * @param onFail Callback function on error returns error object */ move(src: String, dest: String, onSuccess: (url: String) => void, onFail: (err: any) => void): void; - /** - * Opens file provider to select file - * @param onSuccess Callback function on success returns url of selected file - * @param onFail Callback function on error returns error object - * @param mimeType MimeType of file to be selected - */ - openDocumentFile(onSuccess: (url: String) => void, onFail: (err: any) => void, mimeType: String): void; - /** - * Renames the given file/directory to given new name - * @param src Url of file/directory - * @param newname New name + /** + * Opens file provider to select file + * @param onSuccess Callback function on success returns url of selected file + * @param onFail Callback function on error returns error object + * @param mimeType MimeType of file to be selected + */ + openDocumentFile(onSuccess: (url: String) => void, onFail: (err: any) => void, mimeType: String): void; + /** + * Opens gallery/photo picker to select an image + * Returns a temporary URI grant for the selected image. + * Use read/stats on the returned URI if you need to inspect or preview it. + * @param onSuccess Callback function on success returns URI of selected image + * @param onFail Callback function on error returns error object + * @param mimeType MimeType of file to be selected + */ + getImage(onSuccess: (url: String) => void, onFail: (err: any) => void, mimeType: String): void; + /** + * Renames the given file/directory to given new name + * @param src Url of file/directory + * @param newname New name * @param onSuccess Callback function on success returns url of renamed file * @param onFail Callback function on error returns error object */ diff --git a/src/plugins/sdcard/src/android/SDcard.java b/src/plugins/sdcard/src/android/SDcard.java index 35747393be..578d33dda3 100644 --- a/src/plugins/sdcard/src/android/SDcard.java +++ b/src/plugins/sdcard/src/android/SDcard.java @@ -24,6 +24,9 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.nio.charset.Charset; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; @@ -58,12 +61,15 @@ public class SDcard extends CordovaPlugin { private DocumentFile originalRootFile; private CallbackContext activityResultCallback; private HashMap fileObservers = new HashMap(); + private WorkspaceIndex workspaceIndex; public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); this.REQUEST_CODE = this.ACCESS_INTENT; this.context = cordova.getContext(); this.activity = cordova.getActivity(); + this.contentResolver = this.context.getContentResolver(); + this.workspaceIndex = new WorkspaceIndex(this.context); this.storageManager = (StorageManager) this.activity.getSystemService( Context.STORAGE_SERVICE ); @@ -105,6 +111,9 @@ public boolean execute( case "read": readFile(arg1, callback); break; + case "readAsText": + readAsText(arg1, arg2, callback); + break; case "write": writeFile( formatUri(arg1), @@ -113,6 +122,9 @@ public boolean execute( callback ); break; + case "writeText": + writeText(arg1, arg2, arg3, callback); + break; case "rename": rename(arg1, arg2, callback); break; @@ -153,6 +165,42 @@ public boolean execute( case "unwatch file": unwatchFile(arg1); break; + case "workspace scan": + workspaceIndex.scan( + args.optJSONObject(0) == null ? new JSONObject() : args.optJSONObject(0), + callback + ); + break; + case "workspace update": + workspaceIndex.update( + args.optJSONObject(0) == null ? new JSONObject() : args.optJSONObject(0), + callback + ); + break; + case "workspace search": + workspaceIndex.search( + args.optJSONObject(0) == null ? new JSONObject() : args.optJSONObject(0), + callback + ); + break; + case "workspace query": + workspaceIndex.query( + args.optJSONObject(0) == null ? new JSONObject() : args.optJSONObject(0), + callback + ); + break; + case "workspace cancel": + workspaceIndex.cancel(arg1); + callback.success("OK"); + break; + case "workspace mark dirty": + workspaceIndex.markDirty(args.optJSONArray(0)); + callback.success("OK"); + break; + case "workspace clear": + workspaceIndex.clear(args.optJSONArray(0)); + callback.success("OK"); + break; default: return false; } @@ -218,6 +266,11 @@ public void openDocumentFile(String mimeType, CallbackContext callback) { intent.setAction(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType(mimeType); + intent.addFlags( + Intent.FLAG_GRANT_READ_URI_PERMISSION | + Intent.FLAG_GRANT_WRITE_URI_PERMISSION | + Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION + ); activityResultCallback = callback; cordova.startActivityForResult(this, intent, this.OPEN_DOCUMENT); } @@ -226,6 +279,7 @@ public void getImage(String mimeType, CallbackContext callback) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); if (mimeType == null) mimeType = "image/*"; + intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType(mimeType); activityResultCallback = callback; cordova.startActivityForResult(this, intent, this.PICK_FROM_GALLERY); @@ -314,8 +368,6 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) { return; } - if (data == null) return; - if (resultCode == Activity.RESULT_CANCELED) { activityResultCallback.error("Operation cancelled"); return; @@ -323,20 +375,24 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_FROM_GALLERY) { if (resultCode == Activity.RESULT_OK) { + if (data == null) { + activityResultCallback.error("No result returned from picker"); + return; + } + Uri uri = data.getData(); + + if (uri == null && data.getClipData() != null) { + if (data.getClipData().getItemCount() > 0) { + uri = data.getClipData().getItemAt(0).getUri(); + } + } + if (uri == null) { activityResultCallback.error("No file selected"); } else { - try { - takePermission(uri); - activityResultCallback.success(uri.toString()); - } catch (Exception e) { - activityResultCallback.error( - "Error taking permission: " + e.getMessage() - ); - } + activityResultCallback.success(uri.toString()); } - //activityResultCallback.success(uri.toString()); } else { activityResultCallback.error("Operation cancelled"); } @@ -346,6 +402,11 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == OPEN_DOCUMENT) { if (resultCode == Activity.RESULT_OK) { try { + if (data == null) { + activityResultCallback.error("No result returned from picker"); + return; + } + Uri uri = data.getData(); if (uri == null) { @@ -353,7 +414,10 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) { return; } - takePermission(uri); + boolean persistedUriPermission = takePermission( + uri, + data.getFlags() + ); DocumentFile file = DocumentFile.fromSingleUri(context, uri); JSONObject res = new JSONObject(); @@ -362,6 +426,7 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) { res.put("filename", file.getName()); res.put("canWrite", canWrite(file.getUri())); res.put("uri", uri.toString()); + res.put("persistedUriPermission", persistedUriPermission); activityResultCallback.success(res); } catch (JSONException e) { activityResultCallback.error(e.toString()); @@ -380,13 +445,18 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) { } try { + if (data == null) { + activityResultCallback.error("No result returned from picker"); + return; + } + Uri uri = data.getData(); if (uri == null) { activityResultCallback.error("Empty uri"); return; } - takePermission(uri); + takePermission(uri, data.getFlags()); DocumentFile file = DocumentFile.fromTreeUri(context, uri); if (file != null && file.canWrite()) { activityResultCallback.success(uri.toString()); @@ -436,6 +506,102 @@ public void run() { ); } + private void readAsText(final String filename, final String encoding, final CallbackContext callback) { + cordova + .getThreadPool() + .execute( + new Runnable() { + public void run() { + try { + String formattedUri = formatUri(filename); + Uri uri = Uri.parse(formattedUri); + + String charSetName = encoding; + if (charSetName == null || charSetName.isEmpty() || "auto".equalsIgnoreCase(charSetName)) { + charSetName = "UTF-8"; + } + if (!Charset.isSupported(charSetName)) { + callback.error("Charset not supported: " + charSetName); + return; + } + Charset charset = Charset.forName(charSetName); + + InputStream is = context + .getContentResolver() + .openInputStream(uri); + + if (is == null) { + callback.error("File not found"); + return; + } + + StringBuilder sb = new StringBuilder(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset))) { + char[] buffer = new char[8192]; + int charsRead; + while ((charsRead = reader.read(buffer)) != -1) { + sb.append(buffer, 0, charsRead); + } + } + callback.success(sb.toString()); + } catch (Exception e) { + callback.error(e.toString()); + } + } + } + ); + } + + private void writeText( + final String filename, + final String content, + final String encoding, + final CallbackContext callback + ) { + final Context context = this.context; + + cordova + .getThreadPool() + .execute( + new Runnable() { + public void run() { + try { + String formattedUri = formatUri(filename); + DocumentFile file = getFile(formattedUri); + if (file == null) { + callback.error("File not found."); + return; + } + if (canWrite(file.getUri())) { + String charSetName = encoding; + if (charSetName == null || charSetName.isEmpty() || "auto".equalsIgnoreCase(charSetName)) { + charSetName = "UTF-8"; + } + if (!Charset.isSupported(charSetName)) { + callback.error("Charset not supported: " + charSetName); + return; + } + Charset charset = Charset.forName(charSetName); + + try (OutputStream op = context + .getContentResolver() + .openOutputStream(file.getUri(), "rwt")) { + byte[] bytes = content.getBytes(charset); + op.write(bytes); + op.flush(); + } + callback.success("OK"); + } else { + callback.error("No write permission"); + } + } catch (Exception e) { + callback.error(e.toString()); + } + } + } + ); + } + private void writeFile( final String filename, final String content, @@ -452,7 +618,7 @@ public void run() { try { DocumentFile file = getFile(filename); if (file == null) { - callback.error("File not fount."); + callback.error("File not found."); return; } if (canWrite(file.getUri())) { @@ -783,23 +949,28 @@ private void listDir(String src, String parentId, CallbackContext callback) { .execute( new Runnable() { public void run() { - Uri srcUri = Uri.parse(src); ContentResolver contentResolver = context.getContentResolver(); String parentDocId = parentId; - - if (parentDocId == null) { - parentDocId = DocumentsContract.getTreeDocumentId(srcUri); - } - - Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( - srcUri, - parentDocId - ); - JSONArray result = new JSONArray(); Cursor cursor = null; try { + Uri srcUri = Uri.parse(src); + + if (parentDocId == null) { + if (!DocumentsContract.isTreeUri(srcUri)) { + Log.w("sdCard", "Cannot list non-tree URI: " + src); + callback.error("Cannot read directory."); + return; + } + parentDocId = DocumentsContract.getTreeDocumentId(srcUri); + } + + Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( + srcUri, + parentDocId + ); + cursor = contentResolver.query( childrenUri, new String[] { @@ -990,13 +1161,22 @@ private DocumentFile getFile(String filePath) { return documentFile; } - private void takePermission(Uri uri) { - contentResolver = context.getContentResolver(); - contentResolver.takePersistableUriPermission( - uri, - Intent.FLAG_GRANT_WRITE_URI_PERMISSION | - Intent.FLAG_GRANT_READ_URI_PERMISSION - ); + private boolean takePermission(Uri uri, int intentFlags) { + int permissionFlags = + intentFlags & + (Intent.FLAG_GRANT_WRITE_URI_PERMISSION | + Intent.FLAG_GRANT_READ_URI_PERMISSION); + + if (permissionFlags == 0) return false; + + try { + contentResolver = context.getContentResolver(); + contentResolver.takePersistableUriPermission(uri, permissionFlags); + return true; + } catch (SecurityException | IllegalArgumentException error) { + Log.w("SDcard", "Unable to persist URI permission for " + uri, error); + return false; + } } public boolean canWrite(Uri uri) { diff --git a/src/plugins/sdcard/src/android/WorkspaceIndex.java b/src/plugins/sdcard/src/android/WorkspaceIndex.java new file mode 100644 index 0000000000..8215bee157 --- /dev/null +++ b/src/plugins/sdcard/src/android/WorkspaceIndex.java @@ -0,0 +1,2083 @@ +package com.foxdebug.sdcard; + +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.net.Uri; +import android.os.CancellationSignal; +import android.provider.DocumentsContract; +import android.provider.DocumentsContract.Document; +import android.util.Log; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; +import org.apache.cordova.CallbackContext; +import org.apache.cordova.PluginResult; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +class WorkspaceIndex { + private static final String TAG = "WorkspaceIndex"; + private static final String SEPARATOR = "::"; + private static final int DB_VERSION = 2; + private static final int BATCH_SIZE = 200; + private static final int MAX_INDEXED_CHARS = 512 * 1024; + private static final int INDEX_READ_LIMIT_BYTES = MAX_INDEXED_CHARS * 4; + private static final int DIRECT_SEARCH_READ_LIMIT_BYTES = 16 * 1024 * 1024; + private static final int EXPLICIT_INCLUDE_READ_LIMIT_BYTES = 128 * 1024 * 1024; + private static final int SAMPLE_BYTES = 8192; + private static final int MAX_MATCHES_PER_FILE = 5000; + private static final int SEARCH_RESULT_BATCH_MATCHES = 200; + + private static final Set BINARY_EXTENSIONS = new HashSet<>(); + private static final Set TEXT_EXTENSIONS = new HashSet<>(); + private static final Set BINARY_MIME_TYPES = new HashSet<>(); + private static final Set TEXT_MIME_TYPES = new HashSet<>(); + + static { + Collections.addAll( + BINARY_EXTENSIONS, + "3gp", + "7z", + "aab", + "aac", + "apk", + "avi", + "bin", + "bmp", + "class", + "db", + "dex", + "dll", + "doc", + "docx", + "eot", + "exe", + "flac", + "gif", + "gz", + "heic", + "ico", + "jar", + "jpeg", + "jpg", + "keystore", + "m4a", + "m4v", + "mkv", + "mov", + "mp3", + "mp4", + "o", + "odt", + "ogg", + "otf", + "pdf", + "png", + "ppt", + "pptx", + "pyc", + "rar", + "so", + "sqlite", + "sqlite3", + "tar", + "tgz", + "ttf", + "wav", + "webm", + "webp", + "woff", + "woff2", + "xls", + "xlsx", + "xz", + "zip" + ); + Collections.addAll( + TEXT_EXTENSIONS, + "astro", + "c", + "cc", + "cfg", + "conf", + "cpp", + "cs", + "css", + "csv", + "cxx", + "dart", + "env", + "go", + "graphql", + "h", + "hpp", + "htm", + "html", + "java", + "js", + "json", + "jsx", + "kt", + "kts", + "less", + "lua", + "md", + "mjs", + "php", + "properties", + "py", + "rb", + "rs", + "sass", + "scss", + "sh", + "sql", + "svg", + "swift", + "toml", + "ts", + "tsx", + "txt", + "vue", + "xml", + "yaml", + "yml" + ); + Collections.addAll( + BINARY_MIME_TYPES, + "application/java-archive", + "application/java-vm", + "application/octet-stream", + "application/pdf", + "application/vnd.android.package-archive", + "application/zip", + "application/x-7z-compressed", + "application/x-rar-compressed", + "application/x-sqlite3", + "application/x-tar", + "application/x-xz" + ); + Collections.addAll( + TEXT_MIME_TYPES, + "application/javascript", + "application/json", + "application/ld+json", + "application/sql", + "application/typescript", + "application/x-javascript", + "application/x-php", + "application/x-sh", + "application/x-yaml", + "application/xhtml+xml", + "application/xml", + "image/svg+xml" + ); + } + + private final Context context; + private final ContentResolver resolver; + private final ExecutorService indexExecutor = Executors.newSingleThreadExecutor(); + private final ExecutorService executor = Executors.newFixedThreadPool(2); + private final Map jobs = new ConcurrentHashMap<>(); + private final DB db; + + WorkspaceIndex(Context context) { + this.context = context.getApplicationContext(); + this.resolver = context.getContentResolver(); + this.db = new DB(this.context); + } + + void scan(JSONObject options, CallbackContext callback) { + final String id = options.optString("id", UUID.randomUUID().toString()); + final Job job = new Job(id); + jobs.put(id, job); + + indexExecutor.execute( + () -> { + try { + runScan(job, options, callback); + } catch (Exception error) { + sendError(callback, id, error); + } finally { + jobs.remove(id); + } + } + ); + } + + void update(JSONObject options, CallbackContext callback) { + indexExecutor.execute( + () -> { + try { + callback.success(runUpdate(options)); + } catch (Exception error) { + callback.error(error.getMessage() == null ? error.toString() : error.getMessage()); + } + } + ); + } + + void search(JSONObject options, CallbackContext callback) { + final String id = options.optString("id", UUID.randomUUID().toString()); + final Job job = new Job(id); + jobs.put(id, job); + + executor.execute( + () -> { + try { + runSearch(job, options, callback); + } catch (Exception error) { + sendError(callback, id, error); + } finally { + jobs.remove(id); + } + } + ); + } + + void query(JSONObject options, CallbackContext callback) { + executor.execute( + () -> { + try { + callback.success(runQuery(options)); + } catch (Exception error) { + callback.error(error.getMessage() == null ? error.toString() : error.getMessage()); + } + } + ); + } + + void cancel(String id) { + Job job = jobs.get(id); + if (job != null) job.cancel(); + } + + void markDirty(JSONArray urls) { + SQLiteDatabase writable = db.getWritableDatabase(); + for (int i = 0; i < urls.length(); i++) { + String url = urls.optString(i, null); + if (url == null || url.length() == 0) continue; + writable.delete("content", "url = ?", new String[] { url }); + } + } + + void clear(JSONArray roots) { + SQLiteDatabase writable = db.getWritableDatabase(); + if (roots == null || roots.length() == 0) { + writable.delete("content", null, null); + writable.delete("files", null, null); + writable.delete("workspaces", null, null); + return; + } + + for (int i = 0; i < roots.length(); i++) { + String root = roots.optString(i, null); + if (root == null || root.length() == 0) continue; + writable.delete("content", "url IN (SELECT url FROM files WHERE root_url = ?)", new String[] { root }); + writable.delete("files", "root_url = ?", new String[] { root }); + writable.delete("workspaces", "root_url = ?", new String[] { root }); + } + } + + private void runScan(Job job, JSONObject options, CallbackContext callback) + throws Exception { + if (job.cancelled) { + send(callback, baseEvent(job.id, "cancelled"), false); + return; + } + + String rootUrl = options.getString("rootUrl"); + String title = options.optString("title", basename(rootUrl)); + JSONArray exclude = options.optJSONArray("excludeFolders"); + boolean showHiddenFiles = options.optBoolean("showHiddenFiles", false); + String defaultEncoding = options.optString("defaultEncoding", "UTF-8"); + boolean indexContent = options.optBoolean("indexContent", false); + boolean emitEntries = options.optBoolean("emitEntries", true); + + JSONArray batch = new JSONArray(); + ScanStats stats = new ScanStats(); + + sendStatus(callback, job.id, "scanning", "Scanning project files", 0, true); + + SQLiteDatabase writable = db.getWritableDatabase(); + writable.beginTransaction(); + try { + ContentValues workspace = new ContentValues(); + workspace.put("root_url", rootUrl); + workspace.put("title", title); + workspace.put("indexed_at", System.currentTimeMillis()); + workspace.put("options_hash", String.valueOf(options.toString().hashCode())); + writable.replace("workspaces", null, workspace); + writable.delete("files", "root_url = ?", new String[] { rootUrl }); + + if (isSafUrl(rootUrl)) { + SafUrl rootSafUrl = parseSafUrl(rootUrl); + scanSafDir( + job, + callback, + rootSafUrl.treeUrl, + rootUrl, + rootSafUrl.docId, + rootUrl, + title, + title, + exclude, + showHiddenFiles, + defaultEncoding, + indexContent, + emitEntries, + batch, + stats + ); + } else { + File rootFile = fileFromUrl(rootUrl); + scanFileDir( + job, + callback, + rootUrl, + rootFile, + rootUrl, + title, + title, + exclude, + showHiddenFiles, + defaultEncoding, + indexContent, + emitEntries, + batch, + stats + ); + } + + if (job.cancelled) { + send(callback, baseEvent(job.id, "cancelled"), false); + return; + } + if (emitEntries) flushBatch(callback, job.id, batch); + writable.setTransactionSuccessful(); + } finally { + writable.endTransaction(); + } + + JSONObject done = baseEvent(job.id, "done"); + done.put("files", stats.files); + done.put("dirs", stats.dirs); + done.put("indexed", stats.indexed); + send(callback, done, false); + } + + private JSONObject runUpdate(JSONObject options) throws Exception { + String rootUrl = options.getString("rootUrl"); + String title = options.optString("title", getWorkspaceTitle(rootUrl)); + JSONArray removed = options.optJSONArray("removed"); + JSONArray added = options.optJSONArray("added"); + JSONArray exclude = options.optJSONArray("excludeFolders"); + boolean showHiddenFiles = options.optBoolean("showHiddenFiles", false); + String defaultEncoding = options.optString("defaultEncoding", "UTF-8"); + SQLiteDatabase writable = db.getWritableDatabase(); + int removedCount = 0; + int addedCount = 0; + + writable.beginTransaction(); + try { + if (removed != null) { + for (int i = 0; i < removed.length(); i++) { + String url = removed.optString(i, ""); + if (url.length() == 0 || rootUrl.equals(url)) continue; + removedCount += deleteIndexedSubtree(writable, rootUrl, url); + } + } + + if (added != null) { + for (int i = 0; i < added.length(); i++) { + JSONObject change = added.optJSONObject(i); + if (change == null) continue; + String url = change.optString("url", ""); + String parentUrl = change.optString("parentUrl", ""); + if (url.length() == 0 || parentUrl.length() == 0) continue; + + removedCount += deleteIndexedSubtree(writable, rootUrl, url); + FileEntry entry = readEntry(rootUrl, parentUrl, url, title); + if (entry == null) continue; + if (!showHiddenFiles && entry.name.startsWith(".")) continue; + + saveFile(entry); + addedCount += 1; + if ( + entry.isDirectory && + !shouldSkipDirectory(rootUrl, entry.url, entry.path, exclude) + ) { + Job job = new Job("update-" + UUID.randomUUID()); + ScanStats stats = new ScanStats(); + if (isSafUrl(url)) { + SafUrl rootSafUrl = parseSafUrl(rootUrl); + scanSafDir( + job, + null, + rootSafUrl.treeUrl, + rootUrl, + parseSafUrl(url).docId, + url, + entry.path, + title, + exclude, + showHiddenFiles, + defaultEncoding, + false, + false, + new JSONArray(), + stats + ); + } else { + scanFileDir( + job, + null, + rootUrl, + fileFromUrl(url), + url, + entry.path, + title, + exclude, + showHiddenFiles, + defaultEncoding, + false, + false, + new JSONArray(), + stats + ); + } + addedCount += stats.files + stats.dirs; + } + } + } + + ContentValues workspace = new ContentValues(); + workspace.put("root_url", rootUrl); + workspace.put("title", title); + workspace.put("indexed_at", System.currentTimeMillis()); + int updated = writable.update( + "workspaces", + workspace, + "root_url = ?", + new String[] { rootUrl } + ); + if (updated == 0) writable.insert("workspaces", null, workspace); + writable.setTransactionSuccessful(); + } finally { + writable.endTransaction(); + } + + JSONObject result = new JSONObject(); + result.put("added", addedCount); + result.put("removed", removedCount); + return result; + } + + private FileEntry readEntry( + String rootUrl, + String parentUrl, + String url, + String title + ) { + String parentPath = getIndexedPath(rootUrl, parentUrl, title); + if (isSafUrl(url)) { + Cursor cursor = null; + try { + cursor = + resolver.query( + formatSafUri(url), + new String[] { + Document.COLUMN_DISPLAY_NAME, + Document.COLUMN_MIME_TYPE, + Document.COLUMN_SIZE, + Document.COLUMN_LAST_MODIFIED, + }, + null, + null, + null + ); + if (cursor == null || !cursor.moveToFirst()) return null; + String name = cursor.getString(0); + String mime = normalizeMime(name, cursor.getString(1)); + boolean isDirectory = Document.MIME_TYPE_DIR.equals(mime); + return new FileEntry( + rootUrl, + parentUrl, + url, + name, + joinPath(parentPath, name), + mime, + isDirectory, + safeLong(cursor, 2), + safeLong(cursor, 3) + ); + } catch (Exception error) { + Log.d(TAG, "Unable to refresh SAF index entry " + url, error); + return null; + } finally { + if (cursor != null) cursor.close(); + } + } + + File file = fileFromUrl(url); + if (!file.exists()) return null; + String name = file.getName(); + boolean isDirectory = file.isDirectory(); + return new FileEntry( + rootUrl, + parentUrl, + url, + name, + joinPath(parentPath, name), + isDirectory + ? Document.MIME_TYPE_DIR + : normalizeMime(name, guessMime(name)), + isDirectory, + file.length(), + file.lastModified() + ); + } + + private String getIndexedPath( + String rootUrl, + String url, + String fallbackTitle + ) { + if (rootUrl.equals(url)) return fallbackTitle; + Cursor cursor = null; + try { + cursor = + db + .getReadableDatabase() + .query( + "files", + new String[] { "path" }, + "root_url = ? AND url = ?", + new String[] { rootUrl, url }, + null, + null, + null, + "1" + ); + if (cursor.moveToFirst()) return cursor.getString(0); + } finally { + if (cursor != null) cursor.close(); + } + return fallbackTitle; + } + + private String getWorkspaceTitle(String rootUrl) { + Cursor cursor = null; + try { + cursor = + db + .getReadableDatabase() + .query( + "workspaces", + new String[] { "title" }, + "root_url = ?", + new String[] { rootUrl }, + null, + null, + null, + "1" + ); + if (cursor.moveToFirst()) return cursor.getString(0); + } finally { + if (cursor != null) cursor.close(); + } + return basename(rootUrl); + } + + private int deleteIndexedSubtree( + SQLiteDatabase writable, + String rootUrl, + String url + ) { + ArrayDeque directories = new ArrayDeque<>(); + Set visitedDirectories = new HashSet<>(); + Set urls = new HashSet<>(); + directories.add(url); + urls.add(url); + + while (!directories.isEmpty()) { + String parentUrl = directories.removeFirst(); + if (!visitedDirectories.add(parentUrl)) continue; + Cursor cursor = null; + try { + cursor = + writable.query( + "files", + new String[] { "url", "is_directory" }, + "root_url = ? AND parent_url = ?", + new String[] { rootUrl, parentUrl }, + null, + null, + null + ); + while (cursor.moveToNext()) { + String childUrl = cursor.getString(0); + urls.add(childUrl); + if (cursor.getInt(1) != 0) directories.add(childUrl); + } + } finally { + if (cursor != null) cursor.close(); + } + } + + int deleted = 0; + for (String entryUrl : urls) { + writable.delete("content", "url = ?", new String[] { entryUrl }); + deleted += + writable.delete( + "files", + "root_url = ? AND url = ?", + new String[] { rootUrl, entryUrl } + ); + } + return deleted; + } + + private void scanFileDir( + Job job, + CallbackContext callback, + String rootUrl, + File dir, + String parentUrl, + String parentPath, + String title, + JSONArray exclude, + boolean showHiddenFiles, + String defaultEncoding, + boolean indexContent, + boolean emitEntries, + JSONArray batch, + ScanStats stats + ) throws Exception { + if (job.cancelled || dir == null) return; + File[] children; + try { + children = dir.listFiles(); + } catch (Exception error) { + Log.d(TAG, "Skipping unreadable directory " + dir, error); + return; + } + if (children == null) return; + + for (File child : children) { + if (job.cancelled) return; + String name = child.getName(); + if (!showHiddenFiles && name.startsWith(".")) continue; + + boolean isDir = child.isDirectory(); + String url = Uri.fromFile(child).toString(); + String path = joinPath(parentPath, name); + String mime = isDir ? Document.MIME_TYPE_DIR : normalizeMime(name, guessMime(name)); + FileEntry entry = new FileEntry( + rootUrl, + parentUrl, + url, + name, + path, + mime, + isDir, + child.length(), + child.lastModified() + ); + + addEntry(callback, job.id, batch, entry, stats, emitEntries); + if (isDir) { + if (shouldSkipDirectory(rootUrl, url, path, exclude)) continue; + try { + scanFileDir( + job, + callback, + rootUrl, + child, + url, + path, + title, + exclude, + showHiddenFiles, + defaultEncoding, + indexContent, + emitEntries, + batch, + stats + ); + } catch (Exception error) { + Log.d(TAG, "Skipping unreadable directory " + url, error); + } + } else { + if (indexContent) { + indexFile(entry, defaultEncoding); + stats.indexed += 1; + } + } + } + } + + private void scanSafDir( + Job job, + CallbackContext callback, + String treeUrl, + String rootUrl, + String parentDocId, + String parentUrl, + String parentPath, + String title, + JSONArray exclude, + boolean showHiddenFiles, + String defaultEncoding, + boolean indexContent, + boolean emitEntries, + JSONArray batch, + ScanStats stats + ) throws Exception { + if (job.cancelled) return; + Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( + Uri.parse(treeUrl), + parentDocId + ); + Cursor cursor = null; + CancellationSignal signal = new CancellationSignal(); + CancellationSignal previousSignal = job.setSignal(signal); + try { + try { + cursor = + resolver.query( + childrenUri, + new String[] { + Document.COLUMN_DOCUMENT_ID, + Document.COLUMN_DISPLAY_NAME, + Document.COLUMN_MIME_TYPE, + Document.COLUMN_SIZE, + Document.COLUMN_LAST_MODIFIED, + }, + null, + null, + null, + signal + ); + } catch (Exception error) { + Log.d(TAG, "Skipping unreadable SAF directory " + parentUrl, error); + return; + } + if (cursor == null) return; + + while (cursor.moveToNext()) { + if (job.cancelled) return; + String docId = cursor.getString(0); + String name = cursor.getString(1); + String mime = normalizeMime(name, cursor.getString(2)); + long size = safeLong(cursor, 3); + long modified = safeLong(cursor, 4); + + if (!showHiddenFiles && name != null && name.startsWith(".")) continue; + + boolean isDir = Document.MIME_TYPE_DIR.equals(mime); + String url = treeUrl + SEPARATOR + docId; + String path = joinPath(parentPath, name); + FileEntry entry = new FileEntry( + rootUrl, + parentUrl, + url, + name, + path, + mime, + isDir, + size, + modified + ); + + addEntry(callback, job.id, batch, entry, stats, emitEntries); + if (isDir) { + if (shouldSkipDirectory(rootUrl, url, path, exclude)) continue; + try { + scanSafDir( + job, + callback, + treeUrl, + rootUrl, + docId, + url, + path, + title, + exclude, + showHiddenFiles, + defaultEncoding, + indexContent, + emitEntries, + batch, + stats + ); + } catch (Exception error) { + Log.d(TAG, "Skipping unreadable SAF directory " + url, error); + } + } else { + if (indexContent) { + indexFile(entry, defaultEncoding); + stats.indexed += 1; + } + } + } + } catch (Exception error) { + Log.d(TAG, "Stopping unreadable SAF directory " + parentUrl, error); + } finally { + if (cursor != null) cursor.close(); + job.restoreSignal(signal, previousSignal); + } + } + + private void addEntry( + CallbackContext callback, + String id, + JSONArray batch, + FileEntry entry, + ScanStats stats, + boolean emitEntries + ) throws Exception { + saveFile(entry); + if (entry.isDirectory) stats.dirs += 1; else stats.files += 1; + if (!emitEntries) return; + batch.put(entry.toJSON()); + if (batch.length() >= BATCH_SIZE) { + flushBatch(callback, id, batch); + } + } + + private JSONObject runQuery(JSONObject options) throws Exception { + JSONArray roots = options.optJSONArray("roots"); + String text = options.optString("text", "").trim(); + String url = options.optString("url", ""); + boolean includeDirectories = options.optBoolean("includeDirectories", false); + int limit = Math.max(1, Math.min(options.optInt("limit", 200), 1000)); + int offset = Math.max(0, options.optInt("cursor", options.optInt("offset", 0))); + + StringBuilder where = new StringBuilder("1 = 1"); + List args = new ArrayList<>(); + appendRootsClause(where, args, roots); + if (url.length() > 0) { + where.append(" AND url = ?"); + args.add(url); + } + if (!includeDirectories) { + where.append(" AND is_directory = 0"); + } + if (text.length() > 0) { + where.append(" AND (name LIKE ? ESCAPE '\\' OR path LIKE ? ESCAPE '\\')"); + String pattern = "%" + escapeLike(text) + "%"; + args.add(pattern); + args.add(pattern); + } + + String order; + if (text.length() > 0) { + order = + "CASE WHEN name LIKE ? ESCAPE '\\' THEN 0 ELSE 1 END, " + + "name COLLATE NOCASE, path COLLATE NOCASE"; + args.add(escapeLike(text) + "%"); + } else { + order = "name COLLATE NOCASE, path COLLATE NOCASE"; + } + + String sql = + "SELECT root_url, parent_url, url, name, path, mime, is_directory, size, modified_date " + + "FROM files WHERE " + + where + + " ORDER BY " + + order + + " LIMIT ? OFFSET ?"; + args.add(String.valueOf(limit + 1)); + args.add(String.valueOf(offset)); + + JSONArray entries = new JSONArray(); + Cursor cursor = null; + boolean hasMore = false; + try { + cursor = db.getReadableDatabase().rawQuery(sql, args.toArray(new String[0])); + while (cursor.moveToNext()) { + if (entries.length() >= limit) { + hasMore = true; + break; + } + entries.put(fileEntryFromCursor(cursor).toJSON()); + } + } finally { + if (cursor != null) cursor.close(); + } + + JSONObject result = new JSONObject(); + result.put("entries", entries); + result.put("cursor", hasMore ? offset + entries.length() : JSONObject.NULL); + result.put("hasMore", hasMore); + return result; + } + + private void flushBatch(CallbackContext callback, String id, JSONArray batch) + throws JSONException { + if (batch.length() == 0) return; + JSONObject event = baseEvent(id, "batch"); + event.put("entries", new JSONArray(batch.toString())); + send(callback, event, true); + while (batch.length() > 0) batch.remove(0); + } + + private void runSearch(Job job, JSONObject options, CallbackContext callback) + throws Exception { + JSONArray files = options.optJSONArray("files"); + if (files == null) files = new JSONArray(); + files = mergeIndexedFiles(files, options.optJSONArray("roots")); + String search = options.optString("search", ""); + String replace = options.optString("replace", null); + String mode = options.optString("mode", "search"); + JSONObject searchOptions = options.optJSONObject("options"); + if (searchOptions == null) searchOptions = new JSONObject(); + JSONObject overlays = options.optJSONObject("overlays"); + if (overlays == null) overlays = new JSONObject(); + String defaultEncoding = options.optString("defaultEncoding", "UTF-8"); + boolean useIndex = options.optBoolean("useIndex", false); + boolean batchResults = options.optBoolean("batchResults", false); + + Pattern pattern = compileSearchPattern(search, searchOptions); + int total = files.length(); + int processed = 0; + int lastProgress = -1; + + sendStatus(callback, job.id, "searching", "Searching files", 0, true); + + for (int i = 0; i < total; i++) { + if (job.cancelled) return; + JSONObject file = files.getJSONObject(i); + int progress = total == 0 ? 100 : (processed * 100) / total; + if (progress != lastProgress) { + sendProgress(callback, job.id, progress); + lastProgress = progress; + } + if (!isSupportedUrl(file.optString("url"))) { + processed += 1; + continue; + } + if (shouldSkipSearchFile(file, searchOptions)) { + processed += 1; + continue; + } + + boolean allowLargeFile = isExplicitlyIncluded(file, searchOptions); + String content; + try { + content = + getFileContent( + file, + overlays, + defaultEncoding, + useIndex, + allowLargeFile + ); + } catch (Exception error) { + Log.d(TAG, "Skipping unreadable search file " + file.optString("url"), error); + processed += 1; + continue; + } + if (content == null) { + processed += 1; + continue; + } + + if ("replace".equals(mode)) { + String replacement = replace == null ? "" : replace; + Matcher matcher = pattern.matcher(new SearchInput(content, job)); + String text = searchOptions.optBoolean("regExp", false) + ? replaceAllJs(matcher, content, replacement) + : matcher.replaceAll(Matcher.quoteReplacement(replacement)); + JSONObject result = baseEvent(job.id, "replace-result"); + result.put("file", file); + result.put("text", text); + send(callback, result, true); + } else { + searchInContent(file, content, pattern, job, callback, batchResults); + } + + processed += 1; + } + + sendProgress(callback, job.id, 100); + send(callback, baseEvent(job.id, "replace".equals(mode) ? "done-replacing" : "done-searching"), false); + } + + /** + * Replaces every match using JavaScript String.prototype.replace substitution + * rules ($$, $&, $`, $', $1..$99, $), so regex replacements behave the + * same as the JS worker path. + */ + static String replaceAllJs(Matcher matcher, String content, String replace) { + StringBuilder out = new StringBuilder(content.length()); + boolean namedGroups = hasNamedGroups(matcher.pattern().pattern()); + int last = 0; + while (matcher.find()) { + out.append(content, last, matcher.start()); + appendJsSubstitution(out, matcher, content, replace, namedGroups); + last = matcher.end(); + } + out.append(content, last, content.length()); + return out.toString(); + } + + /** + * Whether the pattern declares a named capture group, ignoring escaped text, + * \Q...\E quotes and character classes. + */ + static boolean hasNamedGroups(String pattern) { + int len = pattern.length(); + int classDepth = 0; + for (int i = 0; i < len; i++) { + char c = pattern.charAt(i); + if (c == '\\') { + if (i + 1 < len && pattern.charAt(i + 1) == 'Q') { + int end = pattern.indexOf("\\E", i + 2); + if (end == -1) return false; + i = end + 1; + } else { + i++; + } + } else if (classDepth > 0) { + if (c == '[') classDepth++; + else if (c == ']') classDepth--; + } else if (c == '[') { + classDepth = 1; + if (i + 1 < len && pattern.charAt(i + 1) == '^') i++; + if (i + 1 < len && pattern.charAt(i + 1) == ']') i++; + } else if ( + c == '(' && + i + 3 < len && + pattern.charAt(i + 1) == '?' && + pattern.charAt(i + 2) == '<' && + Character.isLetter(pattern.charAt(i + 3)) + ) { + return true; + } + } + return false; + } + + private static void appendJsSubstitution( + StringBuilder out, + Matcher matcher, + String content, + String replace, + boolean namedGroups + ) { + int groups = matcher.groupCount(); + int len = replace.length(); + for (int i = 0; i < len; i++) { + char c = replace.charAt(i); + if (c != '$' || i + 1 >= len) { + out.append(c); + continue; + } + + char next = replace.charAt(i + 1); + if (next == '$') { + out.append('$'); + i++; + } else if (next == '&') { + out.append(content, matcher.start(), matcher.end()); + i++; + } else if (next == '`') { + out.append(content, 0, matcher.start()); + i++; + } else if (next == '\'') { + out.append(content, matcher.end(), content.length()); + i++; + } else if (next >= '0' && next <= '9') { + int index = next - '0'; + int consumed = 1; + if (i + 2 < len) { + char digit = replace.charAt(i + 2); + if (digit >= '0' && digit <= '9') { + int twoDigit = index * 10 + (digit - '0'); + if (twoDigit >= 1 && twoDigit <= groups) { + index = twoDigit; + consumed = 2; + } + } + } + if (index >= 1 && index <= groups) { + String group = matcher.group(index); + if (group != null) out.append(group); + i += consumed; + } else { + out.append(c); + } + } else if (next == '<') { + int close = replace.indexOf('>', i + 2); + boolean found = false; + String group = null; + if (close != -1) { + try { + group = matcher.group(replace.substring(i + 2, close)); + found = true; + } catch (IllegalArgumentException ignored) { + // JS: an unknown name is empty when the pattern has named groups. + found = namedGroups; + } + } + if (found) { + if (group != null) out.append(group); + i = close; + } else { + out.append(c); + } + } else { + out.append(c); + } + } + } + + private Pattern compileSearchPattern(String search, JSONObject options) + throws PatternSyntaxException { + boolean regExp = options.optBoolean("regExp", false); + boolean wholeWord = options.optBoolean("wholeWord", false); + boolean caseSensitive = options.optBoolean("caseSensitive", false); + + String pattern = regExp ? search : Pattern.quote(search); + if (wholeWord) pattern = "\\b" + pattern + "\\b"; + + int flags = Pattern.MULTILINE; + if (!caseSensitive) flags |= Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE; + return Pattern.compile(pattern, flags); + } + + private void searchInContent( + JSONObject file, + String content, + Pattern pattern, + Job job, + CallbackContext callback, + boolean batchResults + ) throws JSONException { + SearchInput input = new SearchInput(content, job); + Matcher matcher = pattern.matcher(input); + JSONArray matches = new JSONArray(); + int matchCount = 0; + int cursor = 0; + int row = 0; + int column = 0; + while (true) { + input.check(); + if (!matcher.find()) break; + String word = content.substring(matcher.start(), Math.min(matcher.end(), matcher.start() + 160)); + int start = matcher.start(); + int end = matcher.end(); + String[] surrounding = getSurrounding(content, word, start, end); + while (cursor < start) { + if ((cursor & 1023) == 0) input.check(); + if (content.charAt(cursor) == '\n') { + row += 1; + column = 0; + } else { + column += 1; + } + cursor += 1; + } + JSONObject startPosition = lineColumn(row, column); + while (cursor < end) { + if ((cursor & 1023) == 0) input.check(); + if (content.charAt(cursor) == '\n') { + row += 1; + column = 0; + } else { + column += 1; + } + cursor += 1; + } + JSONObject endPosition = lineColumn(row, column); + JSONObject match = new JSONObject(); + match.put("match", word); + match.put("renderText", surrounding[1]); + match.put("line", surrounding[0].trim()); + match.put("position", position(startPosition, endPosition)); + matches.put(match); + matchCount++; + if (matchCount == MAX_MATCHES_PER_FILE) { + sendSearchMatches(callback, job.id, file, matches, batchResults, matcher.find()); + return; + } + if (matches.length() >= SEARCH_RESULT_BATCH_MATCHES) { + sendSearchMatches(callback, job.id, file, matches, batchResults, false); + matches = new JSONArray(); + input.renewDeadline(); + } + } + + sendSearchMatches(callback, job.id, file, matches, batchResults, false); + } + + private void sendSearchMatches(CallbackContext callback, String id, JSONObject file, + JSONArray matches, boolean batchResults, boolean limited) throws JSONException { + if (matches.length() == 0) return; + JSONObject data = new JSONObject(); + data.put("file", file); + data.put("matches", matches); + data.put("limited", limited); + JSONObject event = baseEvent(id, batchResults ? "search-results" : "search-result"); + event.put("data", batchResults ? new JSONArray().put(data) : data); + send(callback, event, true); + } + + private String getFileContent( + JSONObject file, + JSONObject overlays, + String defaultEncoding, + boolean useIndex, + boolean allowLargeFile + ) throws Exception { + String url = file.optString("url"); + if (overlays.has(url)) return overlays.optString(url, ""); + + long size = file.optLong("size", 0); + long modified = normalizeModified(file); + + if (useIndex) { + SQLiteDatabase readable = db.getReadableDatabase(); + Cursor cursor = null; + try { + cursor = + readable.query( + "content", + new String[] { "text", "size", "modified_date" }, + "url = ?", + new String[] { url }, + null, + null, + null + ); + if (cursor != null && cursor.moveToFirst()) { + long cachedSize = cursor.getLong(1); + long cachedModified = cursor.getLong(2); + if ((size == 0 || cachedSize == size) && (modified == 0 || cachedModified == modified)) { + return cursor.getString(0); + } + } + } finally { + if (cursor != null) cursor.close(); + } + } + + FileEntry entry = FileEntry.fromJSON(file); + if (useIndex && !allowLargeFile) { + String indexed = indexFile(entry, defaultEncoding); + if (indexed != null) return indexed; + } + return readFileText( + entry, + defaultEncoding, + allowLargeFile ? EXPLICIT_INCLUDE_READ_LIMIT_BYTES : DIRECT_SEARCH_READ_LIMIT_BYTES, + allowLargeFile ? EXPLICIT_INCLUDE_READ_LIMIT_BYTES : DIRECT_SEARCH_READ_LIMIT_BYTES + ); + } + + private String indexFile(FileEntry entry, String defaultEncoding) { + if (entry.isDirectory || isBinary(entry) || entry.size > INDEX_READ_LIMIT_BYTES) { + return null; + } + + try { + String text = readFileText( + entry, + defaultEncoding, + INDEX_READ_LIMIT_BYTES, + MAX_INDEXED_CHARS + ); + if (text == null) return null; + String encoding = normalizeEncoding(defaultEncoding); + + ContentValues values = new ContentValues(); + values.put("url", entry.url); + values.put("size", entry.size); + values.put("modified_date", entry.modifiedDate); + values.put("encoding", encoding); + values.put("text", text); + values.put("lower_text", text.toLowerCase(Locale.ROOT)); + values.put("indexed_at", System.currentTimeMillis()); + db.getWritableDatabase().replace("content", null, values); + return text; + } catch (Exception error) { + Log.d(TAG, "Unable to index " + entry.url, error); + return null; + } + } + + private String readFileText( + FileEntry entry, + String defaultEncoding, + int readLimitBytes, + int maxChars + ) + throws Exception { + if (entry.isDirectory || isBinary(entry) || entry.size > readLimitBytes) { + return null; + } + + byte[] bytes = readBytes(entry.url, readLimitBytes + 1); + if (bytes.length > readLimitBytes) return null; + String encoding = detectEncoding(bytes, defaultEncoding); + if (isSingleByteEncoding(encoding) && looksBinary(bytes)) return null; + String text = new String(bytes, Charset.forName(encoding)); + if (text.length() > maxChars || hasBinaryChars(text)) return null; + return text; + } + + private byte[] readBytes(String url, int limit) throws Exception { + InputStream input = null; + try { + if (isSafUrl(url)) { + input = resolver.openInputStream(formatSafUri(url)); + } else { + input = new FileInputStream(fileFromUrl(url)); + } + if (input == null) return new byte[0]; + + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buffer = new byte[8192]; + int read; + int total = 0; + while ((read = input.read(buffer)) != -1) { + total += read; + if (total > limit) { + output.write(buffer, 0, read - (total - limit)); + break; + } + output.write(buffer, 0, read); + } + return output.toByteArray(); + } finally { + if (input != null) input.close(); + } + } + + private void saveFile(FileEntry entry) { + ContentValues values = new ContentValues(); + values.put("url", entry.url); + values.put("root_url", entry.rootUrl); + values.put("parent_url", entry.parentUrl); + values.put("path", entry.path); + values.put("name", entry.name); + values.put("mime", entry.mime); + values.put("is_directory", entry.isDirectory ? 1 : 0); + values.put("size", entry.size); + values.put("modified_date", entry.modifiedDate); + values.put("indexed_at", System.currentTimeMillis()); + values.put("skipped_reason", isBinary(entry) ? "binary" : null); + db.getWritableDatabase().replace("files", null, values); + } + + private JSONArray mergeIndexedFiles(JSONArray explicitFiles, JSONArray roots) + throws JSONException { + JSONArray result = new JSONArray(); + Set seen = new HashSet<>(); + for (int i = 0; i < explicitFiles.length(); i++) { + JSONObject file = explicitFiles.optJSONObject(i); + if (file == null) continue; + String url = file.optString("url", ""); + if (url.length() == 0 || !seen.add(url)) continue; + result.put(file); + } + + if (roots == null || roots.length() == 0) return result; + + StringBuilder where = new StringBuilder("is_directory = 0"); + List args = new ArrayList<>(); + appendRootsClause(where, args, roots); + Cursor cursor = null; + try { + cursor = + db + .getReadableDatabase() + .query( + "files", + new String[] { + "root_url", + "parent_url", + "url", + "name", + "path", + "mime", + "is_directory", + "size", + "modified_date", + }, + where.toString(), + args.toArray(new String[0]), + null, + null, + null + ); + while (cursor.moveToNext()) { + FileEntry entry = fileEntryFromCursor(cursor); + if (seen.add(entry.url)) result.put(entry.toJSON()); + } + } finally { + if (cursor != null) cursor.close(); + } + return result; + } + + private FileEntry fileEntryFromCursor(Cursor cursor) { + return new FileEntry( + cursor.getString(0), + cursor.getString(1), + cursor.getString(2), + cursor.getString(3), + cursor.getString(4), + cursor.isNull(5) ? null : cursor.getString(5), + cursor.getInt(6) != 0, + safeLong(cursor, 7), + safeLong(cursor, 8) + ); + } + + private void appendRootsClause( + StringBuilder where, + List args, + JSONArray roots + ) { + if (roots == null || roots.length() == 0) return; + where.append(" AND root_url IN ("); + boolean added = false; + for (int i = 0; i < roots.length(); i++) { + String root = roots.optString(i, ""); + if (root.length() == 0) continue; + if (added) where.append(','); + where.append('?'); + args.add(root); + added = true; + } + if (!added) { + where.append("NULL"); + } + where.append(')'); + } + + private String escapeLike(String value) { + return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_"); + } + + private boolean shouldSkipDirectory( + String rootUrl, + String url, + String path, + JSONArray excludes + ) { + if (isExcluded(path, excludes) || isExcluded(path + "/", excludes)) { + return true; + } + + return ( + rootUrl != null && + rootUrl.startsWith("content://com.termux.documents/tree/") && + url != null && + url.matches(".*::/data/data/com\\.termux/files/home/storage(?:/)?$") + ); + } + + private boolean shouldSkipSearchFile(JSONObject file, JSONObject options) { + if (FileEntry.fromJSON(file).isBinary()) return true; + String path = file.optString("path", ""); + if (path.length() == 0) return false; + + JSONArray excludes = splitPatterns(options.optString("exclude", "")); + JSONArray includes = splitPatterns(options.optString("include", "")); + if (includes.length() == 0) includes.put("**"); + + return matchesAny(path, excludes) || !matchesAny(path, includes); + } + + private boolean isExplicitlyIncluded(JSONObject file, JSONObject options) { + String path = file.optString("path", ""); + if (path.length() == 0) return false; + JSONArray includes = splitPatterns(options.optString("include", "")); + return includes.length() > 0 && matchesAny(path, includes); + } + + private JSONArray splitPatterns(String value) { + JSONArray result = new JSONArray(); + if (value == null || value.trim().length() == 0) return result; + String[] patterns = value.split(","); + for (String pattern : patterns) { + String item = pattern.trim(); + if (item.length() > 0) result.put(item); + } + return result; + } + + private boolean isExcluded(String path, JSONArray excludes) { + return matchesAny(path, excludes); + } + + private boolean matchesAny(String path, JSONArray patterns) { + if (patterns == null) return false; + for (int i = 0; i < patterns.length(); i++) { + String pattern = patterns.optString(i, ""); + if (globMatches(path, pattern)) return true; + } + return false; + } + + private boolean globMatches(String path, String pattern) { + if (pattern == null || pattern.length() == 0) return false; + String normalizedPath = path.replace('\\', '/'); + String normalizedPattern = pattern.replace('\\', '/'); + if ("**".equals(normalizedPattern)) return true; + + String regex = globToRegex(normalizedPattern); + Pattern compiled = Pattern.compile(regex); + if (compiled.matcher(normalizedPath).matches()) return true; + + int slash = normalizedPath.lastIndexOf('/'); + String basename = slash >= 0 ? normalizedPath.substring(slash + 1) : normalizedPath; + return compiled.matcher(basename).matches(); + } + + private String globToRegex(String glob) { + StringBuilder regex = new StringBuilder("^"); + for (int i = 0; i < glob.length(); i++) { + char ch = glob.charAt(i); + if (ch == '*') { + boolean doublestar = i + 1 < glob.length() && glob.charAt(i + 1) == '*'; + if (doublestar) { + i++; + if (i + 1 < glob.length() && glob.charAt(i + 1) == '/') { + regex.append("(?:.*/)?"); + i++; + } else { + regex.append(".*"); + } + } else { + regex.append("[^/]*"); + } + } else if (ch == '?') { + regex.append('.'); + } else if ("\\.[]{}()+-^$|".indexOf(ch) >= 0) { + regex.append('\\').append(ch); + } else { + regex.append(ch); + } + } + regex.append('$'); + return regex.toString(); + } + + private boolean isBinary(FileEntry entry) { + return entry.isBinary(); + } + + private String detectEncoding(byte[] bytes, String defaultEncoding) { + if (bytes.length >= 3 && (bytes[0] & 0xff) == 0xef && (bytes[1] & 0xff) == 0xbb && (bytes[2] & 0xff) == 0xbf) { + return "UTF-8"; + } + if (bytes.length >= 2 && (bytes[0] & 0xff) == 0xff && (bytes[1] & 0xff) == 0xfe) { + return "UTF-16LE"; + } + if (bytes.length >= 2 && (bytes[0] & 0xff) == 0xfe && (bytes[1] & 0xff) == 0xff) { + return "UTF-16BE"; + } + String utf16 = detectUtf16ByNullPattern(bytes); + if (utf16 != null) return utf16; + return normalizeEncoding(defaultEncoding); + } + + private String detectUtf16ByNullPattern(byte[] bytes) { + int sample = Math.min(bytes.length, SAMPLE_BYTES); + if (sample < 8) return null; + + int evenNulls = 0; + int oddNulls = 0; + int pairs = sample / 2; + for (int i = 0; i + 1 < sample; i += 2) { + if (bytes[i] == 0) evenNulls++; + if (bytes[i + 1] == 0) oddNulls++; + } + if (oddNulls > pairs * 0.35 && evenNulls < pairs * 0.05) return "UTF-16LE"; + if (evenNulls > pairs * 0.35 && oddNulls < pairs * 0.05) return "UTF-16BE"; + return null; + } + + private boolean isSingleByteEncoding(String encoding) { + String normalized = encoding == null ? "" : encoding.toUpperCase(Locale.ROOT); + return !normalized.startsWith("UTF-16") && !normalized.startsWith("UTF-32"); + } + + private boolean looksBinary(byte[] bytes) { + int sample = Math.min(bytes.length, SAMPLE_BYTES); + if (sample == 0) return false; + + int control = 0; + int high = 0; + for (int i = 0; i < sample; i++) { + int value = bytes[i] & 0xff; + if (value == 0) return true; + if ( + value < 32 && + value != 9 && + value != 10 && + value != 13 && + value != 12 + ) { + control++; + } + if (value >= 0x80) high++; + } + return control > Math.max(8, sample * 0.02) && high < sample * 0.5; + } + + private String normalizeEncoding(String defaultEncoding) { + if (defaultEncoding == null || defaultEncoding.equals("auto") || defaultEncoding.length() == 0) { + return "UTF-8"; + } + try { + if (Charset.isSupported(defaultEncoding)) return defaultEncoding; + } catch (Exception ignored) {} + return "UTF-8"; + } + + private boolean hasBinaryChars(String text) { + int len = Math.min(text.length(), 2048); + for (int i = 0; i < len; i++) { + char ch = text.charAt(i); + if ( + (ch >= 0 && ch <= 8) || + ch == 11 || + (ch >= 14 && ch <= 31) || + ch == 127 + ) { + return true; + } + } + return false; + } + + private JSONObject position(JSONObject start, JSONObject end) throws JSONException { + JSONObject position = new JSONObject(); + position.put("start", start); + position.put("end", end); + return position; + } + + private JSONObject lineColumn(int row, int column) throws JSONException { + JSONObject result = new JSONObject(); + result.put("row", row); + result.put("column", column); + return result; + } + + // Java's Matcher does not honor thread interruption. Check its input access + // so backtracking is subject to the same cancellation and deadline as results. + private static final class SearchInput implements CharSequence { + final String content; + final Job job; + long deadline = System.nanoTime() + 2_000_000_000L; + int accesses; + + SearchInput(String content, Job job) { + this.content = content; + this.job = job; + } + + void renewDeadline() { deadline = System.nanoTime() + 2_000_000_000L; } + + void check() { + if (job.cancelled) throw new IllegalStateException("Search cancelled"); + if (System.nanoTime() > deadline) throw new IllegalStateException("Search timed out; simplify the expression"); + } + + public int length() { return content.length(); } + public char charAt(int index) { + if ((accesses++ & 1023) == 0) check(); + return content.charAt(index); + } + public CharSequence subSequence(int start, int end) { return content.subSequence(start, end); } + public String toString() { return content; } + } + + private String[] getSurrounding(String content, String word, int start, int end) { + int max = 160; + int remaining = Math.max(0, max - (end - start)); + int snippetStart = start; + int leftLimit = Math.max(0, start - remaining / 2); + while (snippetStart > leftLimit) { + char c = content.charAt(snippetStart - 1); + if (c == '\n' || c == '\r') break; + snippetStart--; + } + int snippetEnd = Math.min(end, start + max); + int rightLimit = Math.min(content.length(), snippetStart + max); + while (snippetEnd < rightLimit) { + char c = content.charAt(snippetEnd); + if (c == '\n' || c == '\r') break; + snippetEnd++; + } + StringBuilder line = new StringBuilder(); + if (snippetStart > 0 && content.charAt(snippetStart - 1) != '\n' && content.charAt(snippetStart - 1) != '\r') line.append("..."); + line.append(content.substring(snippetStart, snippetEnd).trim()); + if (snippetEnd < content.length() && content.charAt(snippetEnd) != '\n' && content.charAt(snippetEnd) != '\r') line.append("..."); + String renderText = word; + + return new String[] { + line.toString().replaceAll("[\\r\\n]+", " ⏎ "), + renderText.replaceAll("[\\r\\n]+", " ⏎ "), + }; + } + + private void sendStatus( + CallbackContext callback, + String id, + String state, + String message, + int progress, + boolean keep + ) throws JSONException { + JSONObject event = baseEvent(id, "status"); + event.put("state", state); + event.put("message", message); + event.put("progress", progress); + send(callback, event, keep); + } + + private void sendProgress(CallbackContext callback, String id, int progress) + throws JSONException { + JSONObject event = baseEvent(id, "progress"); + event.put("data", progress); + send(callback, event, true); + } + + private JSONObject baseEvent(String id, String type) throws JSONException { + JSONObject event = new JSONObject(); + event.put("id", id); + event.put("type", type); + event.put("action", type); + return event; + } + + private void send(CallbackContext callback, JSONObject event, boolean keep) { + PluginResult result = new PluginResult(PluginResult.Status.OK, event); + result.setKeepCallback(keep); + callback.sendPluginResult(result); + } + + private void sendError(CallbackContext callback, String id, Exception error) { + try { + JSONObject event = baseEvent(id, "error"); + event.put("error", error.getMessage() == null ? error.toString() : error.getMessage()); + send(callback, event, false); + } catch (JSONException jsonError) { + callback.error(error.getMessage()); + } + } + + private boolean isSupportedUrl(String url) { + return url != null && (url.startsWith("file:") || url.startsWith("content:")); + } + + private boolean isSafUrl(String url) { + return url != null && url.startsWith("content:"); + } + + private Uri formatSafUri(String url) { + SafUrl safUrl = parseSafUrl(url); + return DocumentsContract.buildDocumentUriUsingTree( + Uri.parse(safUrl.treeUrl), + safUrl.docId + ); + } + + private SafUrl parseSafUrl(String url) { + if (url.contains(SEPARATOR)) { + String[] parts = url.split(SEPARATOR, 2); + return new SafUrl(parts[0], parts[1]); + } + Uri treeUri = Uri.parse(url); + return new SafUrl(url, DocumentsContract.getTreeDocumentId(treeUri)); + } + + private File fileFromUrl(String url) { + Uri uri = Uri.parse(url); + return new File(uri.getPath()); + } + + private long safeLong(Cursor cursor, int index) { + try { + if (cursor.isNull(index)) return 0; + return cursor.getLong(index); + } catch (Exception ignored) { + return 0; + } + } + + private long normalizeModified(JSONObject file) { + long modified = file.optLong("modifiedDate", 0); + if (modified == 0) modified = file.optLong("lastModified", 0); + return modified; + } + + private String joinPath(String parent, String name) { + if (parent == null || parent.length() == 0) return name; + if (name == null || name.length() == 0) return parent; + if (parent.endsWith("/")) return parent + name; + return parent + "/" + name; + } + + private String basename(String url) { + if (url == null || url.length() == 0) return ""; + int slash = url.lastIndexOf('/'); + return slash >= 0 ? url.substring(slash + 1) : url; + } + + private String guessMime(String name) { + if (name == null) return null; + String lower = name.toLowerCase(Locale.ROOT); + if (lower.endsWith(".js")) return "application/javascript"; + if (lower.endsWith(".ts") || lower.endsWith(".tsx")) return "application/typescript"; + if (lower.endsWith(".jsx")) return "application/javascript"; + if (lower.endsWith(".json")) return "application/json"; + if (lower.endsWith(".svg")) return "image/svg+xml"; + if (lower.endsWith(".html") || lower.endsWith(".htm")) return "text/html"; + if (lower.endsWith(".css")) return "text/css"; + if (lower.endsWith(".md")) return "text/markdown"; + if (lower.endsWith(".txt")) return "text/plain"; + if (lower.endsWith(".xml")) return "application/xml"; + return null; + } + + private String normalizeMime(String name, String mime) { + String guessed = guessMime(name); + if (guessed != null && (mime == null || mime.length() == 0 || "application/octet-stream".equals(mime))) { + return guessed; + } + return mime; + } + + private static class Job { + final String id; + volatile boolean cancelled = false; + volatile CancellationSignal signal; + + Job(String id) { + this.id = id; + } + + void cancel() { + cancelled = true; + CancellationSignal activeSignal = signal; + if (activeSignal != null) activeSignal.cancel(); + } + + CancellationSignal setSignal(CancellationSignal nextSignal) { + CancellationSignal previousSignal = signal; + signal = nextSignal; + if (cancelled) nextSignal.cancel(); + return previousSignal; + } + + void restoreSignal( + CancellationSignal currentSignal, + CancellationSignal previousSignal + ) { + if (signal != currentSignal) return; + signal = previousSignal; + if (cancelled && previousSignal != null) previousSignal.cancel(); + } + } + + private static class ScanStats { + int files = 0; + int dirs = 0; + int indexed = 0; + } + + private static class SafUrl { + final String treeUrl; + final String docId; + + SafUrl(String treeUrl, String docId) { + this.treeUrl = treeUrl; + this.docId = docId; + } + } + + private static class FileEntry { + final String rootUrl; + final String parentUrl; + final String url; + final String name; + final String path; + final String mime; + final boolean isDirectory; + final long size; + final long modifiedDate; + + FileEntry( + String rootUrl, + String parentUrl, + String url, + String name, + String path, + String mime, + boolean isDirectory, + long size, + long modifiedDate + ) { + this.rootUrl = rootUrl; + this.parentUrl = parentUrl; + this.url = url; + this.name = name == null ? "" : name; + this.path = path == null ? this.name : path; + this.mime = mime; + this.isDirectory = isDirectory; + this.size = Math.max(0, size); + this.modifiedDate = Math.max(0, modifiedDate); + } + + JSONObject toJSON() throws JSONException { + JSONObject json = new JSONObject(); + json.put("rootUrl", rootUrl); + json.put("parent", parentUrl); + json.put("parentUrl", parentUrl); + json.put("url", url); + json.put("uri", url); + json.put("name", name); + json.put("path", path); + json.put("mime", mime); + json.put("type", mime); + json.put("isDirectory", isDirectory); + json.put("isFile", !isDirectory); + json.put("size", size); + json.put("modifiedDate", modifiedDate); + return json; + } + + static FileEntry fromJSON(JSONObject json) { + return new FileEntry( + json.optString("rootUrl", ""), + json.optString("parentUrl", json.optString("parent", "")), + json.optString("url", ""), + json.optString("name", ""), + json.optString("path", ""), + json.optString("mime", json.optString("type", null)), + json.optBoolean("isDirectory", false), + json.optLong("size", 0), + json.optLong("modifiedDate", json.optLong("lastModified", 0)) + ); + } + + boolean isBinary() { + if (isDirectory) return false; + String normalizedMime = mime == null ? "" : mime.toLowerCase(Locale.ROOT).split(";")[0].trim(); + if (normalizedMime.startsWith("text/") || TEXT_MIME_TYPES.contains(normalizedMime)) return false; + if (isTextExtension(name)) return false; + if ( + normalizedMime.startsWith("audio/") || + normalizedMime.startsWith("font/") || + normalizedMime.startsWith("image/") || + normalizedMime.startsWith("model/") || + normalizedMime.startsWith("video/") || + BINARY_MIME_TYPES.contains(normalizedMime) + ) { + return true; + } + + String lowerName = name.toLowerCase(Locale.ROOT); + int dot = lowerName.lastIndexOf('.'); + if (dot < 0) return false; + String ext = lowerName.substring(dot + 1); + if (BINARY_EXTENSIONS.contains(ext)) return true; + int previousDot = lowerName.lastIndexOf('.', dot - 1); + return previousDot >= 0 && BINARY_EXTENSIONS.contains(lowerName.substring(previousDot + 1)); + } + + private boolean isTextExtension(String filename) { + String lowerName = filename == null ? "" : filename.toLowerCase(Locale.ROOT); + int dot = lowerName.lastIndexOf('.'); + return dot >= 0 && TEXT_EXTENSIONS.contains(lowerName.substring(dot + 1)); + } + } + + private static class DB extends SQLiteOpenHelper { + DB(Context context) { + super(context, "acode_workspace_index.db", null, DB_VERSION); + } + + @Override + public void onCreate(SQLiteDatabase db) { + db.execSQL( + "CREATE TABLE IF NOT EXISTS workspaces (" + + "root_url TEXT PRIMARY KEY, " + + "title TEXT, " + + "indexed_at INTEGER, " + + "options_hash TEXT" + + ")" + ); + db.execSQL( + "CREATE TABLE IF NOT EXISTS files (" + + "url TEXT, " + + "root_url TEXT, " + + "parent_url TEXT, " + + "path TEXT, " + + "name TEXT, " + + "mime TEXT, " + + "is_directory INTEGER, " + + "size INTEGER, " + + "modified_date INTEGER, " + + "indexed_at INTEGER, " + + "skipped_reason TEXT, " + + "PRIMARY KEY (root_url, url)" + + ")" + ); + db.execSQL( + "CREATE TABLE IF NOT EXISTS content (" + + "url TEXT PRIMARY KEY, " + + "size INTEGER, " + + "modified_date INTEGER, " + + "encoding TEXT, " + + "text TEXT, " + + "lower_text TEXT, " + + "indexed_at INTEGER" + + ")" + ); + db.execSQL("CREATE INDEX IF NOT EXISTS idx_files_root ON files(root_url)"); + db.execSQL("CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parent_url)"); + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + db.execSQL("DROP TABLE IF EXISTS content"); + db.execSQL("DROP TABLE IF EXISTS files"); + db.execSQL("DROP TABLE IF EXISTS workspaces"); + onCreate(db); + } + } +} diff --git a/src/plugins/sdcard/www/plugin.js b/src/plugins/sdcard/www/plugin.js index ed6761e71d..7d994f8aa2 100644 --- a/src/plugins/sdcard/www/plugin.js +++ b/src/plugins/sdcard/www/plugin.js @@ -44,10 +44,16 @@ module.exports = { read: function (filename, onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'SDcard', 'read', [filename]); }, + readAsText: function (filename, encoding, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'SDcard', 'readAsText', [filename, encoding]); + }, write: function (filename, content, onSuccess, onFail) { var _isBuffer = content instanceof ArrayBuffer; cordova.exec(onSuccess, onFail, 'SDcard', 'write', [filename, content, _isBuffer]); }, + writeText: function (filename, content, encoding, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'SDcard', 'writeText', [filename, content, encoding]); + }, stats: function (filename, onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'SDcard', 'stats', [filename]); }, @@ -62,5 +68,26 @@ module.exports = { }, listEncodings: function (onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'SDcard', 'list encodings', []); + }, + workspaceScan: function (options, onEvent, onFail) { + cordova.exec(onEvent, onFail, 'SDcard', 'workspace scan', [options || {}]); + }, + workspaceUpdate: function (options, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'SDcard', 'workspace update', [options || {}]); + }, + workspaceSearch: function (options, onEvent, onFail) { + cordova.exec(onEvent, onFail, 'SDcard', 'workspace search', [options || {}]); + }, + workspaceQuery: function (options, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'SDcard', 'workspace query', [options || {}]); + }, + workspaceCancel: function (id, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'SDcard', 'workspace cancel', [id]); + }, + workspaceMarkDirty: function (urls, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'SDcard', 'workspace mark dirty', [urls || []]); + }, + workspaceClear: function (roots, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'SDcard', 'workspace clear', [roots || []]); } -}; \ No newline at end of file +}; diff --git a/src/plugins/server/src/android/com/foxdebug/server/NanoHTTPDWebserver.java b/src/plugins/server/src/android/com/foxdebug/server/NanoHTTPDWebserver.java index 05887c4a6f..c6f1a0fa0d 100644 --- a/src/plugins/server/src/android/com/foxdebug/server/NanoHTTPDWebserver.java +++ b/src/plugins/server/src/android/com/foxdebug/server/NanoHTTPDWebserver.java @@ -116,17 +116,19 @@ Response serveFile( long endAt = -1; String range = header.get("range"); if (range != null) { - if (range.startsWith("bytes=")) { - range = range.substring("bytes=".length()); - int minus = range.indexOf('-'); - try { - if (minus > 0) { - startFrom = Long.parseLong(range.substring(0, minus)); - endAt = Long.parseLong(range.substring(minus + 1)); - } - } catch (NumberFormatException ignored) {} - } - } + if (range.startsWith("bytes=")) { + range = range.substring("bytes=".length()); + int minus = range.indexOf('-'); + try { + if (minus > 0) { + startFrom = Long.parseLong(range.substring(0, minus)); + endAt = Long.parseLong(range.substring(minus + 1)); + } + } catch (NumberFormatException error) { + Log.w("NanoHTTPDWebserver", "Invalid range header: " + range, error); + } + } + } // get if-range header. If present, it must match etag or else we // should ignore the range request @@ -334,11 +336,13 @@ private InputStream getInputStream(DocumentFile file) return contentResolver.openInputStream(uri); } - private JSONObject getJSONObject(JSONObject ob, String key) { - JSONObject jsonObject = null; - try { - jsonObject = ob.getJSONObject(key); - } catch (JSONException e) {} - return jsonObject; - } -} + private JSONObject getJSONObject(JSONObject ob, String key) { + JSONObject jsonObject = null; + try { + jsonObject = ob.getJSONObject(key); + } catch (JSONException e) { + Log.w("NanoHTTPDWebserver", "Missing or invalid JSON object for key: " + key, e); + } + return jsonObject; + } +} diff --git a/src/plugins/sftp/index.d.ts b/src/plugins/sftp/index.d.ts index 62d0afeedf..ca7db1d098 100644 --- a/src/plugins/sftp/index.d.ts +++ b/src/plugins/sftp/index.d.ts @@ -12,10 +12,25 @@ interface Stats { uri: string; } -interface ExecResult{ +interface ExecResult{ code: Number; result: String; -} +} + +interface ShellEvent { + type: "ready" | "data" | "exit" | "error"; + sessionId?: string; + data?: string; + exitCode?: number; + message?: string; +} + +interface SftpProfileInfo { + hostname: string; + port: number; + username: string; + authType: "password" | "key"; +} interface Sftp { /** @@ -25,28 +40,16 @@ interface Sftp { * @param onFail */ exec(command: String, onSucess: (res: ExecResult)=>void, onFail: (err: any) => void): void; - /** - * Connects to SFTP server - * @param host Hostname of the server - * @param port port numer - * @param username Username - * @param password Password or private key file to authenticate the server - * @param onSuccess Callback function on success returns url of copied file/dir - * @param onFail Callback function on error returns error object - */ - connectUsingPassoword(host: String, port: Number, username: String, password: String, onSuccess: () => void, onFail: (err: any) => void): void; - - /** - * Connects to SFTP server - * @param host Hostname of the server - * @param port port numer - * @param username Username - * @param keyFile Password or private key file to authenticate the server - * @param passphrase Passphrase for keyfile - * @param onSuccess Callback function on success returns url of copied file/dir - * @param onFail Callback function on error returns error object - */ - connectUsingKeyFile(host: String, port: Number, username: String, keyFile: String, passphrase: String, onSuccess: () => void, onFail: (err: any) => void): void; + /** Connects using credentials held by the native profile store. */ + connectUsingProfile(profileId: String, onSuccess: () => void, onFail: (err: any) => void): void; + /** Tests a profile once and returns its remote working directory. */ + testProfile(profileId: String, requestId: String, timeout: Number, onSuccess: (home: String) => void, onFail: (err: any) => void): void; + /** Cancels an in-flight profile connection or test. */ + cancelConnection(requestId: String, onSuccess: () => void, onFail: (err: any) => void): void; + saveProfile(profileId: String | null, host: String, port: Number, username: String, authType: String, password: String, keyFile: String, passphrase: String, onSuccess: (profileId: String) => void, onFail: (err: any) => void): void; + editProfile(profileId: String | null, host: String, port: Number, username: String, authType: String, password: String, keyFile: String, passphrase: String, onSuccess: (profile: SftpProfileInfo & {profileId: string}) => void, onFail: (err: any) => void): void; + getProfileInfo(profileId: String, onSuccess: (profile: SftpProfileInfo & {profileId: string}) => void, onFail: (err: any) => void): void; + deleteProfile(profileId: String, onSuccess: () => void, onFail: (err: any) => void): void; /** * Gets file from the server. @@ -78,7 +81,11 @@ interface Sftp { * @param onSuccess * @param onFail */ - isConnected(onSuccess: (connectionId: String) => void, onFail: (err: any) => void): void; -} + isConnected(onSuccess: (connectionId: String) => void, onFail: (err: any) => void): void; + openShellUsingProfile(profileId: String, cols: Number, rows: Number, onEvent: (event: ShellEvent) => void, onFail: (err: any) => void): void; + writeShell(sessionId: String, data: String, onSuccess: () => void, onFail: (err: any) => void): void; + resizeShell(sessionId: String, cols: Number, rows: Number, onSuccess: () => void, onFail: (err: any) => void): void; + closeShell(sessionId: String, onSuccess: () => void, onFail: (err: any) => void): void; +} -declare var sftp: Sftp; \ No newline at end of file +declare var sftp: Sftp; diff --git a/src/plugins/sftp/plugin.xml b/src/plugins/sftp/plugin.xml index e9d37d67ef..527d729b33 100644 --- a/src/plugins/sftp/plugin.xml +++ b/src/plugins/sftp/plugin.xml @@ -21,12 +21,13 @@ - + + - + - - + + diff --git a/src/plugins/sftp/src/com/foxdebug/sftp/Sftp.java b/src/plugins/sftp/src/com/foxdebug/sftp/Sftp.java index ce5f466876..a72466607d 100644 --- a/src/plugins/sftp/src/com/foxdebug/sftp/Sftp.java +++ b/src/plugins/sftp/src/com/foxdebug/sftp/Sftp.java @@ -1,26 +1,38 @@ package com.foxdebug.sftp; import android.app.Activity; +import android.app.AlertDialog; import android.content.ContentResolver; import android.content.Context; import android.net.Uri; +import android.util.Base64; import android.util.Log; import androidx.documentfile.provider.DocumentFile; import com.sshtools.client.SshClient; import com.sshtools.client.SshClient.SshClientBuilder; +import com.sshtools.client.SshClientContext; +import com.sshtools.client.SessionChannelNG; import com.sshtools.client.sftp.SftpClient; import com.sshtools.client.sftp.SftpClient.SftpClientBuilder; import com.sshtools.client.sftp.SftpFile; import com.sshtools.client.sftp.TransferCancelledException; +import com.sshtools.common.knownhosts.HostKeyVerification; import com.sshtools.common.permissions.PermissionDeniedException; +import com.sshtools.common.policy.FileSystemPolicy; import com.sshtools.common.publickey.InvalidPassphraseException; import com.sshtools.common.publickey.SshKeyUtils; import com.sshtools.common.sftp.SftpFileAttributes; import com.sshtools.common.sftp.SftpStatusException; import com.sshtools.common.ssh.SshException; +import com.sshtools.common.ssh.Channel; +import com.sshtools.common.ssh.ChannelEventListener; +import com.sshtools.common.ssh.RequestFuture; import com.sshtools.common.ssh.components.SshKeyPair; +import com.sshtools.common.ssh.components.SshPublicKey; import com.sshtools.common.ssh.components.jce.JCEProvider; -import com.sshtools.common.util.FileUtils; +import com.sshtools.common.util.UnsignedInteger32; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -31,245 +43,1079 @@ import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; +import java.nio.ByteBuffer; import java.nio.channels.UnresolvedAddressException; import java.nio.charset.StandardCharsets; import java.security.Security; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; +import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import java.util.Arrays; import org.bouncycastle.jce.provider.BouncyCastleProvider; public class Sftp extends CordovaPlugin { private static final String TAG = "SFTP"; + // Maverick's 16 MB default is allocated in full for every SFTP subsystem. + // A smaller mobile window prevents connection bursts from exhausting the heap. + private static final long SFTP_MAX_WINDOW_SIZE = 1024L * 1024L; + private static final long SFTP_MIN_WINDOW_SIZE = 128L * 1024L; + private static final long DEFAULT_CONNECT_TIMEOUT_MS = 10000L; + private static final long MIN_CONNECT_TIMEOUT_MS = 1000L; + private static final long MAX_CONNECT_TIMEOUT_MS = 30000L; + private static boolean cryptoProviderConfigured; + private final Object connectionLock = new Object(); + private final Map connectionAttempts = + new ConcurrentHashMap<>(); + private final Map remoteShells = new ConcurrentHashMap<>(); private SshClient ssh; private SftpClient sftp; private Context context; private Activity activity; private String connectionID; + private SftpSecurityStore securityStore; + + private final class ConnectionAttempt { + + private final CallbackContext callback; + private final AtomicBoolean cancelled = new AtomicBoolean(false); + private final AtomicBoolean completed = new AtomicBoolean(false); + private volatile Future future; + + private ConnectionAttempt(CallbackContext callback) { + this.callback = callback; + } + + private void setFuture(Future future) { + this.future = future; + if (cancelled.get()) future.cancel(true); + } + + private boolean isCancelled() { + return cancelled.get(); + } + + private void cancel() { + cancelled.set(true); + Future current = future; + if (current != null) current.cancel(true); + error(connectionCancelledError()); + } + + private void success() { + if (completed.compareAndSet(false, true)) callback.success(); + } + + private void success(String value) { + if (completed.compareAndSet(false, true)) callback.success(value); + } + + private void error(String message) { + if (completed.compareAndSet(false, true)) callback.error(message); + } + + private void error(JSONObject error) { + if (completed.compareAndSet(false, true)) callback.error(error); + } + } + + private final class ConnectionSecurity { + + private final String hostname; + private final int port; + private volatile JSONObject failure; + + private ConnectionSecurity(String hostname, int port) { + this.hostname = hostname; + this.port = port; + } + + private void configure(SshClientContext sshContext) { + configureClient(sshContext); + sshContext.setHostKeyVerification( + new HostKeyVerification() { + @Override + public boolean verifyHost(String host, SshPublicKey publicKey) + throws SshException { + try { + String fingerprint = publicKey.getFingerprint(); + String algorithm = publicKey.getAlgorithm(); + String encodedKey = Base64.encodeToString( + publicKey.getEncoded(), + Base64.NO_WRAP + ); + String endpoint = hostname + ":" + port; + JSONObject trusted = securityStore.getKnownHost(endpoint); + if (trusted == null) { + if ( + confirmUnknownHost(endpoint, algorithm, fingerprint) + ) { + securityStore.trustHost( + endpoint, + algorithm, + fingerprint, + encodedKey + ); + return true; + } + failure = hostKeyFailure( + "HOST_KEY_REJECTED", + endpoint, + fingerprint, + null + ); + return false; + } + + String expected = trusted.optString("fingerprint"); + String expectedKey = trusted.optString("publicKey"); + if ( + (!expectedKey.isEmpty() && !encodedKey.equals(expectedKey)) || + (expectedKey.isEmpty() && !fingerprint.equals(expected)) + ) { + failure = hostKeyFailure( + "HOST_KEY_CHANGED", + endpoint, + fingerprint, + expected + ); + showChangedHostKey(endpoint, expected, fingerprint); + return false; + } + return true; + } catch (JSONException | InterruptedException e) { + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + throw new SshException( + "Could not verify the SSH host key", + SshException.HOST_KEY_ERROR, + e + ); + } + } + } + ); + } + + private boolean report(CallbackContext callback) { + JSONObject error = takeFailure(); + if (error == null) return false; + callback.error(error); + return true; + } + + private JSONObject takeFailure() { + JSONObject error = failure; + failure = null; + return error; + } + } + + private final class RemoteShell { + + private final String id; + private final SshClient client; + private final SessionChannelNG channel; + private final CallbackContext streamCallback; + private final AtomicBoolean finished = new AtomicBoolean(false); + private final ExecutorService inputWriter = Executors.newSingleThreadExecutor(); + + private RemoteShell( + String id, + SshClient client, + SessionChannelNG channel, + CallbackContext streamCallback + ) { + this.id = id; + this.client = client; + this.channel = channel; + this.streamCallback = streamCallback; + } + + private void sendData(ByteBuffer source) { + if (finished.get() || source == null || !source.hasRemaining()) return; + + ByteBuffer data = source.asReadOnlyBuffer(); + byte[] bytes = new byte[data.remaining()]; + data.get(bytes); + try { + JSONObject event = new JSONObject(); + event.put("type", "data"); + event.put("data", Base64.encodeToString(bytes, Base64.NO_WRAP)); + sendShellEvent(streamCallback, event, true); + } catch (JSONException e) { + finish(null, e.getMessage()); + } + } + + private void finish(Integer exitCode, String error) { + if (!finished.compareAndSet(false, true)) return; + remoteShells.remove(id, this); + inputWriter.shutdownNow(); + + try { + channel.close(); + } catch (Exception e) { + Log.w(TAG, "Failed to close SSH shell channel " + id, e); + } + try { + client.close(); + } catch (IOException e) { + Log.w(TAG, "Failed to close SSH shell connection " + id, e); + } + + try { + JSONObject event = new JSONObject(); + event.put("type", error == null ? "exit" : "error"); + if (exitCode != null) event.put("exitCode", exitCode); + if (error != null) event.put("message", error); + sendShellEvent(streamCallback, event, false); + } catch (JSONException e) { + streamCallback.error(errMessage(e)); + } + } + + private void write(String input, CallbackContext callback) { + if (finished.get()) { + callback.error("SSH shell is not connected"); + return; + } + + try { + inputWriter.execute( + new Runnable() { + @Override + public void run() { + try { + byte[] data = input.getBytes(StandardCharsets.UTF_8); + channel.getOutputStream().write(data); + channel.getOutputStream().flush(); + callback.success(); + } catch (IOException e) { + finish(null, errMessage(e)); + callback.error(errMessage(e)); + } + } + } + ); + } catch (RejectedExecutionException e) { + callback.error("SSH shell is not connected"); + } + } + } public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); context = cordova.getContext(); activity = cordova.getActivity(); + securityStore = new SftpSecurityStore(context); System.setProperty("maverick.log.nothread", "true"); + configureCryptoProvider(); } - public boolean execute( - String action, - JSONArray args, - CallbackContext callback + private static synchronized void configureCryptoProvider() { + if (cryptoProviderConfigured) return; + + Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); + Security.insertProviderAt(new BouncyCastleProvider(), 1); + JCEProvider.enableBouncyCastle(true); + cryptoProviderConfigured = true; + } + + private static void configureClient(SshClientContext sshContext) { + FileSystemPolicy policy = sshContext.getPolicy(FileSystemPolicy.class); + policy.setSftpMaxWindowSize( + new UnsignedInteger32(SFTP_MAX_WINDOW_SIZE) + ); + policy.setSftpMinWindowSize( + new UnsignedInteger32(SFTP_MIN_WINDOW_SIZE) + ); + policy.setMaximumNumberofAsyncSFTPRequests(4); + } + + private void closeConnectionQuietly() { + SftpClient previousSftp = sftp; + SshClient previousSsh = ssh; + sftp = null; + ssh = null; + connectionID = null; + + if (previousSftp != null) { + try { + previousSftp.quit(); + } catch (Exception e) { + Log.w(TAG, "Failed to close the SFTP subsystem", e); + } + } + if (previousSsh != null) { + try { + previousSsh.close(); + } catch (Exception e) { + Log.w(TAG, "Failed to close the SSH connection", e); + } + } + } + + private boolean establishConnection( + SshClientBuilder builder, + String newConnectionID, + ConnectionSecurity security, + ConnectionAttempt attempt + ) throws IOException, SshException, PermissionDeniedException { + synchronized (connectionLock) { + closeConnectionQuietly(); + ssh = builder.onConfigure(security::configure).build(); + if (attempt.isCancelled()) { + closeConnectionQuietly(); + return false; + } + if (!ssh.isConnected()) { + closeConnectionQuietly(); + return false; + } + + connectionID = newConnectionID; + try { + sftp = SftpClientBuilder.create().withClient(ssh).build(); + } catch (IOException | SshException | PermissionDeniedException e) { + closeConnectionQuietly(); + throw e; + } + + if (attempt.isCancelled()) { + closeConnectionQuietly(); + return false; + } + + try { + sftp.getSubsystemChannel().setCharsetEncoding("UTF-8"); + } catch (UnsupportedEncodingException | SshException e) { + Log.w(TAG, "Failed to set UTF-8 encoding, using the default", e); + } + return true; + } + } + + private static void sendShellEvent( + CallbackContext callback, + JSONObject event, + boolean keepCallback ) { + PluginResult result = new PluginResult(PluginResult.Status.OK, event); + result.setKeepCallback(keepCallback); + callback.sendPluginResult(result); + } + + private static JSONObject hostKeyFailure( + String code, + String host, + String fingerprint, + String expectedFingerprint + ) throws JSONException { + JSONObject error = new JSONObject(); + error.put("code", code); + error.put("host", host); + error.put("fingerprint", fingerprint); + if (expectedFingerprint != null) { + error.put("expectedFingerprint", expectedFingerprint); + } + return error; + } + + private static JSONObject connectionCancelledError() { + JSONObject error = new JSONObject(); try { - Method method = getClass() - .getDeclaredMethod(action, JSONArray.class, CallbackContext.class); + error.put("code", "SFTP_CONNECT_CANCELLED"); + error.put("message", "SFTP connection cancelled"); + error.put("cancelled", true); + error.put("nonRetryable", true); + } catch (JSONException ignored) {} + return error; + } - if (method != null) { - method.invoke(this, args, callback); - return true; + private boolean confirmUnknownHost( + String endpoint, + String algorithm, + String fingerprint + ) throws InterruptedException { + if (activity == null || activity.isFinishing()) return false; + + CountDownLatch decision = new CountDownLatch(1); + AtomicBoolean trusted = new AtomicBoolean(false); + activity.runOnUiThread( + () -> { + AlertDialog dialog = new AlertDialog.Builder(activity) + .setTitle("Unknown SSH host") + .setMessage( + "This is the first connection to " + + endpoint + + ".\n\nKey type: " + + algorithm + + "\nFingerprint: " + + fingerprint + + "\n\nVerify this fingerprint before trusting the host." + ) + .setNegativeButton("Cancel", (ignored, which) -> decision.countDown()) + .setPositiveButton( + "Trust and connect", + (ignored, which) -> { + trusted.set(true); + decision.countDown(); + } + ) + .create(); + dialog.setOnCancelListener(ignored -> decision.countDown()); + dialog.show(); } - } catch (NoSuchMethodException e) { - callback.error("Method not found: " + action); - return false; - } catch (SecurityException e) { - callback.error("Security exception: " + e.getMessage()); - return false; - } catch (Exception e) { - callback.error("Exception: " + e.getMessage()); - return false; + ); + decision.await(); + return trusted.get(); + } + + private void showChangedHostKey( + String endpoint, + String expectedFingerprint, + String receivedFingerprint + ) { + if (activity == null || activity.isFinishing()) return; + activity.runOnUiThread( + () -> + new AlertDialog.Builder(activity) + .setTitle("SSH host key changed") + .setMessage( + "The identity of " + + endpoint + + " has changed. The connection was blocked.\n\nExpected: " + + expectedFingerprint + + "\nReceived: " + + receivedFingerprint + ) + .setPositiveButton("Close", null) + .show() + ); + } + + private void closeRemoteShells() { + for (RemoteShell shell : remoteShells.values()) { + shell.finish(null, null); + } + remoteShells.clear(); + } + + private void cancelConnectionAttempts() { + for (ConnectionAttempt attempt : connectionAttempts.values()) { + attempt.cancel(); } + connectionAttempts.clear(); + } - return false; + @Override + public void onReset() { + cancelConnectionAttempts(); + closeRemoteShells(); + super.onReset(); + } + + @Override + public void onDestroy() { + cancelConnectionAttempts(); + closeRemoteShells(); + super.onDestroy(); + } + + private SshClientBuilder buildProfileBuilder(JSONObject profile) + throws IOException, InvalidPassphraseException, JSONException { + return buildProfileBuilder(profile, DEFAULT_CONNECT_TIMEOUT_MS); + } + + private SshClientBuilder buildProfileBuilder( + JSONObject profile, + long connectTimeout + ) throws IOException, InvalidPassphraseException, JSONException { + SshClientBuilder builder = SshClientBuilder.create() + .withHostname(profile.getString("hostname")) + .withPort(profile.optInt("port", 22)) + .withConnectTimeout(connectTimeout) + .withUsername(profile.getString("username")); + + if ("key".equals(profile.optString("authType"))) { + byte[] privateKey = Base64.decode( + profile.getString("privateKey"), + Base64.NO_WRAP + ); + SshKeyPair keyPair = SshKeyUtils.getPrivateKey( + new ByteArrayInputStream(privateKey), + profile.optString("passphrase") + ); + builder.withIdentities(keyPair); + } else { + builder.withPassword(profile.optString("password")); + } + return builder; + } + + private byte[] readUri(String uriString) throws IOException { + if (uriString == null || uriString.isEmpty()) { + throw new IOException("Private key file is required"); + } + try ( + InputStream input = context + .getContentResolver() + .openInputStream(Uri.parse(uriString)); + ByteArrayOutputStream output = new ByteArrayOutputStream() + ) { + if (input == null) throw new IOException("Could not open key file"); + byte[] buffer = new byte[8192]; + int read; + while ((read = input.read(buffer)) != -1) { + output.write(buffer, 0, read); + } + return output.toByteArray(); + } + } + + private void openRemoteShell( + SshClient shellClient, + int columns, + int rows, + CallbackContext callback + ) throws SshException, JSONException, IOException { + if (!shellClient.isConnected()) { + shellClient.close(); + throw new IOException("Failed to establish SSH connection"); + } + + String shellID = UUID.randomUUID().toString(); + SessionChannelNG channel; + try { + channel = shellClient.openSessionChannel(true); + } catch (SshException e) { + shellClient.close(); + throw e; + } + RemoteShell shell = new RemoteShell(shellID, shellClient, channel, callback); + remoteShells.put(shellID, shell); + + channel.addEventListener( + new ChannelEventListener() { + @Override + public void onChannelDataIn(Channel source, ByteBuffer data) { + shell.sendData(data); + } + + @Override + public void onChannelExtendedData( + Channel source, + ByteBuffer data, + int type + ) { + shell.sendData(data); + } + + @Override + public void onChannelClose(Channel source) { + int exitCode = channel.getExitCode(); + shell.finish( + exitCode == SessionChannelNG.EXITCODE_NOT_RECEIVED ? null : exitCode, + null + ); + } + + @Override + public void onChannelError(Channel source, Throwable error) { + shell.finish(null, error == null ? "SSH shell error" : error.toString()); + } + } + ); + + RequestFuture pty = channel + .allocatePseudoTerminal("xterm-256color", columns, rows) + .waitFor(30000L); + if (!pty.isSuccess()) { + shell.finish(null, "Remote server rejected PTY allocation"); + return; + } + if (shell.finished.get()) return; + + RequestFuture start = channel.startShell().waitFor(30000L); + if (!start.isSuccess()) { + shell.finish(null, "Remote server rejected the interactive shell"); + return; + } + if (shell.finished.get()) return; + + JSONObject ready = new JSONObject(); + ready.put("type", "ready"); + ready.put("sessionId", shellID); + sendShellEvent(callback, ready, true); } - public void connectUsingPassword(JSONArray args, CallbackContext callback) { + public void openShellUsingProfile(JSONArray args, CallbackContext callback) { cordova .getThreadPool() .execute( new Runnable() { public void run() { + ConnectionSecurity security = null; try { - String host = args.optString(0); - int port = args.optInt(1); - String username = args.optString(2); - String password = args.optString(3); - JCEProvider.enableBouncyCastle(true); - Log.d( - TAG, - "Connecting to " + host + ":" + port + " as " + username + String profileID = args.optString(0); + int columns = Math.max(1, args.optInt(1, 80)); + int rows = Math.max(1, args.optInt(2, 24)); + JSONObject profile = securityStore.getProfile(profileID); + ConnectionSecurity profileSecurity = new ConnectionSecurity( + profile.getString("hostname"), + profile.optInt("port", 22) + ); + security = profileSecurity; + openRemoteShell( + buildProfileBuilder(profile) + .onConfigure(profileSecurity::configure) + .build(), + columns, + rows, + callback ); - ssh = SshClientBuilder.create() - .withHostname(host) - .withPort(port) - .withUsername(username) - .withPassword(password) - .build(); + } catch (InvalidPassphraseException e) { + callback.error("Invalid passphrase for stored key"); + } catch (Exception e) { + if (security != null && security.report(callback)) return; + callback.error("Failed to open SSH shell: " + errMessage(e)); + Log.e(TAG, "Failed to open SSH shell from profile", e); + } + } + } + ); + } - if (ssh.isConnected()) { - connectionID = username + "@" + host; + public void saveProfile(JSONArray args, CallbackContext callback) { + cordova + .getThreadPool() + .execute( + new Runnable() { + public void run() { + try { + String requestedID = args.optString(0, null); + if (requestedID != null && !requestedID.isEmpty()) { + callback.error("Legacy profile import cannot replace a saved profile"); + return; + } + String authType = args.optString(4, "password"); + JSONObject profile = new JSONObject(); + profile.put("hostname", args.getString(1)); + profile.put("port", args.optInt(2, 22)); + profile.put("username", args.getString(3)); + profile.put("authType", authType); + if ("key".equals(authType)) { + profile.put( + "privateKey", + Base64.encodeToString(readUri(args.optString(6)), Base64.NO_WRAP) + ); + profile.put("passphrase", args.optString(7)); + } else { + profile.put("password", args.optString(5)); + } + callback.success(securityStore.saveProfile(requestedID, profile)); + } catch (Exception e) { + callback.error("Could not securely save SFTP profile: " + errMessage(e)); + Log.e(TAG, "Could not save SFTP profile", e); + } + } + } + ); + } - try { - sftp = SftpClientBuilder.create().withClient(ssh).build(); - } catch (IOException | SshException e) { - ssh.close(); - callback.error( - "Failed to initialize SFTP subsystem: " + errMessage(e) - ); - Log.e(TAG, "Failed to initialize SFTP subsystem", e); - return; - } + public void editProfile(JSONArray args, CallbackContext callback) { + cordova + .getThreadPool() + .execute( + new Runnable() { + public void run() { + try { + String requestedID = nullableProfileID(args); + JSONObject existing = requestedID == null + ? null + : securityStore.getProfile(requestedID); + String hostname = args.getString(1).trim(); + int port = args.optInt(2, 22); + String username = args.getString(3).trim(); + String authType = args.optString(4, "password"); + if (hostname.isEmpty()) { + throw new IllegalArgumentException("Hostname is required"); + } + if (username.isEmpty()) { + throw new IllegalArgumentException("Username is required"); + } + if (port < 1 || port > 65535) { + throw new IllegalArgumentException( + "Port must be between 1 and 65535" + ); + } - try { - sftp.getSubsystemChannel().setCharsetEncoding("UTF-8"); - } catch (UnsupportedEncodingException | SshException e) { - // Fallback to default encoding if UTF-8 fails - Log.w( - TAG, - "Failed to set UTF-8 encoding, falling back to default", - e + JSONObject profile = new JSONObject(); + profile.put("hostname", hostname); + profile.put("port", port); + profile.put("username", username); + profile.put("authType", authType); + if ("key".equals(authType)) { + String keyFile = args.optString(6); + if (!keyFile.isEmpty()) { + profile.put( + "privateKey", + Base64.encodeToString(readUri(keyFile), Base64.NO_WRAP) + ); + profile.put("passphrase", args.optString(7)); + } else if ( + existing != null && + "key".equals(existing.optString("authType")) + ) { + profile.put("privateKey", existing.getString("privateKey")); + profile.put("passphrase", existing.optString("passphrase")); + } else { + throw new IllegalArgumentException( + "Select a private key file" ); } - callback.success(); - Log.d(TAG, "Connected successfully to " + connectionID); - return; + } else { + String password = args.optString(5); + if ( + password.isEmpty() && + existing != null && + "password".equals(existing.optString("authType")) + ) { + password = existing.optString("password"); + } + profile.put("password", password); } - callback.error("Failed to establish SSH connection"); - } catch (UnresolvedAddressException e) { - callback.error("Cannot resolve host address"); - Log.e(TAG, "Cannot resolve host address", e); - } catch (PermissionDeniedException e) { - callback.error("Authentication failed: " + e.getMessage()); - Log.e(TAG, "Authentication failed", e); - } catch (SshException e) { - callback.error("SSH error: " + errMessage(e)); - Log.e(TAG, "SSH error", e); - } catch (IOException e) { - callback.error("I/O error: " + errMessage(e)); - Log.e(TAG, "I/O error", e); + String profileID = securityStore.saveProfile( + requestedID, + profile + ); + callback.success(profileInfo(profileID, profile)); } catch (Exception e) { - callback.error("Unexpected error: " + errMessage(e)); - Log.e(TAG, "Unexpected error", e); + callback.error( + "Could not securely save SFTP profile: " + errMessage(e) + ); + Log.e(TAG, "Could not save SFTP profile", e); } } } ); } - public void connectUsingKeyFile(JSONArray args, CallbackContext callback) { + public void getProfileInfo(JSONArray args, CallbackContext callback) { cordova .getThreadPool() .execute( new Runnable() { public void run() { try { - String host = args.optString(0); - int port = args.optInt(1); - String username = args.optString(2); - String keyFile = args.optString(3); - String passphrase = args.optString(4); - DocumentFile file = DocumentFile.fromSingleUri( - context, - Uri.parse(keyFile) + String profileID = args.getString(0); + callback.success( + profileInfo(profileID, securityStore.getProfile(profileID)) ); - Uri uri = file.getUri(); - ContentResolver contentResolver = context.getContentResolver(); - InputStream in = contentResolver.openInputStream(uri); - -// for `appDataDirectory`, Ref: https://developer.android.com/reference/android/content/Context#getExternalFilesDir(java.lang.String) -// the absolute path to application-specific directory. May return *null* if shared storage is not currently available. - File appDataDirectory = context.getExternalFilesDir(null); - if (appDataDirectory != null) { - com.sshtools.common.logger.Log.getDefaultContext().enableFile(com.sshtools.common.logger.Log.Level.DEBUG, new File(appDataDirectory,"synergy.log")); - } -// JCEProvider.enableBouncyCastle(false); + } catch (Exception e) { + callback.error("Could not read SFTP profile: " + errMessage(e)); + } + } + } + ); + } - Log.i(TAG, "All Available Security Providers (Security.getProviders() : " + Arrays.toString(Security.getProviders())); - Log.i(TAG, "All Available Security Providers for ED25519 (Security.getProviders(\"KeyPairGenerator.Ed25519\"\") : " + Arrays.toString(Security.getProviders("KeyPairGenerator.Ed25519"))); - Log.i(TAG, "BC Security Provider Name (`Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)`) : " + Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)); - Security.removeProvider("BC"); - Security.insertProviderAt(new BouncyCastleProvider(), 1); + private static JSONObject profileInfo(String profileID, JSONObject profile) + throws JSONException { + JSONObject info = new JSONObject(); + info.put("profileId", profileID); + info.put("hostname", profile.getString("hostname")); + info.put("port", profile.optInt("port", 22)); + info.put("username", profile.getString("username")); + info.put("authType", profile.optString("authType", "password")); + return info; + } - Log.i(TAG, "(After Inserting BC) All Available Security Providers (Security.getProviders() : " + Arrays.toString(Security.getProviders())); - Log.i(TAG, "(After Inserting BC) All Available Security Providers for ED25519 (Security.getProviders(\"KeyPairGenerator.Ed25519\"\") : " + Arrays.toString(Security.getProviders("KeyPairGenerator.Ed25519"))); - Log.i(TAG, "(After Inserting BC) BC Security Provider Name (`Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)`) : " + Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)); + private static String nullableProfileID(JSONArray args) { + if (args.length() == 0 || args.isNull(0)) return null; + String value = args.optString(0, null); + if (value == null) return null; + value = value.trim(); + if ( + value.isEmpty() || + "null".equalsIgnoreCase(value) || + "undefined".equalsIgnoreCase(value) + ) return null; + return value; + } - SshKeyPair keyPair = null; - try { - keyPair = SshKeyUtils.getPrivateKey(in, passphrase); - } catch (InvalidPassphraseException e) { - callback.error("Invalid passphrase for key file"); - Log.e(TAG, "Invalid passphrase for key file", e); - return; - } catch (IOException e) { - callback.error("Could not read key file: " + errMessage(e)); - Log.e(TAG, "Could not read key file", e); - return; + public void deleteProfile(JSONArray args, CallbackContext callback) { + String profileID = args.optString(0); + try { + JSONObject profile = securityStore.getProfile(profileID); + String label = profile.optString("username") + "@" + profile.optString("hostname"); + activity.runOnUiThread( + () -> { + AlertDialog confirmation = new AlertDialog.Builder(activity) + .setTitle("Delete saved SSH credentials?") + .setMessage( + "Remove the encrypted SFTP/SSH profile for " + label + "?" + ) + .setNegativeButton( + "Cancel", + (ignored, which) -> callback.error("Profile deletion was cancelled") + ) + .setPositiveButton( + "Delete", + (ignored, which) -> { + securityStore.deleteProfile(profileID); + callback.success(); } + ) + .create(); + confirmation.setOnCancelListener( + ignored -> callback.error("Profile deletion was cancelled") + ); + confirmation.show(); + } + ); + } catch (Exception e) { + callback.error("Could not delete SFTP profile: " + errMessage(e)); + } + } - ssh = SshClientBuilder.create() - .withHostname(host) - .withPort(port) - .withUsername(username) - .withIdentities(keyPair) - .build(); + public void writeShell(JSONArray args, CallbackContext callback) { + RemoteShell shell = remoteShells.get(args.optString(0)); + if (shell == null || shell.finished.get()) { + callback.error("SSH shell is not connected"); + return; + } + shell.write(args.optString(1), callback); + } - if (ssh.isConnected()) { - connectionID = username + "@" + host; - try { - sftp = SftpClientBuilder.create().withClient(ssh).build(); - } catch (IOException | SshException e) { - ssh.close(); - callback.error( - "Failed to initialize SFTP subsystem: " + errMessage(e) - ); - Log.e(TAG, "Failed to initialize SFTP subsystem", e); - return; - } + public void resizeShell(JSONArray args, CallbackContext callback) { + String shellID = args.optString(0); + RemoteShell shell = remoteShells.get(shellID); + if (shell == null || shell.finished.get()) { + callback.error("SSH shell is not connected"); + return; + } + shell.channel.changeTerminalDimensions( + Math.max(1, args.optInt(1, 80)), + Math.max(1, args.optInt(2, 24)), + 0, + 0 + ); + callback.success(); + } - try { - sftp.getSubsystemChannel().setCharsetEncoding("UTF-8"); - } catch (UnsupportedEncodingException | SshException e) { - // Fallback to default encoding if UTF-8 fails - Log.w( - TAG, - "Failed to set UTF-8 encoding, falling back to default", - e + public void closeShell(JSONArray args, CallbackContext callback) { + RemoteShell shell = remoteShells.get(args.optString(0)); + if (shell != null) shell.finish(null, null); + callback.success(); + } + + public boolean execute( + String action, + JSONArray args, + CallbackContext callback + ) { + if (!isAllowedAction(action)) { + callback.error("SFTP action is not available: " + action); + return false; + } + try { + Method method = getClass() + .getDeclaredMethod(action, JSONArray.class, CallbackContext.class); + + if (method != null) { + method.invoke(this, args, callback); + return true; + } + } catch (NoSuchMethodException e) { + callback.error("Method not found: " + action); + return false; + } catch (SecurityException e) { + callback.error("Security exception: " + e.getMessage()); + return false; + } catch (Exception e) { + callback.error("Exception: " + e.getMessage()); + return false; + } + + return false; + } + + private static boolean isAllowedAction(String action) { + switch (action) { + case "exec": + case "connectUsingProfile": + case "testProfile": + case "cancelConnection": + case "saveProfile": + case "editProfile": + case "getProfileInfo": + case "deleteProfile": + case "getFile": + case "putFile": + case "lsDir": + case "stat": + case "mkdir": + case "rm": + case "createFile": + case "rename": + case "pwd": + case "close": + case "isConnected": + case "openShellUsingProfile": + case "writeShell": + case "resizeShell": + case "closeShell": + return true; + default: + return false; + } + } + + public void connectUsingProfile(JSONArray args, CallbackContext callback) { + startProfileConnection(args, callback, false); + } + + public void testProfile(JSONArray args, CallbackContext callback) { + startProfileConnection(args, callback, true); + } + + public void cancelConnection(JSONArray args, CallbackContext callback) { + ConnectionAttempt attempt = connectionAttempts.get(args.optString(0)); + if (attempt != null) attempt.cancel(); + callback.success(); + } + + private void startProfileConnection( + JSONArray args, + CallbackContext callback, + boolean returnWorkingDirectory + ) { + String suppliedRequestID = args.optString(1); + String requestID = suppliedRequestID.isEmpty() + ? UUID.randomUUID().toString() + : suppliedRequestID; + long requestedTimeout = args.optLong(2, DEFAULT_CONNECT_TIMEOUT_MS); + long connectTimeout = Math.max( + MIN_CONNECT_TIMEOUT_MS, + Math.min(requestedTimeout, MAX_CONNECT_TIMEOUT_MS) + ); + ConnectionAttempt attempt = new ConnectionAttempt(callback); + if (connectionAttempts.putIfAbsent(requestID, attempt) != null) { + callback.error("An SFTP connection with this request ID is already running"); + return; + } + + FutureTask task = new FutureTask( + () -> { + ConnectionSecurity security = null; + String profileID = args.optString(0); + try { + JSONObject profile = securityStore.getProfile(profileID); + ConnectionSecurity profileSecurity = new ConnectionSecurity( + profile.getString("hostname"), + profile.optInt("port", 22) + ); + security = profileSecurity; + SshClientBuilder builder = buildProfileBuilder( + profile, + connectTimeout + ); + boolean connected; + String workingDirectory = null; + if (returnWorkingDirectory) { + synchronized (connectionLock) { + connected = establishConnection( + builder, + profileID, + profileSecurity, + attempt + ); + if (connected && !attempt.isCancelled()) { + SftpClient activeSftp = sftp; + if (activeSftp == null) { + throw new IOException( + "SFTP connection was closed before validation" ); } - callback.success(); - Log.d(TAG, "Connected successfully to " + connectionID); - return; + workingDirectory = activeSftp.pwd(); } - - callback.error("Failed to establish SSH connection"); - } catch (UnresolvedAddressException e) { - callback.error("Cannot resolve host address"); - Log.e(TAG, "Cannot resolve host address", e); - } catch (PermissionDeniedException e) { - callback.error("Authentication failed: " + e.getMessage()); - Log.e(TAG, "Authentication failed", e); - } catch (SshException e) { - callback.error("SSH error: " + errMessage(e)); - Log.e(TAG, "SSH error", e); - } catch (IOException e) { - callback.error("I/O error: " + errMessage(e)); - Log.e(TAG, "I/O error", e); - } catch (SecurityException e) { - callback.error("Security error: " + errMessage(e)); - Log.e(TAG, "Security error", e); - } catch (Exception e) { - callback.error("Unexpected error: " + errMessage(e)); - Log.e(TAG, "Unexpected error", e); } + } else { + connected = establishConnection( + builder, + profileID, + profileSecurity, + attempt + ); + } + if (connected) { + if (attempt.isCancelled()) return null; + if (returnWorkingDirectory) { + attempt.success(workingDirectory); + } else { + attempt.success(); + } + return null; + } + if (attempt.isCancelled()) return null; + JSONObject securityError = security.takeFailure(); + if (securityError != null) { + attempt.error(securityError); + return null; + } + attempt.error("Failed to establish SSH connection"); + } catch (InvalidPassphraseException e) { + if (!attempt.isCancelled()) { + attempt.error("Invalid passphrase for stored key"); + } + } catch (Exception e) { + if (attempt.isCancelled()) return null; + JSONObject securityError = security == null + ? null + : security.takeFailure(); + if (securityError != null) { + attempt.error(securityError); + return null; + } + attempt.error("Failed to connect SFTP profile: " + errMessage(e)); + Log.e(TAG, "Failed to connect SFTP profile", e); + } catch (OutOfMemoryError e) { + synchronized (connectionLock) { + closeConnectionQuietly(); + } + if (!attempt.isCancelled()) { + attempt.error("Not enough memory to initialize SFTP"); } } - ); + return null; + } + ) { + @Override + protected void done() { + connectionAttempts.remove(requestID, attempt); + } + }; + + attempt.setFuture(task); + cordova.getThreadPool().execute(task); } public void exec(JSONArray args, CallbackContext callback) { @@ -320,7 +1166,7 @@ public void run() { try ( InputStream inputStream = sftp.getInputStream(filename); java.io.OutputStream outputStream = - contentResolver.openOutputStream(fileUri) + contentResolver.openOutputStream(fileUri, "wt") ) { byte[] buffer = new byte[32768]; int bytesRead; @@ -412,11 +1258,22 @@ public void lsDir(JSONArray args, CallbackContext callback) { .execute( new Runnable() { public void run() { + SftpClient activeSftp = null; try { String path = args.optString(0); - if (ssh != null && sftp != null) { + synchronized (connectionLock) { + activeSftp = sftp; + if ( + ssh == null || + !ssh.isConnected() || + activeSftp == null || + activeSftp.isClosed() + ) { + callback.error("Not connected"); + return; + } JSONArray files = new JSONArray(); - for (SftpFile file : sftp.ls(path)) { + for (SftpFile file : activeSftp.ls(path)) { String filename = file.getFilename(); if (filename.equals(".") || filename.equals("..")) { continue; @@ -443,11 +1300,11 @@ public void run() { if (permissions.charAt(0) == 'l') { fileInfo.put("isLink", true); try { - String linkTarget = sftp.getSymbolicLinkTarget( + String linkTarget = activeSftp.getSymbolicLinkTarget( file.getAbsolutePath() ); fileInfo.put("linkTarget", linkTarget); - SftpFileAttributes linkAttributes = sftp.stat( + SftpFileAttributes linkAttributes = activeSftp.stat( linkTarget ); fileInfo.put("isFile", linkAttributes.isFile()); @@ -473,15 +1330,30 @@ public void run() { callback.success(files); return; } - callback.error("Not connected"); - } catch (SftpStatusException | JSONException | SshException e) { + } catch (SftpStatusException | JSONException e) { callback.error(errMessage(e)); + } catch (SshException | RuntimeException e) { + invalidateSftpConnection(activeSftp, e); + callback.error( + "SFTP connection was interrupted. Reconnect and try again." + ); } } } ); } + private void invalidateSftpConnection( + SftpClient failedSftp, + Exception failure + ) { + synchronized (connectionLock) { + if (failedSftp == null || sftp != failedSftp) return; + Log.w(TAG, "Invalidating failed SFTP connection", failure); + closeConnectionQuietly(); + } + } + public void stat(JSONArray args, CallbackContext callback) { cordova .getThreadPool() @@ -728,16 +1600,13 @@ public void close(JSONArray args, CallbackContext callback) { .execute( new Runnable() { public void run() { - try { - if (ssh != null) { - ssh.close(); - sftp.quit(); + synchronized (connectionLock) { + if (ssh != null || sftp != null) { + closeConnectionQuietly(); callback.success(); return; } - callback.error("Not connected"); - } catch (IOException | SshException e) { - callback.error(errMessage(e)); + callback.success(); } } } @@ -750,17 +1619,19 @@ public void isConnected(JSONArray args, CallbackContext callback) { .execute( new Runnable() { public void run() { - if ( - ssh != null && - ssh.isConnected() && - sftp != null && - !sftp.isClosed() - ) { - callback.success(connectionID); - return; - } + synchronized (connectionLock) { + if ( + ssh != null && + ssh.isConnected() && + sftp != null && + !sftp.isClosed() + ) { + callback.success(connectionID); + return; + } - callback.success(0); + callback.success(0); + } } } ); diff --git a/src/plugins/sftp/src/com/foxdebug/sftp/SftpSecurityStore.java b/src/plugins/sftp/src/com/foxdebug/sftp/SftpSecurityStore.java new file mode 100644 index 0000000000..9951566fcc --- /dev/null +++ b/src/plugins/sftp/src/com/foxdebug/sftp/SftpSecurityStore.java @@ -0,0 +1,75 @@ +package com.foxdebug.sftp; + +import android.content.Context; +import com.foxdebug.acode.rk.auth.EncryptedPreferenceManager; +import java.security.GeneralSecurityException; +import java.util.UUID; +import org.json.JSONException; +import org.json.JSONObject; + +final class SftpSecurityStore { + + static final String PROFILE_PREFIX = "profile-"; + private static final String PROFILE_PREFS = "acode_sftp_profiles_v1"; + private static final String HOST_PREFS = "acode_ssh_known_hosts_v1"; + + private final EncryptedPreferenceManager profiles; + private final EncryptedPreferenceManager knownHosts; + + SftpSecurityStore(Context context) { + // SSH credentials and trusted-host records must never fall back to plaintext. + profiles = new EncryptedPreferenceManager(context, PROFILE_PREFS, false); + knownHosts = new EncryptedPreferenceManager(context, HOST_PREFS, false); + } + + static boolean isProfileID(String value) { + return value != null && value.startsWith(PROFILE_PREFIX); + } + + synchronized String saveProfile(String requestedID, JSONObject profile) + throws GeneralSecurityException, JSONException { + String profileID = isProfileID(requestedID) + ? requestedID + : PROFILE_PREFIX + UUID.randomUUID(); + if (!profiles.setStringSync(profileID, profile.toString())) { + throw new GeneralSecurityException("Could not persist SFTP profile"); + } + return profileID; + } + + synchronized JSONObject getProfile(String profileID) + throws GeneralSecurityException, JSONException { + if (!isProfileID(profileID)) throw new GeneralSecurityException( + "Invalid SFTP profile ID" + ); + String storedProfile = profiles.getString(profileID, null); + if (storedProfile == null) throw new GeneralSecurityException( + "SFTP profile was not found" + ); + return new JSONObject(storedProfile); + } + + synchronized void deleteProfile(String profileID) { + if (isProfileID(profileID)) profiles.removeSync(profileID); + } + + synchronized JSONObject getKnownHost(String host) throws JSONException { + String value = knownHosts.getString(host, null); + return value == null ? null : new JSONObject(value); + } + + synchronized void trustHost( + String host, + String algorithm, + String fingerprint, + String publicKey + ) throws JSONException { + JSONObject record = new JSONObject(); + record.put("algorithm", algorithm); + record.put("fingerprint", fingerprint); + record.put("publicKey", publicKey); + if (!knownHosts.setStringSync(host, record.toString())) { + throw new JSONException("Could not persist trusted SSH host"); + } + } +} diff --git a/src/plugins/sftp/www/sftp.js b/src/plugins/sftp/www/sftp.js index cd1859ea68..855cf1cdf6 100644 --- a/src/plugins/sftp/www/sftp.js +++ b/src/plugins/sftp/www/sftp.js @@ -2,22 +2,27 @@ module.exports = { exec: function (command, onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'Sftp', 'exec', [command]); }, - connectUsingPassword: function (host, port, username, password, onSuccess, onFail) { - if (typeof port != 'number') { - throw new Error('Port must be number'); - } - - port = Number.parseInt(port); - cordova.exec(onSuccess, onFail, 'Sftp', 'connectUsingPassword', [host, port, username, password]); - }, - connectUsingKeyFile: function (host, port, username, keyFile, passphrase, onSuccess, onFail) { - if (typeof port != 'number') { - throw new Error('Port must be number'); - } - - port = Number.parseInt(port); - cordova.exec(onSuccess, onFail, 'Sftp', 'connectUsingKeyFile', [host, port, username, keyFile, passphrase]); - }, + connectUsingProfile: function (profileId, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'Sftp', 'connectUsingProfile', [profileId]); + }, + testProfile: function (profileId, requestId, timeout, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'Sftp', 'testProfile', [profileId, requestId, timeout]); + }, + cancelConnection: function (requestId, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'Sftp', 'cancelConnection', [requestId]); + }, + saveProfile: function (profileId, host, port, username, authType, password, keyFile, passphrase, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'Sftp', 'saveProfile', [profileId, host, port, username, authType, password, keyFile, passphrase]); + }, + editProfile: function (profileId, host, port, username, authType, password, keyFile, passphrase, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'Sftp', 'editProfile', [profileId, host, port, username, authType, password, keyFile, passphrase]); + }, + getProfileInfo: function (profileId, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'Sftp', 'getProfileInfo', [profileId]); + }, + deleteProfile: function (profileId, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'Sftp', 'deleteProfile', [profileId]); + }, getFile: function (filename, localFilename, onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'Sftp', 'getFile', [filename, localFilename]); }, @@ -48,7 +53,19 @@ module.exports = { close: function (onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'Sftp', 'close', []); }, - isConnected: function (onSuccess, onFail) { - cordova.exec(onSuccess, onFail, 'Sftp', 'isConnected', []); - } -}; + isConnected: function (onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'Sftp', 'isConnected', []); + }, + openShellUsingProfile: function (profileId, cols, rows, onEvent, onFail) { + cordova.exec(onEvent, onFail, 'Sftp', 'openShellUsingProfile', [profileId, cols, rows]); + }, + writeShell: function (sessionId, data, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'Sftp', 'writeShell', [sessionId, data]); + }, + resizeShell: function (sessionId, cols, rows, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'Sftp', 'resizeShell', [sessionId, cols, rows]); + }, + closeShell: function (sessionId, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'Sftp', 'closeShell', [sessionId]); + } +}; diff --git a/src/plugins/system/android/com/foxdebug/system/RewardPassManager.java b/src/plugins/system/android/com/foxdebug/system/RewardPassManager.java new file mode 100644 index 0000000000..d947cf7ac2 --- /dev/null +++ b/src/plugins/system/android/com/foxdebug/system/RewardPassManager.java @@ -0,0 +1,189 @@ +package com.foxdebug.system; + +import android.content.Context; +import android.util.Log; +import com.foxdebug.acode.rk.auth.EncryptedPreferenceManager; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.Random; +import org.json.JSONException; +import org.json.JSONObject; + +public class RewardPassManager { + private static final String TAG = "SystemRewardPass"; + private static final String ADS_PREFS_FILENAME = "ads"; + private static final String KEY_REWARD_STATE = "reward_state"; + private static final long ONE_HOUR_MS = 60L * 60L * 1000L; + private static final long MAX_ACTIVE_PASS_MS = 10L * ONE_HOUR_MS; + private static final int MAX_REDEMPTIONS_PER_DAY = 3; + + private final EncryptedPreferenceManager adsPrefManager; + private final Random random = new Random(); + + public RewardPassManager(Context context) { + this.adsPrefManager = new EncryptedPreferenceManager(context, ADS_PREFS_FILENAME); + } + + public String getRewardStatus() throws JSONException { + JSONObject state = syncRewardState(loadRewardState()); + JSONObject status = buildRewardStatus(state); + + if (status.optBoolean("hasPendingExpiryNotice")) { + state.put("expiryNoticePendingUntil", 0L); + } + + saveRewardState(state); + return status.toString(); + } + + public String redeemReward(String offerId) throws JSONException { + JSONObject state = syncRewardState(loadRewardState()); + int redemptionsToday = state.optInt("redemptionsToday", 0); + long now = java.lang.System.currentTimeMillis(); + long adFreeUntil = state.optLong("adFreeUntil", 0L); + long remainingMs = Math.max(0L, adFreeUntil - now); + + if (redemptionsToday >= MAX_REDEMPTIONS_PER_DAY) { + throw new JSONException( + "Daily limit reached. You can redeem up to " + MAX_REDEMPTIONS_PER_DAY + " rewards per day." + ); + } + + if (remainingMs >= MAX_ACTIVE_PASS_MS) { + throw new JSONException("You already have the maximum 10 hours of ad-free time active."); + } + + long grantedDurationMs = resolveRewardDuration(offerId); + long baseTime = Math.max(now, adFreeUntil); + long newAdFreeUntil = Math.min(baseTime + grantedDurationMs, now + MAX_ACTIVE_PASS_MS); + long appliedDurationMs = Math.max(0L, newAdFreeUntil - baseTime); + + state.put("adFreeUntil", newAdFreeUntil); + state.put("lastExpiredRewardUntil", 0L); + state.put("expiryNoticePendingUntil", 0L); + state.put("redemptionDay", getTodayKey()); + state.put("redemptionsToday", redemptionsToday + 1); + saveRewardState(state); + + JSONObject status = buildRewardStatus(state); + status.put("grantedDurationMs", grantedDurationMs); + status.put("appliedDurationMs", appliedDurationMs); + status.put("offerId", offerId); + return status.toString(); + } + + private JSONObject loadRewardState() { + String raw = adsPrefManager.getString(KEY_REWARD_STATE, ""); + if (raw == null || raw.isEmpty()) { + return defaultRewardState(); + } + + try { + return mergeRewardState(new JSONObject(raw)); + } catch (JSONException error) { + Log.w(TAG, "Failed to parse reward state, resetting.", error); + return defaultRewardState(); + } + } + + private JSONObject defaultRewardState() { + JSONObject state = new JSONObject(); + try { + state.put("adFreeUntil", 0L); + state.put("lastExpiredRewardUntil", 0L); + state.put("expiryNoticePendingUntil", 0L); + state.put("redemptionDay", getTodayKey()); + state.put("redemptionsToday", 0); + } catch (JSONException ignored) { + } + return state; + } + + private JSONObject mergeRewardState(JSONObject parsed) { + JSONObject state = defaultRewardState(); + try { + state.put("adFreeUntil", parsed.optLong("adFreeUntil", 0L)); + state.put("lastExpiredRewardUntil", parsed.optLong("lastExpiredRewardUntil", 0L)); + state.put("expiryNoticePendingUntil", parsed.optLong("expiryNoticePendingUntil", 0L)); + state.put("redemptionDay", parsed.optString("redemptionDay", getTodayKey())); + state.put("redemptionsToday", parsed.optInt("redemptionsToday", 0)); + } catch (JSONException ignored) { + } + return state; + } + + private void saveRewardState(JSONObject state) { + adsPrefManager.setString(KEY_REWARD_STATE, state.toString()); + } + + private JSONObject syncRewardState(JSONObject state) throws JSONException { + String todayKey = getTodayKey(); + if (!todayKey.equals(state.optString("redemptionDay", todayKey))) { + state.put("redemptionDay", todayKey); + state.put("redemptionsToday", 0); + } + + long adFreeUntil = state.optLong("adFreeUntil", 0L); + long now = java.lang.System.currentTimeMillis(); + if (adFreeUntil > 0L && adFreeUntil <= now) { + if (state.optLong("expiryNoticePendingUntil", 0L) != adFreeUntil) { + state.put("expiryNoticePendingUntil", adFreeUntil); + } + state.put("lastExpiredRewardUntil", adFreeUntil); + state.put("adFreeUntil", 0L); + } + + return state; + } + + private JSONObject buildRewardStatus(JSONObject state) throws JSONException { + long now = java.lang.System.currentTimeMillis(); + long adFreeUntil = state.optLong("adFreeUntil", 0L); + int redemptionsToday = state.optInt("redemptionsToday", 0); + long remainingMs = Math.max(0L, adFreeUntil - now); + int remainingRedemptions = Math.max(0, MAX_REDEMPTIONS_PER_DAY - redemptionsToday); + + JSONObject status = new JSONObject(); + status.put("adFreeUntil", adFreeUntil); + status.put("lastExpiredRewardUntil", state.optLong("lastExpiredRewardUntil", 0L)); + status.put("isActive", adFreeUntil > now); + status.put("remainingMs", remainingMs); + status.put("redemptionsToday", redemptionsToday); + status.put("remainingRedemptions", remainingRedemptions); + status.put("maxRedemptionsPerDay", MAX_REDEMPTIONS_PER_DAY); + status.put("maxActivePassMs", MAX_ACTIVE_PASS_MS); + status.put("hasPendingExpiryNotice", state.optLong("expiryNoticePendingUntil", 0L) > 0L); + status.put("expiryNoticePendingUntil", state.optLong("expiryNoticePendingUntil", 0L)); + + boolean canRedeem = remainingRedemptions > 0 && remainingMs < MAX_ACTIVE_PASS_MS; + status.put("canRedeem", canRedeem); + status.put("redeemDisabledReason", getRedeemDisabledReason(remainingRedemptions, remainingMs)); + return status; + } + + private String getRedeemDisabledReason(int remainingRedemptions, long remainingMs) { + if (remainingRedemptions <= 0) { + return "Daily limit reached. You can redeem up to " + MAX_REDEMPTIONS_PER_DAY + " rewards per day."; + } + if (remainingMs >= MAX_ACTIVE_PASS_MS) { + return "You already have the maximum 10 hours of ad-free time active."; + } + return ""; + } + + private long resolveRewardDuration(String offerId) throws JSONException { + if ("quick".equals(offerId)) { + return ONE_HOUR_MS; + } + if ("focus".equals(offerId)) { + int selectedHours = 4 + random.nextInt(3); + return selectedHours * ONE_HOUR_MS; + } + throw new JSONException("Unknown reward offer."); + } + + private String getTodayKey() { + return new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(new Date()); + } +} diff --git a/src/plugins/system/android/com/foxdebug/system/StreamHttp.java b/src/plugins/system/android/com/foxdebug/system/StreamHttp.java new file mode 100644 index 0000000000..d59bb2f52d --- /dev/null +++ b/src/plugins/system/android/com/foxdebug/system/StreamHttp.java @@ -0,0 +1,400 @@ +package com.foxdebug.system; + +import android.util.Base64; +import android.util.Log; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.PluginResult; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Incrementally streams an HTTP response body to JavaScript. + * + *

The request runs on a dedicated background thread (never the UI thread). + * Response bytes are forwarded to the bridge as they arrive. To survive the + * JSON bridge without a base64 round trip, chunks are sent as raw bytes mapped + * onto ISO-8859-1 characters (byte n == code point n), which the JSON bridge + * round-trips losslessly; only chunks containing control bytes (< 0x20, + * which JSON must escape) fall back to base64. The native layer performs no + * SSE/LLM specific parsing: chunk boundaries are arbitrary and may split + * multi-byte UTF-8 characters or SSE frames. + * + *

Events emitted to JS (JSON object with a {@code type} field): + *

    + *
  • {@code headers} - status, statusText, url and response headers
  • + *
  • {@code data} - a byte chunk (raw ISO-8859-1 string, or base64 when the + * {@code b64} flag is set)
  • + *
  • {@code complete} - response body finished (terminal)
  • + *
  • {@code error} - transport failure (terminal)
  • + *
+ * + *

Exactly one terminal event ({@code complete} or {@code error}) is ever + * emitted per stream. 4xx/5xx HTTP statuses are still delivered as a normal + * {@code headers} + body stream and remain distinguishable from network + * failures. + */ +public class StreamHttp implements Runnable { + + private static final String TAG = "SystemStreamHttp"; + private static final int DEFAULT_CHUNK_SIZE = 32 * 1024; + private static final int MAX_CHUNK_SIZE = 100 * 1024; + + private static final int MAX_CONCURRENT_STREAMS = 50; + + private static final int CREDIT_WINDOW_BYTES = 256 * 1024; + + private static final ConcurrentHashMap STREAMS = new ConcurrentHashMap<>(); + + private final String requestId; + private final String url; + private final String method; + private final JSONObject headers; + private final String body; + private final boolean bodyIsBase64; + private final boolean followRedirects; + private final int connectTimeout; + private final int readTimeout; + private final int chunkSize; + private final CallbackContext callback; + + private final Object creditLock = new Object(); + private volatile boolean cancelled; + private volatile boolean finished; + private long pendingBytes; + + private HttpURLConnection connection; + private InputStream inputStream; + + public StreamHttp( + String requestId, + String url, + String method, + JSONObject headers, + String body, + boolean bodyIsBase64, + boolean followRedirects, + int connectTimeout, + int readTimeout, + int chunkSize, + CallbackContext callback + ) { + this.requestId = requestId; + this.url = url; + this.method = method; + this.headers = headers; + this.body = body; + this.bodyIsBase64 = bodyIsBase64; + this.followRedirects = followRedirects; + this.connectTimeout = connectTimeout; + this.readTimeout = readTimeout; + this.chunkSize = chunkSize > 0 + ? Math.min(chunkSize, MAX_CHUNK_SIZE) + : DEFAULT_CHUNK_SIZE; + this.callback = callback; + } + + public static void start( + String requestId, + String url, + String method, + JSONObject headers, + String body, + boolean bodyIsBase64, + boolean followRedirects, + int connectTimeout, + int readTimeout, + int chunkSize, + CallbackContext callback + ) { + StreamHttp stream = new StreamHttp( + requestId, + url, + method, + headers, + body, + bodyIsBase64, + followRedirects, + connectTimeout, + readTimeout, + chunkSize, + callback + ); + if (STREAMS.size() >= MAX_CONCURRENT_STREAMS) { + callback.error( + "Too many concurrent HTTP streams (" + + MAX_CONCURRENT_STREAMS + + "). Cancel an active stream or retry later." + ); + return; + } + STREAMS.put(requestId, stream); + Thread thread = new Thread(stream, "SystemStreamHttp-" + requestId); + thread.setDaemon(true); + thread.start(); + } + + /** Acknowledges that JavaScript has consumed {@code bytes} response bytes. */ + public static void ack(String requestId, int bytes) { + StreamHttp stream = STREAMS.get(requestId); + if (stream != null) stream.ack(bytes); + } + + /** Cancels the request and disconnects the underlying connection. */ + public static void cancel(String requestId) { + StreamHttp stream = STREAMS.get(requestId); + if (stream != null) stream.cancel(); + } + + /** Cancels every active stream. Used during plugin/app teardown. */ + public static void cancelAll() { + for (StreamHttp stream : STREAMS.values()) { + stream.cancel(); + } + } + + private void ack(int bytes) { + if (bytes <= 0) return; + synchronized (creditLock) { + pendingBytes = Math.max(0, pendingBytes - bytes); + creditLock.notifyAll(); + } + } + + private void cancel() { + cancelled = true; + synchronized (creditLock) { + creditLock.notifyAll(); + } + if (connection != null) { + try { + connection.disconnect(); + } catch (Exception e) { + Log.w(TAG, "Failed to disconnect stream " + requestId, e); + } + } + release(); + } + + private void release() { + if (finished) return; + finished = true; + try { + PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); + result.setKeepCallback(false); + callback.sendPluginResult(result); + } catch (Exception e) { + Log.w(TAG, "Failed to release stream callback " + requestId, e); + } + } + + @Override + public void run() { + try { + if (cancelled) return; + URL url = new URL(this.url); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod(method); + connection.setInstanceFollowRedirects(followRedirects); + connection.setConnectTimeout(connectTimeout); + connection.setReadTimeout(readTimeout); + connection.setUseCaches(false); + + if (headers != null) { + Iterator keys = headers.keys(); + while (keys.hasNext()) { + String key = keys.next(); + String value = headers.optString(key); + if (key != null && value != null) { + connection.setRequestProperty(key, value); + } + } + } + + if (body != null) { + byte[] bytes = bodyIsBase64 + ? Base64.decode(body, Base64.NO_WRAP) + : body.getBytes(StandardCharsets.UTF_8); + connection.setFixedLengthStreamingMode(bytes.length); + connection.setDoOutput(true); + OutputStream out = connection.getOutputStream(); + out.write(bytes); + out.flush(); + } + + if (cancelled) return; + + int status = connection.getResponseCode(); + if (cancelled) return; + + String statusText = connection.getResponseMessage(); + String finalUrl = connection.getURL().toString(); + sendHeaders(status, statusText, finalUrl, connection.getHeaderFields()); + + InputStream stream = status >= 400 + ? connection.getErrorStream() + : connection.getInputStream(); + inputStream = stream; + + if (stream != null) { + byte[] buffer = new byte[chunkSize]; + int read; + while (!cancelled && (read = stream.read(buffer)) != -1) { + if (read <= 0) continue; + waitForCredit(read); + if (cancelled) break; + byte[] chunk = read == buffer.length + ? buffer + : java.util.Arrays.copyOf(buffer, read); + if (read == buffer.length) { + buffer = new byte[chunkSize]; + } + // Reserve credit before publishing: ack() can only race against + // chunks JavaScript has already received, so incrementing here keeps + // the subtraction in ack() from ever clamping a not-yet-accounted + // reservation to zero and silently exhausting the credit window. + synchronized (creditLock) { + pendingBytes += read; + } + sendData(chunk); + } + } + + if (!cancelled) { + sendComplete(); + } + } catch (Exception e) { + Log.w(TAG, "Stream " + requestId + " failed", e); + if (!cancelled && !finished) { + try { + sendError(e.getMessage() != null ? e.getMessage() : e.toString()); + } catch (JSONException jsonError) { + Log.w(TAG, "Failed to send stream error event", jsonError); + } + } + } finally { + cleanup(); + } + } + + private void waitForCredit(long bytes) { + synchronized (creditLock) { + while (!cancelled && pendingBytes + bytes > CREDIT_WINDOW_BYTES) { + try { + creditLock.wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + if (cancelled) return; + } + } + } + } + + private void sendHeaders( + int status, + String statusText, + String finalUrl, + Map> headerFields + ) throws JSONException { + JSONObject event = new JSONObject(); + event.put("type", "headers"); + event.put("status", status); + event.put("statusText", statusText != null ? statusText : ""); + event.put("url", finalUrl != null ? finalUrl : ""); + + // Delivered as ordered [name, value] pairs so repeated headers (e.g. + // Set-Cookie, which cannot be comma joined) survive the JSON bridge. + JSONArray headerPairs = new JSONArray(); + if (headerFields != null) { + for (Map.Entry> entry : headerFields.entrySet()) { + String name = entry.getKey(); + List values = entry.getValue(); + if (name == null || values == null || values.isEmpty()) { + continue; + } + String lower = name.toLowerCase(); + for (String value : values) { + if (value == null) continue; + JSONArray pair = new JSONArray(); + pair.put(lower); + pair.put(value); + headerPairs.put(pair); + } + } + } + event.put("headers", headerPairs); + sendEvent(event, true); + } + + private void sendData(byte[] chunk) throws JSONException { + JSONObject event = new JSONObject(); + event.put("type", "data"); + if (jsonSafe(chunk)) { + // Byte n as code point n survives the JSON bridge unescaped, avoiding + // the ~33% base64 inflation and the base64 decode on the JS side. + event.put("chunk", new String(chunk, StandardCharsets.ISO_8859_1)); + } else { + event.put("b64", true); + event.put("chunk", Base64.encodeToString(chunk, Base64.NO_WRAP)); + } + sendEvent(event, true); + } + + // True when the chunk has no byte below 0x20, i.e. nothing the JSON encoder + // is forced to escape (as a U+XXXX sequence) into a larger payload. + private static boolean jsonSafe(byte[] chunk) { + for (byte b : chunk) { + if ((b & 0xFF) < 0x20) return false; + } + return true; + } + + private void sendComplete() throws JSONException { + JSONObject event = new JSONObject(); + event.put("type", "complete"); + sendEvent(event, false); + } + + private void sendError(String message) throws JSONException { + JSONObject event = new JSONObject(); + event.put("type", "error"); + event.put("message", message); + sendEvent(event, false); + } + + private void sendEvent(JSONObject event, boolean keepCallback) { + if (finished) return; + if (!keepCallback) finished = true; + PluginResult result = new PluginResult(PluginResult.Status.OK, event); + result.setKeepCallback(keepCallback); + callback.sendPluginResult(result); + } + + private void cleanup() { + STREAMS.remove(requestId); + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException ignored) { + } + } + if (connection != null) { + try { + connection.disconnect(); + } catch (Exception ignored) { + } + } + } +} diff --git a/src/plugins/system/android/com/foxdebug/system/System.java b/src/plugins/system/android/com/foxdebug/system/System.java index 861032524b..146755da62 100644 --- a/src/plugins/system/android/com/foxdebug/system/System.java +++ b/src/plugins/system/android/com/foxdebug/system/System.java @@ -2,39 +2,52 @@ import static android.os.Build.VERSION.SDK_INT; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.io.IOException; +import android.Manifest; import android.app.Activity; import android.app.PendingIntent; -import android.content.ClipData; -import android.content.Context; -import android.content.Intent; -import android.content.res.Configuration; import android.content.*; import android.content.pm.*; -import java.util.*; +import android.content.res.Configuration; import android.graphics.Bitmap; +import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ImageDecoder; +import android.graphics.Paint; +import android.graphics.RectF; +import android.graphics.Typeface; import android.net.Uri; import android.os.Build; import android.os.Bundle; +import android.os.Environment; import android.os.PowerManager; +import android.provider.DocumentsContract; +import android.provider.MediaStore; +import android.provider.Settings; import android.provider.Settings.Global; import android.util.Base64; +import android.util.Log; +import android.util.TypedValue; import android.view.View; import android.view.Window; import android.view.WindowInsetsController; import android.view.inputmethod.InputMethodManager; +import android.webkit.MimeTypeMap; import android.webkit.WebView; +import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import androidx.core.content.pm.ShortcutInfoCompat; import androidx.core.content.pm.ShortcutManagerCompat; import androidx.core.graphics.drawable.IconCompat; +import androidx.documentfile.provider.DocumentFile; import com.foxdebug.system.Ui.Theme; +import java.io.BufferedReader; import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; @@ -42,1249 +55,2383 @@ import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; +import java.util.*; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; +import org.apache.cordova.CordovaWebViewImpl; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import java.nio.file.Files; -import java.nio.file.LinkOption; -import java.nio.file.Path; -import android.content.Context; -import android.net.Uri; -import android.util.Log; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.IOException; -import android.webkit.MimeTypeMap; +public class System extends CordovaPlugin { -// DocumentFile import (AndroidX library) -import androidx.documentfile.provider.DocumentFile; + private static final String TAG = "SystemPlugin"; + + private CallbackContext requestPermissionCallback; + private static final Map APP_ICON_ALIASES; + + static { + Map aliases = new HashMap<>(); + aliases.put("default", "MainActivityIconDefault"); + aliases.put("pro", "MainActivityIconPro"); + aliases.put("midnight_circuit", "MainActivityIconMidnightCircuit"); + aliases.put("aurora_pulse", "MainActivityIconAuroraPulse"); + aliases.put("terminal_glow", "MainActivityIconTerminalGlow"); + aliases.put("solar_flare", "MainActivityIconSolarFlare"); + aliases.put("blueprint", "MainActivityIconBlueprint"); + aliases.put("pixel_party", "MainActivityIconPixelParty"); + aliases.put("prism", "MainActivityIconPrism"); + aliases.put("porcelain", "MainActivityIconPorcelain"); + aliases.put("tangerine", "MainActivityIconTangerine"); + aliases.put("tidal", "MainActivityIconTidal"); + aliases.put("lilac", "MainActivityIconLilac"); + aliases.put("volt", "MainActivityIconVolt"); + aliases.put("cobalt", "MainActivityIconCobalt"); + aliases.put("glacier", "MainActivityIconGlacier"); + APP_ICON_ALIASES = Collections.unmodifiableMap(aliases); + } + + private Activity activity; + private Context context; + private int REQ_PERMISSIONS = 1; + private int REQ_PERMISSION = 2; + private int systemBarColor = 0xFF000000; + private Theme theme; + private CallbackContext intentHandler; + private CordovaWebView webView; + private String fileProviderAuthority; + private RewardPassManager rewardPassManager; + + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); + this.context = cordova.getContext(); + this.activity = cordova.getActivity(); + this.webView = webView; + this.rewardPassManager = new RewardPassManager(this.context); + this.activity.runOnUiThread( + new Runnable() { + @Override + public void run() { + setNativeContextMenuDisabled(false); + } + } + ); + } + + @Override + public void onReset() { + super.onReset(); + StreamHttp.cancelAll(); + intentHandler = null; + } + + @Override + public void onDestroy() { + StreamHttp.cancelAll(); + super.onDestroy(); + } + + public boolean execute( + String action, + final JSONArray args, + final CallbackContext callbackContext + ) throws JSONException { + final String arg1 = args.optString(0); + final String arg2 = args.optString(1); + final String arg3 = args.optString(2); + final String arg4 = args.optString(3); + final String arg5 = args.optString(4); + final String arg6 = args.optString(5); + + switch (action) { + case "get-webkit-info": + case "file-action": + case "checksumText": + case "is-powersave-mode": + case "get-app-info": + case "add-shortcut": + case "remove-shortcut": + case "pin-shortcut": + case "get-android-version": + case "request-permissions": + case "request-permission": + case "has-permission": + case "open-in-browser": + case "launch-app": + case "get-global-setting": + case "get-available-encodings": + case "decode": + case "encode": + case "copyToUri": + case "getInstaller": + case "compare-file-text": + case "compare-texts": + case "extractAsset": + case "pin-file-shortcut": + break; + case "get-configuration": + getConfiguration(callbackContext); + return true; + case "set-fullscreen-back-handler": + final boolean fullscreenBackHandler = args.getBoolean(0); + activity.runOnUiThread(() -> { + try { + ((CordovaWebViewImpl) webView).setFullscreenBackHandler(fullscreenBackHandler); + callbackContext.success(); + } catch (RuntimeException error) { + callbackContext.error(error.getMessage()); + } + }); + return true; + case "set-fullscreen-orientation": + final String orientation = args.isNull(0) ? null : args.getString(0); + activity.runOnUiThread(() -> { + try { + ((CordovaWebViewImpl) webView).setFullscreenOrientation(orientation); + callbackContext.success(); + } catch (RuntimeException error) { + callbackContext.error(error.getMessage()); + } + }); + return true; + case "http-stream-start": + httpStreamStart(args, callbackContext); + return true; + case "http-stream-ack": + StreamHttp.ack(arg1, args.optInt(1, 0)); + callbackContext.success(); + return true; + case "http-stream-cancel": + StreamHttp.cancel(arg1); + callbackContext.success(); + return true; + case "set-input-type": + setInputType(arg1); + callbackContext.success(); + return true; + case "set-native-context-menu-disabled": + this.cordova.getActivity().runOnUiThread( + new Runnable() { + @Override + public void run() { + setNativeContextMenuDisabled(Boolean.parseBoolean(arg1)); + callbackContext.success(); + } + } + ); + return true; + case "set-app-icon": + setAppIcon(arg1, callbackContext); + return true; + case "get-cordova-intent": + getCordovaIntent(callbackContext); + return true; + case "set-intent-handler": + setIntentHandler(callbackContext); + return true; + case "shareText": + String text = args.getString(0); + + cordova.getActivity().runOnUiThread(() -> { + try { + Intent shareIntent = new Intent(Intent.ACTION_SEND); + shareIntent.setType("text/plain"); + shareIntent.putExtra(Intent.EXTRA_TEXT, text); + + cordova + .getActivity() + .startActivity(Intent.createChooser(shareIntent, "Share")); + + callbackContext.success(); + } catch (Exception e) { + callbackContext.error(e.getMessage()); + } + }); + return true; + case "set-ui-theme": + this.cordova.getActivity().runOnUiThread( + new Runnable() { + public void run() { + setUiTheme(arg1, args.optJSONObject(1), callbackContext); + } + } + ); + return true; + case "clear-cache": + this.cordova.getActivity().runOnUiThread( + new Runnable() { + public void run() { + clearCache(callbackContext); + } + } + ); + return true; + case "fileExists": + callbackContext.success( + fileExists(args.getString(0), args.getString(1)) ? 1 : 0 + ); + return true; + case "createSymlink": + boolean success = createSymlink(args.getString(0), args.getString(1)); + callbackContext.success(success ? 1 : 0); + return true; + case "getNativeLibraryPath": + callbackContext.success(getNativeLibraryPath()); + return true; + case "getFilesDir": + callbackContext.success(getFilesDir()); + return true; + case "getRewardStatus": + callbackContext.success(rewardPassManager.getRewardStatus()); + return true; + case "redeemReward": + callbackContext.success( + rewardPassManager.redeemReward(args.getString(0)) + ); + return true; + case "getParentPath": + callbackContext.success(getParentPath(args.getString(0))); + return true; + case "listChildren": + callbackContext.success(listChildren(args.getString(0))); + return true; + case "writeText": { + try { + String filePath = args.getString(0); + String content = args.getString(1); -// Java I/O imports -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.IOException; + Files.write( + Paths.get(filePath), + Collections.singleton(content), + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING + ); -import android.os.Build; -import android.os.Environment; -import android.Manifest; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.net.Uri; -import android.provider.Settings; + callbackContext.success("File written successfully"); + } catch (Exception e) { + callbackContext.error("Failed to write file: " + e.getMessage()); + } + return true; + } + case "getArch": + String arch; + + if (android.os.Build.VERSION.SDK_INT >= 21) { + arch = android.os.Build.SUPPORTED_ABIS[0]; + } else { + arch = android.os.Build.CPU_ABI; + } -import androidx.core.content.ContextCompat; + callbackContext.success(arch); + return true; + case "requestStorageManager": + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + try { + Intent intent = new Intent( + Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION + ); + intent.setData(Uri.parse("package:" + context.getPackageName())); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + callbackContext.success("true"); + } catch (Exception e) { + // Fallback to general settings if specific one fails + Intent intent = new Intent( + Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION + ); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + callbackContext.success("true"); + } + } else { + callbackContext.success("false"); // Not needed on Android < 11 + } + return true; + case "hasGrantedStorageManager": + boolean granted; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + granted = Environment.isExternalStorageManager(); + } else { + // Fallback for Android 10 and below + granted = + ContextCompat.checkSelfPermission( + context, + Manifest.permission.READ_EXTERNAL_STORAGE + ) == PackageManager.PERMISSION_GRANTED; + } + callbackContext.success(String.valueOf(granted)); + return true; + case "isManageExternalStorageDeclared": + PackageManager pm = context.getPackageManager(); + try { + PackageInfo info = pm.getPackageInfo( + context.getPackageName(), + PackageManager.GET_PERMISSIONS + ); + String[] permissions = info.requestedPermissions; + String isDeclared = "false"; + + if (permissions != null) { + for (String perm : permissions) { + if (perm.equals("android.permission.MANAGE_EXTERNAL_STORAGE")) { + isDeclared = "true"; + break; + } + } + } + callbackContext.success(isDeclared); + } catch (PackageManager.NameNotFoundException e) { + e.printStackTrace(); + callbackContext.error(e.toString()); + } + return true; + case "mkdirs": + if (new File(args.getString(0)).mkdirs()) { + callbackContext.success(); + } else { + callbackContext.error("mkdirs failed"); + } + return true; + case "deleteFile": + if (new File(args.getString(0)).delete()) { + callbackContext.success(); + } else { + callbackContext.error("delete failed"); + } + return true; + case "setExec": + if ( + new File(args.getString(0)).setExecutable( + Boolean.parseBoolean(args.getString(1)) + ) + ) { + callbackContext.success(); + } else { + callbackContext.error("set exec failed"); + } + return true; + default: + return false; + } -public class System extends CordovaPlugin { + cordova.getThreadPool().execute( + new Runnable() { + public void run() { + switch (action) { + case "extractAsset": + try { + String assetName = args.getString(0); + String destinationPath = args.getString(1); + extractAsset(assetName, destinationPath, callbackContext); + } catch (Exception e) { + callbackContext.error( + "Failed to extract asset: " + e.getMessage() + ); + } + return; + case "getInstaller": + try { + PackageManager pm = context.getPackageManager(); - private CallbackContext requestPermissionCallback; - private Activity activity; - private Context context; - private int REQ_PERMISSIONS = 1; - private int REQ_PERMISSION = 2; - private int systemBarColor = 0xFF000000; - private Theme theme; - private CallbackContext intentHandler; - private CordovaWebView webView; - - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - this.context = cordova.getContext(); - this.activity = cordova.getActivity(); - this.webView = webView; - - // Set up global exception handler - Thread.setDefaultUncaughtExceptionHandler( - new Thread.UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread thread, Throwable ex) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - ex.printStackTrace(pw); - String stackTrace = sw.toString(); - - String errorMsg = String.format( - "Uncaught Exception: %s\nStack trace: %s", - ex.getMessage(), - stackTrace - ); + String installer; - sendLogToJavaScript("error", errorMsg); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + InstallSourceInfo info = pm.getInstallSourceInfo( + context.getPackageName() + ); - // rethrow to the default handler - Thread.getDefaultUncaughtExceptionHandler() - .uncaughtException(thread, ex); + installer = info.getInstallingPackageName(); + } else { + installer = pm.getInstallerPackageName( + context.getPackageName() + ); } - } - ); - } - public boolean execute( - String action, - final JSONArray args, - final CallbackContext callbackContext - ) throws JSONException { - final String arg1 = args.optString(0); - final String arg2 = args.optString(1); - final String arg3 = args.optString(2); - final String arg4 = args.optString(3); - final String arg5 = args.optString(4); - final String arg6 = args.optString(5); + callbackContext.success(installer); + } catch (Exception e) { + callbackContext.error(e.getMessage()); + } + break; + case "copyToUri": + try { + //srcUri is a file + Uri srcUri = Uri.parse(args.getString(0)); + + //destUri is a directory + Uri destUri = Uri.parse(args.getString(1)); + + //create a file named this into the dest Directory and copy the srcUri into it + String fileName = args.getString(2); - switch (action) { + InputStream in = null; + OutputStream out = null; + try { + // Open input stream from the source URI + if ("file".equalsIgnoreCase(srcUri.getScheme())) { + File file = new File(srcUri.getPath()); + in = new FileInputStream(file); + } else { + in = context.getContentResolver().openInputStream(srcUri); + } + + // Create the destination file using DocumentFile for better URI handling + DocumentFile destFile = null; + + if ("file".equalsIgnoreCase(destUri.getScheme())) { + // Handle file:// scheme using DocumentFile + File destDir = new File(destUri.getPath()); + if (!destDir.exists()) { + destDir.mkdirs(); // Create directory if it doesn't exist + } + DocumentFile destDocDir = DocumentFile.fromFile(destDir); + + // Check if file already exists and delete it + DocumentFile existingFile = destDocDir.findFile(fileName); + if (existingFile != null && existingFile.exists()) { + existingFile.delete(); + } + + // Create new file + String mimeType = getMimeTypeFromExtension(fileName); + destFile = destDocDir.createFile(mimeType, fileName); + } else { + // Handle content:// scheme using DocumentFile + DocumentFile destDocDir = DocumentFile.fromTreeUri( + context, + destUri + ); + + if ( + destDocDir == null || + !destDocDir.exists() || + !destDocDir.isDirectory() + ) { + callbackContext.error( + "Destination directory does not exist or is not accessible" + ); + return; + } + + // Check if file already exists and delete it + DocumentFile existingFile = destDocDir.findFile(fileName); + if (existingFile != null && existingFile.exists()) { + existingFile.delete(); + } + + // Create new file + String mimeType = getMimeTypeFromExtension(fileName); + destFile = destDocDir.createFile(mimeType, fileName); + } + + if (destFile == null || !destFile.exists()) { + callbackContext.error("Failed to create destination file"); + return; + } + + // Open output stream to the created file + out = context + .getContentResolver() + .openOutputStream(destFile.getUri()); + + if (in == null || out == null) { + callbackContext.error("uri streams are null"); + return; + } + + // Copy stream + byte[] buffer = new byte[8192]; + int len; + while ((len = in.read(buffer)) > 0) { + out.write(buffer, 0, len); + } + + out.flush(); + callbackContext.success(); + } catch (IOException e) { + e.printStackTrace(); + callbackContext.error(e.toString()); + } finally { + try { + if (in != null) in.close(); + if (out != null) out.close(); + } catch (IOException e) { + e.printStackTrace(); + callbackContext.error(e.toString()); + } + } + } catch (Exception e) { + e.printStackTrace(); + callbackContext.error(e.toString()); + } + break; case "get-webkit-info": + getWebkitInfo(callbackContext); + break; case "file-action": + fileAction(arg1, arg2, arg3, arg4, callbackContext); + break; case "is-powersave-mode": + isPowerSaveMode(callbackContext); + break; case "get-app-info": + getAppInfo(callbackContext); + break; + case "pin-file-shortcut": + pinFileShortcut(args.optJSONObject(0), callbackContext); + break; case "add-shortcut": + addShortcut(arg1, arg2, arg3, arg4, arg5, arg6, callbackContext); + break; case "remove-shortcut": + removeShortcut(arg1, callbackContext); + break; case "pin-shortcut": + pinShortcut(arg1, callbackContext); + break; case "get-android-version": + getAndroidVersion(callbackContext); + break; case "request-permissions": + requestPermissions(args.optJSONArray(0), callbackContext); + break; case "request-permission": + requestPermission(arg1, callbackContext); + break; case "has-permission": + hasPermission(arg1, callbackContext); + break; case "open-in-browser": + openInBrowser(arg1, callbackContext); + break; case "launch-app": + launchApp(arg1, arg2, args.optJSONObject(2), callbackContext); + break; case "get-global-setting": + getGlobalSetting(arg1, callbackContext); + break; case "get-available-encodings": + getAvailableEncodings(callbackContext); + break; case "decode": + decode(arg1, arg2, callbackContext); + break; case "encode": - case "copyToUri": - break; - case "get-configuration": - getConfiguration(callbackContext); - return true; - case "set-input-type": - setInputType(arg1); - callbackContext.success(); - return true; - case "get-cordova-intent": - getCordovaIntent(callbackContext); - return true; - case "set-intent-handler": - setIntentHandler(callbackContext); - return true; - case "set-ui-theme": - this.cordova.getActivity() - .runOnUiThread( - new Runnable() { - public void run() { - setUiTheme(arg1, args.optJSONObject(1), callbackContext); - } - } - ); - return true; - case "clear-cache": - this.cordova.getActivity() - .runOnUiThread( - new Runnable() { - public void run() { - clearCache(callbackContext); - } - } - ); - return true; - case "fileExists": - callbackContext.success(fileExists(args.getString(0), args.getString(1)) ? 1 : 0); - return true; - - case "createSymlink": - boolean success = createSymlink(args.getString(0), args.getString(1)); - callbackContext.success(success ? 1 : 0); - return true; - - case "getNativeLibraryPath": - callbackContext.success(getNativeLibraryPath()); - return true; - - case "getFilesDir": - callbackContext.success(getFilesDir()); - return true; - - case "getParentPath": - callbackContext.success(getParentPath(args.getString(0))); - return true; - - case "listChildren": - callbackContext.success(listChildren(args.getString(0))); - return true; - case "writeText": - { - try { - String filePath = args.getString(0); - String content = args.getString(1); - - Files.write(Paths.get(filePath), - Collections.singleton(content), - StandardOpenOption.CREATE, - StandardOpenOption.TRUNCATE_EXISTING); - - callbackContext.success("File written successfully"); - } catch (Exception e) { - callbackContext.error("Failed to write file: " + e.getMessage()); - } - return true; - } - - case "getArch": - String arch; - - if (android.os.Build.VERSION.SDK_INT >= 21) { - arch = android.os.Build.SUPPORTED_ABIS[0]; - } else { - arch = android.os.Build.CPU_ABI; - } + encode(arg1, arg2, callbackContext); + break; + case "compare-file-text": + compareFileText(arg1, arg2, arg3, callbackContext); + break; + case "compare-texts": + compareTexts(arg1, arg2, callbackContext); + break; + case "checksumText": + cordova.getThreadPool().execute(() -> { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); - callbackContext.success(arch); - return true; + byte[] hash = digest.digest( + args.getString(0).getBytes("UTF-8") + ); - case "requestStorageManager": - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - try { - Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION); - intent.setData(Uri.parse("package:" + context.getPackageName())); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); - callbackContext.success("true"); - } catch (Exception e) { - // Fallback to general settings if specific one fails - Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); - callbackContext.success("true"); - } - } else { - callbackContext.success("false"); // Not needed on Android < 11 - } - return true; + StringBuilder hexString = new StringBuilder(); + for (byte b : hash) { + String hex = Integer.toHexString(0xff & b); - case "hasGrantedStorageManager": - boolean granted; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - granted = Environment.isExternalStorageManager(); - } else { - // Fallback for Android 10 and below - granted = ContextCompat.checkSelfPermission( - context, - Manifest.permission.READ_EXTERNAL_STORAGE - ) == PackageManager.PERMISSION_GRANTED; - } - callbackContext.success(String.valueOf(granted)); - return true; + if (hex.length() == 1) hexString.append('0'); - case "isManageExternalStorageDeclared": - PackageManager pm = context.getPackageManager(); - try { - PackageInfo info = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS); - String[] permissions = info.requestedPermissions; - String isDeclared = "false"; - - if (permissions != null) { - for (String perm: permissions) { - if (perm.equals("android.permission.MANAGE_EXTERNAL_STORAGE")) { - isDeclared = "true"; - break; - } - } - } - callbackContext.success(isDeclared); + hexString.append(hex); + } - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - callbackContext.error(e.toString()); + callbackContext.success(hexString.toString()); + } catch (Exception e) { + callbackContext.error(e.getMessage()); } + }); - return true; - case "mkdirs": - File file = new File(args.getString(0)); - if (file.mkdirs()) { - callbackContext.success(); - } else { - callbackContext.error("mkdirs failed"); - } - return true; + break; default: - return false; + break; + } } - - cordova - .getThreadPool() - .execute( - new Runnable() { - public void run() { - switch (action) { - case "copyToUri": - try { - //srcUri is a file - Uri srcUri = Uri.parse(args.getString(0)); - - //destUri is a directory - Uri destUri = Uri.parse(args.getString(1)); - - //create a file named this into the dest Directory and copy the srcUri into it - String fileName = args.getString(2); - - InputStream in = null; - OutputStream out = null; - try { - // Open input stream from the source URI - if ("file".equalsIgnoreCase(srcUri.getScheme())) { - File file = new File(srcUri.getPath()); in = new FileInputStream(file); - } else { in = context.getContentResolver().openInputStream(srcUri); - } - - // Create the destination file using DocumentFile for better URI handling - DocumentFile destFile = null; - - if ("file".equalsIgnoreCase(destUri.getScheme())) { - // Handle file:// scheme using DocumentFile - File destDir = new File(destUri.getPath()); - if (!destDir.exists()) { - destDir.mkdirs(); // Create directory if it doesn't exist - } - DocumentFile destDocDir = DocumentFile.fromFile(destDir); - - // Check if file already exists and delete it - DocumentFile existingFile = destDocDir.findFile(fileName); - if (existingFile != null && existingFile.exists()) { - existingFile.delete(); - } - - // Create new file - String mimeType = getMimeTypeFromExtension(fileName); - destFile = destDocDir.createFile(mimeType, fileName); - } else { - // Handle content:// scheme using DocumentFile - DocumentFile destDocDir = DocumentFile.fromTreeUri(context, destUri); - - if (destDocDir == null || !destDocDir.exists() || !destDocDir.isDirectory()) { - callbackContext.error("Destination directory does not exist or is not accessible"); - return; - } - - // Check if file already exists and delete it - DocumentFile existingFile = destDocDir.findFile(fileName); - if (existingFile != null && existingFile.exists()) { - existingFile.delete(); - } - - // Create new file - String mimeType = getMimeTypeFromExtension(fileName); - destFile = destDocDir.createFile(mimeType, fileName); - } - - if (destFile == null || !destFile.exists()) { - callbackContext.error("Failed to create destination file"); - return; - } - - // Open output stream to the created file - out = context.getContentResolver().openOutputStream(destFile.getUri()); - - if ( in == null || out == null) { - callbackContext.error("uri streams are null"); - return; - } - - // Copy stream - byte[] buffer = new byte[8192]; - int len; - while ((len = in .read(buffer)) > 0) { - out.write(buffer, 0, len); - } - - out.flush(); - callbackContext.success(); - } catch (IOException e) { - e.printStackTrace(); - callbackContext.error(e.toString()); - } finally { - try { - if ( in != null) in .close(); - if (out != null) out.close(); - } catch (IOException e) { - e.printStackTrace(); - callbackContext.error(e.toString()); - } - } - } catch (Exception e) { - e.printStackTrace(); - callbackContext.error(e.toString()); - } - break; - case "get-webkit-info": - getWebkitInfo(callbackContext); - break; - case "file-action": - fileAction(arg1, arg2, arg3, arg4, callbackContext); - break; - case "is-powersave-mode": - isPowerSaveMode(callbackContext); - break; - case "get-app-info": - getAppInfo(callbackContext); - break; - case "add-shortcut": - addShortcut( - arg1, - arg2, - arg3, - arg4, - arg5, - arg6, - callbackContext - ); - break; - case "remove-shortcut": - removeShortcut(arg1, callbackContext); - break; - case "pin-shortcut": - pinShortcut(arg1, callbackContext); - break; - case "get-android-version": - getAndroidVersion(callbackContext); - break; - case "request-permissions": - requestPermissions(args.optJSONArray(0), callbackContext); - break; - case "request-permission": - requestPermission(arg1, callbackContext); - break; - case "has-permission": - hasPermission(arg1, callbackContext); - break; - case "open-in-browser": - openInBrowser(arg1, callbackContext); - break; - case "launch-app": - launchApp(arg1, arg2, arg3, callbackContext); - break; - case "get-global-setting": - getGlobalSetting(arg1, callbackContext); - break; - case "get-available-encodings": - getAvailableEncodings(callbackContext); - break; - case "decode": - decode(arg1, arg2, callbackContext); - break; - case "encode": - encode(arg1, arg2, callbackContext); - break; - default: - break; - } - } - } - ); - - return true; + } + ); + + return true; + } + + private void sendLogToJavaScript(String level, String message) { + final String js = + "if (typeof window.log === 'function')" + + " window.log(" + + JSONObject.quote(level) + + ", " + + JSONObject.quote(message) + + ");" + + "else" + + " console.log(" + + JSONObject.quote(level) + + ", " + + JSONObject.quote(message) + + ");"; + + cordova.getActivity().runOnUiThread(() -> { + try { + ( + (android.webkit.WebView) webView.getEngine().getView() + ).evaluateJavascript(js, null); + } catch (Exception e) { + Log.e(TAG, "Failed to send log to JavaScript: " + e.getMessage()); + } + }); + } + + // Helper method to determine MIME type using Android's built-in MimeTypeMap + private String getMimeTypeFromExtension(String fileName) { + String extension = ""; + int lastDotIndex = fileName.lastIndexOf('.'); + if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1) { + extension = fileName.substring(lastDotIndex + 1).toLowerCase(); } - private void sendLogToJavaScript(String level, String message) { - final String js = - "window.log('" + level + "', " + JSONObject.quote(message) + ");"; - cordova - .getActivity() - .runOnUiThread( - new Runnable() { - @Override - public void run() { - webView.loadUrl("javascript:" + js); - } - } - ); + String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension( + extension + ); + return mimeType != null ? mimeType : "application/octet-stream"; + } + + /** + * Starts a streaming HTTP request. The response body is delivered to + * JavaScript incrementally as raw (or base64 encoded) chunks. + * + *

Args: + *

    + *
  1. requestId - unique id used for pause/resume/cancel
  2. + *
  3. url
  4. + *
  5. options JSON object: + * method, headers, body, bodyIsBase64, followRedirects, + * connectTimeout, readTimeout, chunkSize
  6. + *
+ */ + private void httpStreamStart(JSONArray args, CallbackContext callbackContext) { + try { + final String requestId = args.getString(0); + final String url = args.getString(1); + final JSONObject options = args.getJSONObject(2); + + final String method = options.optString("method", "GET"); + final JSONObject headers = options.optJSONObject("headers"); + final String body = options.isNull("body") ? null : options.optString("body"); + final boolean bodyIsBase64 = options.optBoolean("bodyIsBase64", false); + final boolean followRedirects = options.optBoolean("followRedirects", true); + final int connectTimeout = options.optInt("connectTimeout", 30000); + final int readTimeout = options.optInt("readTimeout", 0); + final int chunkSize = options.optInt("chunkSize", 0); + + StreamHttp.start( + requestId, + url, + method, + headers, + body, + bodyIsBase64, + followRedirects, + connectTimeout, + readTimeout, + chunkSize, + callbackContext + ); + } catch (Exception e) { + callbackContext.error("Failed to start stream: " + e.getMessage()); } - - // Helper method to determine MIME type using Android's built-in MimeTypeMap - private String getMimeTypeFromExtension(String fileName) { - String extension = ""; - int lastDotIndex = fileName.lastIndexOf('.'); - if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1) { - extension = fileName.substring(lastDotIndex + 1).toLowerCase(); - } - - String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); - return mimeType != null ? mimeType : "application/octet-stream"; + } + + private void getConfiguration(CallbackContext callback) { + try { + JSONObject result = new JSONObject(); + Configuration config = context.getResources().getConfiguration(); + InputMethodManager imm = (InputMethodManager) context.getSystemService( + Context.INPUT_METHOD_SERVICE + ); + Method method = InputMethodManager.class.getMethod( + "getInputMethodWindowVisibleHeight" + ); + + result.put("isAcceptingText", imm.isAcceptingText()); + result.put("keyboardHeight", method.invoke(imm)); + result.put("locale", config.locale.toString()); + result.put("fontScale", config.fontScale); + result.put("keyboard", config.keyboard); + result.put("keyboardHidden", config.keyboardHidden); + result.put("hardKeyboardHidden", config.hardKeyboardHidden); + result.put("navigationHidden", config.navigationHidden); + result.put("navigation", config.navigation); + result.put("orientation", config.orientation); + callback.success(result); + } catch ( + JSONException + | NoSuchMethodException + | IllegalAccessException + | InvocationTargetException error + ) { + callback.error(error.toString()); } - - private void getConfiguration(CallbackContext callback) { - try { - JSONObject result = new JSONObject(); - Configuration config = context.getResources().getConfiguration(); - InputMethodManager imm = (InputMethodManager) context.getSystemService( - Context.INPUT_METHOD_SERVICE - ); - Method method = - InputMethodManager.class.getMethod("getInputMethodWindowVisibleHeight"); - - result.put("isAcceptingText", imm.isAcceptingText()); - result.put("keyboardHeight", method.invoke(imm)); - result.put("locale", config.locale.toString()); - result.put("fontScale", config.fontScale); - result.put("keyboard", config.keyboard); - result.put("keyboardHidden", config.keyboardHidden); - result.put("hardKeyboardHidden", config.hardKeyboardHidden); - result.put("navigationHidden", config.navigationHidden); - result.put("navigation", config.navigation); - result.put("orientation", config.orientation); - callback.success(result); - } catch ( - JSONException | - NoSuchMethodException | - IllegalAccessException | - InvocationTargetException error - ) { - callback.error(error.toString()); - } + } + + private void decode( + String content, // base64 encoded string + String charSetName, + CallbackContext callback + ) { + try { + byte[] bytes = Base64.decode(content, Base64.DEFAULT); + + if (Charset.isSupported(charSetName) == false) { + callback.error("Charset not supported: " + charSetName); + return; + } + + Charset charSet = Charset.forName(charSetName); + CharBuffer charBuffer = charSet.decode(ByteBuffer.wrap(bytes)); + String result = String.valueOf(charBuffer); + callback.success(result); + } catch (Exception e) { + callback.error(e.toString()); + } + } + + private void encode( + String content, // string to encode + String charSetName, + CallbackContext callback + ) { + try { + if (Charset.isSupported(charSetName) == false) { + callback.error("Charset not supported: " + charSetName); + return; + } + + Charset charSet = Charset.forName(charSetName); + ByteBuffer byteBuffer = charSet.encode(content); + byte[] bytes = new byte[byteBuffer.remaining()]; + byteBuffer.get(bytes); + callback.success(bytes); + } catch (Exception e) { + callback.error(e.toString()); } + } + + /** + * Compares file content with provided text. + * This method runs in a background thread to avoid blocking the UI. + * + * @param fileUri The URI of the file to read (file:// or content://) + * @param encoding The character encoding to use when reading the file + * @param currentText The text to compare against the file content + * @param callback Returns 1 if texts are different, 0 if same + */ + private void compareFileText( + String fileUri, + String encoding, + String currentText, + CallbackContext callback + ) { + try { + if (fileUri == null || fileUri.isEmpty()) { + callback.error("File URI is required"); + return; + } - private void decode( - String content, // base64 encoded string - String charSetName, - CallbackContext callback - ) { - try { - byte[] bytes = Base64.decode(content, Base64.DEFAULT); + if (encoding == null || encoding.isEmpty()) { + encoding = "UTF-8"; + } - if (Charset.isSupported(charSetName) == false) { - callback.error("Charset not supported: " + charSetName); - return; - } + if (!Charset.isSupported(encoding)) { + callback.error("Charset not supported: " + encoding); + return; + } - Charset charSet = Charset.forName(charSetName); - CharBuffer charBuffer = charSet.decode(ByteBuffer.wrap(bytes)); - String result = String.valueOf(charBuffer); - callback.success(result); - } catch (Exception e) { - callback.error(e.toString()); - } - } + Uri uri = Uri.parse(fileUri); + Charset charset = Charset.forName(encoding); + String fileContent; - private void encode( - String content, // string to encode - String charSetName, - CallbackContext callback - ) { - try { - if (Charset.isSupported(charSetName) == false) { - callback.error("Charset not supported: " + charSetName); - return; - } + // Handle file:// URIs + if ("file".equalsIgnoreCase(uri.getScheme())) { + File file = new File(uri.getPath()); - Charset charSet = Charset.forName(charSetName); - ByteBuffer byteBuffer = charSet.encode(content); - byte[] bytes = new byte[byteBuffer.remaining()]; - byteBuffer.get(bytes); - callback.success(bytes); - } catch (Exception e) { - callback.error(e.toString()); + // Validate file + if (!file.exists()) { + callback.error("File does not exist"); + return; } - } - - private void getAvailableEncodings(CallbackContext callback) { - try { - Map < String, Charset > charsets = Charset.availableCharsets(); - JSONObject result = new JSONObject(); - for (Map.Entry < String, Charset > entry: charsets.entrySet()) { - JSONObject obj = new JSONObject(); - Charset charset = entry.getValue(); - obj.put("label", charset.displayName()); - obj.put("aliases", new JSONArray(charset.aliases())); - obj.put("name", charset.name()); - result.put(charset.name(), obj); - } - callback.success(result); - } catch (Exception e) { - callback.error(e.toString()); + if (!file.isFile()) { + callback.error("Path is not a file"); + return; + } + if (!file.canRead()) { + callback.error("File is not readable"); + return; } - } - private void requestPermissions(JSONArray arr, CallbackContext callback) { + Path path = file.toPath(); + fileContent = new String(Files.readAllBytes(path), charset); + } else if ("content".equalsIgnoreCase(uri.getScheme())) { + // Handle content:// URIs (including SAF tree URIs) + InputStream inputStream = null; try { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { - int[] res = new int[arr.length()]; - for (int i = 0; i < res.length; ++i) { - res[i] = 1; - } - callback.success(1); - return; + String uriString = fileUri; + Uri resolvedUri = uri; + + // Check if this is a SAF tree URI with :: separator + if (uriString.contains("::")) { + try { + // Split into tree URI and document ID + String[] parts = uriString.split("::", 2); + String treeUriStr = parts[0]; + String docId = parts[1]; + + // Build document URI directly from tree URI and document ID + Uri treeUri = Uri.parse(treeUriStr); + resolvedUri = DocumentsContract.buildDocumentUriUsingTree( + treeUri, + docId + ); + } catch (Exception e) { + callback.error( + "SAF_FALLBACK: Invalid SAF URI format - " + e.getMessage() + ); + return; } + } - String[] permissions = checkPermissions(arr); + // Try to open the resolved URI + inputStream = context + .getContentResolver() + .openInputStream(resolvedUri); - if (permissions.length > 0) { - requestPermissionCallback = callback; - cordova.requestPermissions(this, REQ_PERMISSIONS, permissions); - return; + if (inputStream == null) { + callback.error("Cannot open file"); + return; + } + + StringBuilder sb = new StringBuilder(); + try ( + BufferedReader reader = new BufferedReader( + new InputStreamReader(inputStream, charset) + ) + ) { + char[] buffer = new char[8192]; + int charsRead; + while ((charsRead = reader.read(buffer)) != -1) { + sb.append(buffer, 0, charsRead); } - callback.success(new JSONArray()); - } catch (Exception e) { - callback.error(e.toString()); + } + fileContent = sb.toString(); + } finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException closeError) { + Log.w( + TAG, + "Failed to close input stream while reading file.", + closeError + ); + } + } } - } + } else { + callback.error("Unsupported URI scheme: " + uri.getScheme()); + return; + } - private void requestPermission(String permission, CallbackContext callback) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { - callback.success(1); - return; + // check length first + if (fileContent.length() != currentText.length()) { + callback.success(1); // Changed + return; + } + + // Full comparison + if (fileContent.equals(currentText)) { + callback.success(0); // Not changed + } else { + callback.success(1); // Changed + } + } catch (Exception e) { + callback.error(e.toString()); + } + } + + /** + * Compares two text strings. + * This method runs in a background thread to avoid blocking the UI + * for large string comparisons. + * + * @param text1 First text to compare + * @param text2 Second text to compare + * @param callback Returns 1 if texts are different, 0 if same + */ + private void compareTexts( + String text1, + String text2, + CallbackContext callback + ) { + try { + if (text1 == null) text1 = ""; + if (text2 == null) text2 = ""; + + // check length first + if (text1.length() != text2.length()) { + callback.success(1); // Changed + return; + } + + // Full comparison + if (text1.equals(text2)) { + callback.success(0); // Not changed + } else { + callback.success(1); // Changed + } + } catch (Exception e) { + callback.error(e.toString()); + } + } + + private void getAvailableEncodings(CallbackContext callback) { + try { + Map charsets = Charset.availableCharsets(); + JSONObject result = new JSONObject(); + for (Map.Entry entry : charsets.entrySet()) { + JSONObject obj = new JSONObject(); + Charset charset = entry.getValue(); + obj.put("label", charset.displayName()); + obj.put("aliases", new JSONArray(charset.aliases())); + obj.put("name", charset.name()); + result.put(charset.name(), obj); + } + callback.success(result); + } catch (Exception e) { + callback.error(e.toString()); + } + } + + private void requestPermissions(JSONArray arr, CallbackContext callback) { + try { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { + int[] res = new int[arr.length()]; + for (int i = 0; i < res.length; ++i) { + res[i] = 1; } + callback.success(1); + return; + } - if (permission != null || !permission.equals("")) { - if (!cordova.hasPermission(permission)) { - requestPermissionCallback = callback; - cordova.requestPermission(this, REQ_PERMISSION, permission); - return; - } + String[] permissions = checkPermissions(arr); - callback.success(1); - return; - } + if (permissions.length > 0) { + requestPermissionCallback = callback; + cordova.requestPermissions(this, REQ_PERMISSIONS, permissions); + return; + } + callback.success(new JSONArray()); + } catch (Exception e) { + callback.error(e.toString()); + } + } - callback.error("No permission passed to request."); + private void requestPermission(String permission, CallbackContext callback) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { + callback.success(1); + return; } - private void hasPermission(String permission, CallbackContext callback) { - if (permission != null || !permission.equals("")) { - int res = 0; - if (cordova.hasPermission(permission)) { - res = 1; - } + if (permission != null || !permission.equals("")) { + if (!cordova.hasPermission(permission)) { + requestPermissionCallback = callback; + cordova.requestPermission(this, REQ_PERMISSION, permission); + return; + } - callback.success(res); - return; - } - callback.error("No permission passed to check."); + callback.success(1); + return; } - public boolean fileExists(String path, String countSymlinks) { - Path p = new File(path).toPath(); - try { - if (Boolean.parseBoolean(countSymlinks)) { - // This will return true even for broken symlinks - return Files.exists(p, LinkOption.NOFOLLOW_LINKS); - } else { - // Check target file, not symlink itself - return Files.exists(p) && !Files.isSymbolicLink(p); - } - } catch (Exception e) { - return false; - } - } + callback.error("No permission passed to request."); + } - public boolean createSymlink(String target, String linkPath) { - try { - Process process = Runtime.getRuntime().exec(new String[] { - "ln", - "-s", - target, - linkPath - }); - return process.waitFor() == 0; - } catch (Exception e) { - return false; - } + private void hasPermission(String permission, CallbackContext callback) { + if (permission != null || !permission.equals("")) { + int res = 0; + if (cordova.hasPermission(permission)) { + res = 1; + } + + callback.success(res); + return; } + callback.error("No permission passed to check."); + } + + public boolean fileExists(String path, String countSymlinks) { + boolean countSymbolicLinks = Boolean.parseBoolean(countSymlinks); + File file = new File(path); - public String getNativeLibraryPath() { - ApplicationInfo appInfo = context.getApplicationInfo(); - return appInfo.nativeLibraryDir; + // Android < O does not implement File#toPath(), fall back to legacy checks + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + return file.exists(); } - public String getFilesDir() { - return context.getFilesDir().getAbsolutePath(); + Path p = file.toPath(); + try { + if (countSymbolicLinks) { + return Files.exists(p, LinkOption.NOFOLLOW_LINKS); + } + return Files.exists(p); + } catch (Exception e) { + return false; + } + } + + public boolean createSymlink(String target, String linkPath) { + try { + Process process = Runtime.getRuntime().exec(new String[] { + "ln", + "-s", + target, + linkPath, + }); + return process.waitFor() == 0; + } catch (Exception e) { + return false; } + } + + public String getNativeLibraryPath() { + ApplicationInfo appInfo = context.getApplicationInfo(); + return appInfo.nativeLibraryDir; + } + + public String getFilesDir() { + return context.getFilesDir().getAbsolutePath(); + } + + public String getParentPath(String path) { + File file = new File(path); + File parent = file.getParentFile(); + return parent != null ? parent.getAbsolutePath() : null; + } + + public JSONArray listChildren(String path) throws JSONException { + File dir = new File(path); + JSONArray result = new JSONArray(); + if (dir.exists() && dir.isDirectory()) { + File[] files = dir.listFiles(); + if (files != null) { + for (File file : files) { + result.put(file.getAbsolutePath()); + } + } + } + return result; + } + + public void onRequestPermissionResult( + int code, + String[] permissions, + int[] resCodes + ) { + if (requestPermissionCallback == null) return; + + if (code == REQ_PERMISSIONS) { + JSONArray resAr = new JSONArray(); + for (int res : resCodes) { + if (res == PackageManager.PERMISSION_DENIED) { + resAr.put(0); + } + resAr.put(1); + } - public String getParentPath(String path) { - File file = new File(path); - File parent = file.getParentFile(); - return parent != null ? parent.getAbsolutePath() : null; + requestPermissionCallback.success(resAr); + requestPermissionCallback = null; + return; } - public JSONArray listChildren(String path) throws JSONException { - File dir = new File(path); - JSONArray result = new JSONArray(); - if (dir.exists() && dir.isDirectory()) { - File[] files = dir.listFiles(); - if (files != null) { - for (File file: files) { - result.put(file.getAbsolutePath()); - } - } + if ( + resCodes.length >= 1 && resCodes[0] == PackageManager.PERMISSION_DENIED + ) { + requestPermissionCallback.success(0); + requestPermissionCallback = null; + return; + } + requestPermissionCallback.success(1); + requestPermissionCallback = null; + return; + } + + private String[] checkPermissions(JSONArray arr) throws Exception { + List list = new ArrayList(); + for (int i = 0; i < arr.length(); i++) { + try { + String permission = arr.getString(i); + if (permission == null || permission.equals("")) { + throw new Exception("Permission cannot be null or empty"); + } + if (!cordova.hasPermission(permission)) { + list.add(permission); } - return result; + } catch (JSONException e) { + Log.w(TAG, "Invalid permission entry at index " + i, e); + } } - public void onRequestPermissionResult( - int code, - String[] permissions, - int[] resCodes - ) { - if (requestPermissionCallback == null) return; + String[] res = new String[list.size()]; + return list.toArray(res); + } - if (code == REQ_PERMISSIONS) { - JSONArray resAr = new JSONArray(); - for (int res: resCodes) { - if (res == PackageManager.PERMISSION_DENIED) { - resAr.put(0); - } - resAr.put(1); - } + private void getAndroidVersion(CallbackContext callback) { + callback.success(Build.VERSION.SDK_INT); + } - requestPermissionCallback.success(resAr); - requestPermissionCallback = null; - return; - } + private void getWebkitInfo(CallbackContext callback) { + PackageInfo info = null; + JSONObject res = new JSONObject(); - if ( - resCodes.length >= 1 && resCodes[0] == PackageManager.PERMISSION_DENIED - ) { - requestPermissionCallback.success(0); - requestPermissionCallback = null; - return; + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + info = WebView.getCurrentWebViewPackage(); + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + Class webViewFactory = Class.forName("android.webkit.WebViewFactory"); + Method method = webViewFactory.getMethod("getLoadedPackageInfo"); + info = (PackageInfo) method.invoke(null); + } else { + PackageManager packageManager = activity.getPackageManager(); + + try { + info = packageManager.getPackageInfo("com.google.android.webview", 0); + } catch (PackageManager.NameNotFoundException e) { + callback.error("Package not found"); } - requestPermissionCallback.success(1); - requestPermissionCallback = null; + return; + } + + res.put("packageName", info.packageName); + res.put("versionName", info.versionName); + res.put("versionCode", info.versionCode); + + callback.success(res); + } catch ( + JSONException + | InvocationTargetException + | ClassNotFoundException + | NoSuchMethodException + | IllegalAccessException e + ) { + callback.error( + "Cannot determine current WebView engine. (" + e.getMessage() + ")" + ); + + return; + } + } + + private void isPowerSaveMode(CallbackContext callback) { + PowerManager powerManager = (PowerManager) context.getSystemService( + Context.POWER_SERVICE + ); + boolean powerSaveMode = powerManager.isPowerSaveMode(); + + callback.success(powerSaveMode ? 1 : 0); + } + + private void pinFileShortcut( + JSONObject shortcutJson, + CallbackContext callback + ) { + if (shortcutJson == null) { + callback.error("Invalid shortcut data"); + return; } - private String[] checkPermissions(JSONArray arr) throws Exception { - List < String > list = new ArrayList < String > (); - for (int i = 0; i < arr.length(); i++) { - try { - String permission = arr.getString(i); - if (permission != null || !permission.equals("")) { - throw new Exception("Permission cannot be null or empty"); - } - if (!cordova.hasPermission(permission)) { - list.add(permission); - } - } catch (JSONException e) {} - } + String id = shortcutJson.optString("id", ""); + String label = shortcutJson.optString("label", ""); + String description = shortcutJson.optString("description", label); + String iconSrc = shortcutJson.optString("icon", ""); + String uriString = shortcutJson.optString("uri", ""); - String[] res = new String[list.size()]; - return list.toArray(res); + if (id.isEmpty() || label.isEmpty() || uriString.isEmpty()) { + callback.error("Missing required shortcut fields"); + return; } - private void getAndroidVersion(CallbackContext callback) { - callback.success(Build.VERSION.SDK_INT); + if (!ShortcutManagerCompat.isRequestPinShortcutSupported(context)) { + callback.error("Pin shortcut not supported on this launcher"); + return; } - private void getWebkitInfo(CallbackContext callback) { - PackageInfo info = null; - JSONObject res = new JSONObject(); + try { + Uri dataUri = Uri.parse(uriString); + String packageName = context.getPackageName(); + PackageManager pm = context.getPackageManager(); - try { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - info = WebView.getCurrentWebViewPackage(); - } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - Class webViewFactory = Class.forName("android.webkit.WebViewFactory"); - Method method = webViewFactory.getMethod("getLoadedPackageInfo"); - info = (PackageInfo) method.invoke(null); - } else { - PackageManager packageManager = activity.getPackageManager(); + Intent launchIntent = pm.getLaunchIntentForPackage(packageName); + if (launchIntent == null) { + callback.error("Launch intent not found for package: " + packageName); + return; + } - try { - info = packageManager.getPackageInfo("com.google.android.webview", 0); - } catch (PackageManager.NameNotFoundException e) { - callback.error("Package not found"); - } + ComponentName componentName = launchIntent.getComponent(); + if (componentName == null) { + callback.error("ComponentName is null"); + return; + } - return; - } + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.setComponent(componentName); + intent.setData(dataUri); + intent.putExtra("acodeFileUri", uriString); - res.put("packageName", info.packageName); - res.put("versionName", info.versionName); - res.put("versionCode", info.versionCode); - - callback.success(res); - } catch ( - JSONException | - InvocationTargetException | - ClassNotFoundException | - NoSuchMethodException | - IllegalAccessException e - ) { - callback.error( - "Cannot determine current WebView engine. (" + e.getMessage() + ")" + IconCompat icon; + + if (iconSrc != null && !iconSrc.isEmpty()) { + try { + Uri iconUri = Uri.parse(iconSrc); + Bitmap bitmap; + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + // API 28+ + ImageDecoder.Source source = ImageDecoder.createSource( + context.getContentResolver(), + iconUri + ); + bitmap = ImageDecoder.decodeBitmap(source); + } else { + // Below API 28 + bitmap = MediaStore.Images.Media.getBitmap( + context.getContentResolver(), + iconUri ); + } - return; + icon = IconCompat.createWithBitmap(bitmap); + } catch (Exception e) { + icon = getFileShortcutIcon(label); } + } else { + icon = getFileShortcutIcon(label); + } + + ShortcutInfoCompat shortcut = new ShortcutInfoCompat.Builder(context, id) + .setShortLabel(label) + .setLongLabel( + description != null && !description.isEmpty() ? description : label + ) + .setIcon(icon) + .setIntent(intent) + .build(); + + ShortcutManagerCompat.pushDynamicShortcut(context, shortcut); + + boolean requested = ShortcutManagerCompat.requestPinShortcut( + context, + shortcut, + null + ); + + if (!requested) { + callback.error("Failed to request pin shortcut"); + return; + } + + callback.success(); + } catch (Exception e) { + callback.error(e.toString()); } + } - private void isPowerSaveMode(CallbackContext callback) { - PowerManager powerManager = (PowerManager) context.getSystemService( - Context.POWER_SERVICE - ); - boolean powerSaveMode = powerManager.isPowerSaveMode(); + private IconCompat getFileShortcutIcon(String filename) { + Bitmap fallback = createFileShortcutBitmap(filename); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + return IconCompat.createWithAdaptiveBitmap(fallback); + } + return IconCompat.createWithBitmap(fallback); + } + + private Bitmap createFileShortcutBitmap(String filename) { + final float baseSizeDp = 72f; + float sizePx = TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, + baseSizeDp, + context.getResources().getDisplayMetrics() + ); + if (sizePx <= 0) { + sizePx = baseSizeDp; + } + int size = Math.round(sizePx); + Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(bitmap); + Paint paint = new Paint( + Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG + ); + + int backgroundColor = pickShortcutColor(filename); + paint.setColor(backgroundColor); + float radius = size * 0.24f; + RectF bounds = new RectF(0, 0, size, size); + canvas.drawRoundRect(bounds, radius, radius, paint); + + paint.setColor(Color.WHITE); + paint.setTextAlign(Paint.Align.CENTER); + paint.setTypeface(Typeface.create("sans-serif-medium", Typeface.BOLD)); + + String label = getShortcutLabel(filename); + float textLength = Math.max(1, label.length()); + float factor = textLength > 4 ? 0.22f : textLength > 3 ? 0.26f : 0.34f; + paint.setTextSize(size * factor); + Paint.FontMetrics metrics = paint.getFontMetrics(); + float baseline = (size - metrics.bottom - metrics.top) / 2f; + canvas.drawText(label, size / 2f, baseline, paint); + + return bitmap; + } + + private String getFileExtension(String filename) { + if (filename == null) return ""; + int dot = filename.lastIndexOf('.'); + if (dot < 0 || dot == filename.length() - 1) return ""; + return filename.substring(dot + 1).toLowerCase(Locale.getDefault()); + } + + private String getShortcutLabel(String filename) { + String ext = getFileExtension(filename); + if (!ext.isEmpty()) { + switch (ext) { + case "js": + case "jsx": + return "JS"; + case "ts": + case "tsx": + return "TS"; + case "md": + case "markdown": + return "MD"; + case "json": + return "JSON"; + case "html": + case "htm": + return "HTML"; + case "css": + return "CSS"; + case "java": + return "JAVA"; + case "kt": + case "kts": + return "KOT"; + case "py": + return "PY"; + case "rb": + return "RB"; + case "c": + return "C"; + case "cpp": + case "cc": + case "cxx": + return "CPP"; + case "h": + case "hpp": + return "HDR"; + case "go": + return "GO"; + case "rs": + return "RS"; + case "php": + return "PHP"; + case "xml": + return "XML"; + case "yml": + case "yaml": + return "YML"; + case "txt": + return "TXT"; + case "sh": + case "bash": + return "SH"; + default: + String label = ext.replaceAll("[^A-Za-z0-9]", ""); + if (label.isEmpty()) label = ext; + if (label.length() > 4) { + label = label.substring(0, 4); + } + return label.toUpperCase(Locale.getDefault()); + } + } - callback.success(powerSaveMode ? 1 : 0); + if (filename != null && !filename.trim().isEmpty()) { + String cleaned = filename.replaceAll("[^A-Za-z0-9]", ""); + if (!cleaned.isEmpty()) { + if (cleaned.length() > 3) cleaned = cleaned.substring(0, 3); + return cleaned.toUpperCase(Locale.getDefault()); + } + return filename.substring(0, 1).toUpperCase(Locale.getDefault()); } - private void fileAction( - String fileURI, - String filename, - String action, - String mimeType, - CallbackContext callback - ) { - Activity activity = this.activity; - Context context = this.context; - Uri uri = this.getContentProviderUri(fileURI); - try { - Intent intent = new Intent(action); + return "FILE"; + } + + private int pickShortcutColor(String filename) { + String ext = getFileExtension(filename); + switch (ext) { + case "js": + case "jsx": + return 0xFFF7DF1E; + case "ts": + case "tsx": + return 0xFF3178C6; + case "md": + case "markdown": + return 0xFF546E7A; + case "json": + return 0xFF4CAF50; + case "html": + case "htm": + return 0xFFF4511E; + case "css": + return 0xFF2962FF; + case "java": + return 0xFFEC6F2D; + case "kt": + case "kts": + return 0xFF7F52FF; + case "py": + return 0xFF306998; + case "rb": + return 0xFFCC342D; + case "c": + return 0xFF546E7A; + case "cpp": + case "cc": + case "cxx": + return 0xFF00599C; + case "h": + case "hpp": + return 0xFF8D6E63; + case "go": + return 0xFF00ADD8; + case "rs": + return 0xFFB7410E; + case "php": + return 0xFF8892BF; + case "xml": + return 0xFF5C6BC0; + case "yml": + case "yaml": + return 0xFF757575; + case "txt": + return 0xFF546E7A; + case "sh": + case "bash": + return 0xFF388E3C; + default: + final int[] colors = new int[] { + 0xFF1E88E5, + 0xFF6D4C41, + 0xFF00897B, + 0xFF8E24AA, + 0xFF3949AB, + 0xFF039BE5, + 0xFFD81B60, + 0xFF43A047, + }; + String key = ext.isEmpty() + ? (filename == null ? "file" : filename) + : ext; + int hash = Math.abs(key.hashCode()); + return colors[hash % colors.length]; + } + } + + private void fileAction( + String fileURI, + String filename, + String action, + String mimeType, + CallbackContext callback + ) { + Activity activity = this.activity; + Context context = this.context; + Uri uri = this.getContentProviderUri(fileURI, filename); + if (uri == null) { + callback.error("Unable to access file for action " + action); + return; + } + try { + Intent intent = new Intent(action); + + if (mimeType.equals("")) { + mimeType = "text/plain"; + } + + mimeType = resolveMimeType(mimeType, uri, filename); + + String clipLabel = null; + if (filename != null && !filename.isEmpty()) { + clipLabel = new File(filename).getName(); + } + if (clipLabel == null || clipLabel.isEmpty()) { + clipLabel = uri.getLastPathSegment(); + } + if (clipLabel == null || clipLabel.isEmpty()) { + clipLabel = "shared-file"; + } + if (action.equals(Intent.ACTION_SEND)) { + intent.setType(mimeType); + intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + intent.setClipData( + ClipData.newUri(context.getContentResolver(), clipLabel, uri) + ); + intent.putExtra(Intent.EXTRA_STREAM, uri); + intent.putExtra(Intent.EXTRA_TITLE, clipLabel); + intent.putExtra(Intent.EXTRA_SUBJECT, clipLabel); + if (filename != null && !filename.isEmpty()) { + intent.putExtra(Intent.EXTRA_TEXT, filename); + } + } else { + int flags = + Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION | + Intent.FLAG_GRANT_READ_URI_PERMISSION; - if (mimeType.equals("")) { - mimeType = "text/plain"; - } + if (action.equals(Intent.ACTION_EDIT)) { + flags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION; + } - if (action.equals(Intent.ACTION_SEND)) { - intent.putExtra(Intent.EXTRA_STREAM, uri); - if (!filename.equals("")) { - intent.putExtra(Intent.EXTRA_TEXT, filename); - } - intent.setType(mimeType); - } else { - int flags = - Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION | - Intent.FLAG_GRANT_READ_URI_PERMISSION; - - if (action.equals(Intent.ACTION_EDIT)) { - flags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION; - } + intent.setFlags(flags); + intent.setDataAndType(uri, mimeType); + intent.setClipData( + ClipData.newUri(context.getContentResolver(), clipLabel, uri) + ); + intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + if (!clipLabel.equals("shared-file")) { + intent.putExtra(Intent.EXTRA_TITLE, clipLabel); + } + if (action.equals(Intent.ACTION_EDIT)) { + intent.putExtra(Intent.EXTRA_STREAM, uri); + } + } + + int permissionFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION; + if (action.equals(Intent.ACTION_EDIT)) { + permissionFlags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION; + } + grantUriPermissions(intent, uri, permissionFlags); + + if (action.equals(Intent.ACTION_SEND)) { + Intent chooserIntent = Intent.createChooser(intent, null); + chooserIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + activity.startActivity(chooserIntent); + } else if ( + action.equals(Intent.ACTION_EDIT) || action.equals(Intent.ACTION_VIEW) + ) { + Intent chooserIntent = Intent.createChooser(intent, null); + chooserIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + if (action.equals(Intent.ACTION_EDIT)) { + chooserIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); + } + activity.startActivity(chooserIntent); + } else { + activity.startActivity(intent); + } + callback.success(uri.toString()); + } catch (Exception e) { + callback.error(e.getMessage()); + } + } + + private void getAppInfo(CallbackContext callback) { + JSONObject res = new JSONObject(); + try { + PackageManager pm = activity.getPackageManager(); + PackageInfo pInfo = pm.getPackageInfo(context.getPackageName(), 0); + ApplicationInfo appInfo = context.getApplicationInfo(); + int isDebuggable = appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE; + + res.put("firstInstallTime", pInfo.firstInstallTime); + res.put("lastUpdateTime", pInfo.lastUpdateTime); + res.put("label", appInfo.loadLabel(pm).toString()); + res.put("packageName", pInfo.packageName); + res.put("versionName", pInfo.versionName); + res.put("versionCode", pInfo.getLongVersionCode()); + res.put("isDebuggable", isDebuggable); + + callback.success(res); + } catch (JSONException e) { + callback.error(e.getMessage()); + } catch (Exception e) { + callback.error(e.getMessage()); + } + } - intent.setFlags(flags); - intent.setDataAndType(uri, mimeType); - } + private void openInBrowser(String src, CallbackContext callback) { + if (src == null || src.isEmpty()) { + callback.error("No URL provided."); + return; + } - activity.startActivity(intent); - callback.success(uri.toString()); - } catch (Exception e) { - callback.error(e.getMessage()); - } + Uri uri = Uri.parse(src); + if ("file".equalsIgnoreCase(uri.getScheme())) { + // file:// URIs can't leave the app (FileUriExposedException). + callback.error("Cannot open file URI in browser: " + src); + return; } - private void getAppInfo(CallbackContext callback) { - JSONObject res = new JSONObject(); - try { - PackageManager pm = activity.getPackageManager(); - PackageInfo pInfo = pm.getPackageInfo(context.getPackageName(), 0); - ApplicationInfo appInfo = context.getApplicationInfo(); - int isDebuggable = appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE; - - res.put("firstInstallTime", pInfo.firstInstallTime); - res.put("lastUpdateTime", pInfo.lastUpdateTime); - res.put("label", appInfo.loadLabel(pm).toString()); - res.put("packageName", pInfo.packageName); - res.put("versionName", pInfo.versionName); - res.put("versionCode", pInfo.getLongVersionCode()); - res.put("isDebuggable", isDebuggable); - - callback.success(res); - } catch (JSONException e) { - callback.error(e.getMessage()); - } catch (Exception e) { - callback.error(e.getMessage()); - } + try { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri); + activity.startActivity(browserIntent); + callback.success(); + } catch (Exception e) { + Log.e("System", "Failed to open URL: " + src, e); + callback.error(e.getMessage()); + } + } + + private void launchApp( + String appId, + String className, + JSONObject extras, + CallbackContext callback + ) { + if (appId == null || appId.equals("")) { + callback.error("No package name provided."); + return; } - private void openInBrowser(String src, CallbackContext callback) { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(src)); - activity.startActivity(browserIntent); + if (className == null || className.equals("")) { + callback.error("No activity class name provided."); + return; } - private void launchApp( - String appId, - String className, - String data, - CallbackContext callback - ) { - if (appId == null || appId.equals("")) { - callback.error("No package name provided."); - return; + try { + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.addCategory(Intent.CATEGORY_LAUNCHER); + intent.setPackage(appId); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + intent.setClassName(appId, className); + + if (extras != null) { + Iterator keys = extras.keys(); + + while (keys.hasNext()) { + String key = keys.next(); + Object value = extras.get(key); + + if (value instanceof Integer) { + intent.putExtra(key, (Integer) value); + } else if (value instanceof Boolean) { + intent.putExtra(key, (Boolean) value); + } else if (value instanceof Double) { + intent.putExtra(key, (Double) value); + } else if (value instanceof Long) { + intent.putExtra(key, (Long) value); + } else if (value instanceof String) { + intent.putExtra(key, (String) value); + } else { + intent.putExtra(key, value.toString()); + } } + } - if (className == null || className.equals("")) { - callback.error("No activity class name provided."); - return; - } + activity.startActivity(intent); + callback.success("Launched " + appId); + } catch (Exception e) { + callback.error(e.toString()); + } + } + + private void addShortcut( + String id, + String label, + String description, + String iconSrc, + String action, + String data, + CallbackContext callback + ) { + try { + Intent intent; + ImageDecoder.Source imgSrc; + Bitmap bitmap; + IconCompat icon; + + imgSrc = ImageDecoder.createSource( + context.getContentResolver(), + Uri.parse(iconSrc) + ); + bitmap = ImageDecoder.decodeBitmap(imgSrc); + icon = IconCompat.createWithBitmap(bitmap); + intent = activity + .getPackageManager() + .getLaunchIntentForPackage(activity.getPackageName()); + intent.putExtra("action", action); + intent.putExtra("data", data); + + ShortcutInfoCompat shortcut = new ShortcutInfoCompat.Builder(context, id) + .setShortLabel(label) + .setLongLabel(description) + .setIcon(icon) + .setIntent(intent) + .build(); + + ShortcutManagerCompat.pushDynamicShortcut(context, shortcut); + callback.success(); + } catch (Exception e) { + callback.error(e.toString()); + } + } + + private void pinShortcut(String id, CallbackContext callback) { + ShortcutManager shortcutManager = context.getSystemService( + ShortcutManager.class + ); + + if (shortcutManager.isRequestPinShortcutSupported()) { + ShortcutInfo pinShortcutInfo = new ShortcutInfo.Builder( + context, + id + ).build(); + + Intent pinnedShortcutCallbackIntent = + shortcutManager.createShortcutResultIntent(pinShortcutInfo); + + PendingIntent successCallback = PendingIntent.getBroadcast( + context, + 0, + pinnedShortcutCallbackIntent, + PendingIntent.FLAG_IMMUTABLE + ); + + shortcutManager.requestPinShortcut( + pinShortcutInfo, + successCallback.getIntentSender() + ); + + callback.success(); + return; + } + callback.error("Not supported"); + } + + private void removeShortcut(String id, CallbackContext callback) { + try { + List list = new ArrayList(); + list.add(id); + ShortcutManagerCompat.removeDynamicShortcuts(context, list); + callback.success(); + } catch (Exception e) { + callback.error(e.toString()); + } + } + + private void setUiTheme( + final String systemBarColor, + final JSONObject scheme, + final CallbackContext callback + ) { + try { + this.systemBarColor = Color.parseColor(systemBarColor); + this.theme = new Theme(scheme); + + preferences.set("BackgroundColor", this.systemBarColor); + webView.getPluginManager().postMessage("updateSystemBars", null); + applySystemBarTheme(); + + if (scheme != null) { try { - Intent intent = new Intent(Intent.ACTION_MAIN); - intent.addCategory(Intent.CATEGORY_LAUNCHER); - intent.setPackage(appId); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + android.content.SharedPreferences themePrefs = activity + .getApplicationContext() + .getSharedPreferences("acode_theme", Context.MODE_PRIVATE); + android.content.SharedPreferences.Editor prefEditor = themePrefs.edit(); + Iterator keys = scheme.keys(); + while (keys.hasNext()) { + String key = keys.next(); + prefEditor.putString(key, scheme.optString(key)); + } + prefEditor.apply(); + } catch (Exception ignored) {} + } + + callback.success(); + } catch (IllegalArgumentException e) { + callback.error("Invalid color: " + systemBarColor); + } catch (Exception e) { + callback.error(e.toString()); + } + } - if (data != null && !data.equals("")) { - intent.putExtra("acode_data", data); - } + private void applySystemBarTheme() { + final Window window = activity.getWindow(); + final View decorView = window.getDecorView(); - intent.setClassName(appId, className); - activity.startActivity(intent); - callback.success("Launched " + appId); - } catch (Exception e) { - callback.error(e.toString()); - return; - } + // Keep Cordova's BackgroundColor flow for API 36+, but also apply the + // window colors directly so OEM variants do not leave stale system-bar + // colors behind after a theme switch. + window.clearFlags(0x04000000 | 0x08000000); // FLAG_TRANSLUCENT_STATUS | FLAG_TRANSLUCENT_NAVIGATION + window.addFlags(0x80000000); // FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + window.setNavigationBarContrastEnforced(false); + window.setStatusBarContrastEnforced(false); + } + decorView.setBackgroundColor(this.systemBarColor); + View rootView = activity.findViewById(android.R.id.content); + if (rootView != null) { + rootView.setBackgroundColor(this.systemBarColor); } - - private void addShortcut( - String id, - String label, - String description, - String iconSrc, - String action, - String data, - CallbackContext callback - ) { - try { - Intent intent; - ImageDecoder.Source imgSrc; - Bitmap bitmap; - IconCompat icon; - - imgSrc = ImageDecoder.createSource( - context.getContentResolver(), - Uri.parse(iconSrc) - ); - bitmap = ImageDecoder.decodeBitmap(imgSrc); - icon = IconCompat.createWithBitmap(bitmap); - intent = activity - .getPackageManager() - .getLaunchIntentForPackage(activity.getPackageName()); - intent.putExtra("action", action); - intent.putExtra("data", data); - - ShortcutInfoCompat shortcut = new ShortcutInfoCompat.Builder(context, id) - .setShortLabel(label) - .setLongLabel(description) - .setIcon(icon) - .setIntent(intent) - .build(); - - ShortcutManagerCompat.pushDynamicShortcut(context, shortcut); - callback.success(); - } catch (Exception e) { - callback.error(e.toString()); - } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + window.setStatusBarColor(this.systemBarColor); + window.setNavigationBarColor(this.systemBarColor); } - private void pinShortcut(String id, CallbackContext callback) { - ShortcutManager shortcutManager = context.getSystemService( - ShortcutManager.class - ); + setStatusBarStyle(window); + setNavigationBarStyle(window); + } - if (shortcutManager.isRequestPinShortcutSupported()) { - ShortcutInfo pinShortcutInfo = new ShortcutInfo.Builder( - context, - id - ).build(); + private void setStatusBarStyle(final Window window) { + String themeType = theme.getType(); + View decorView = window.getDecorView(); + int uiOptions; + int lightStatusBar; - Intent pinnedShortcutCallbackIntent = - shortcutManager.createShortcutResultIntent(pinShortcutInfo); + if (SDK_INT <= 30) { + uiOptions = getDeprecatedSystemUiVisibility(decorView); + lightStatusBar = deprecatedFlagUiLightStatusBar(); - PendingIntent successCallback = PendingIntent.getBroadcast( - context, - 0, - pinnedShortcutCallbackIntent, - PendingIntent.FLAG_IMMUTABLE - ); + if (themeType.equals("light")) { + setDeprecatedSystemUiVisibility(decorView, uiOptions | lightStatusBar); + return; + } + setDeprecatedSystemUiVisibility(decorView, uiOptions & ~lightStatusBar); + return; + } - shortcutManager.requestPinShortcut( - pinShortcutInfo, - successCallback.getIntentSender() - ); + uiOptions = Objects.requireNonNull( + decorView.getWindowInsetsController() + ).getSystemBarsAppearance(); + lightStatusBar = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS; - callback.success(); - return; - } + if (themeType.equals("light")) { + decorView + .getWindowInsetsController() + .setSystemBarsAppearance(uiOptions | lightStatusBar, lightStatusBar); + return; + } - callback.error("Not supported"); + decorView + .getWindowInsetsController() + .setSystemBarsAppearance(uiOptions & ~lightStatusBar, lightStatusBar); + } + + private void setNavigationBarStyle(final Window window) { + String themeType = theme.getType(); + View decorView = window.getDecorView(); + int uiOptions; + int lightNavigationBar; + + if (SDK_INT <= 30) { + uiOptions = getDeprecatedSystemUiVisibility(decorView); + lightNavigationBar = View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR; + + if (themeType.equals("light")) { + setDeprecatedSystemUiVisibility( + decorView, + uiOptions | lightNavigationBar + ); + return; + } + setDeprecatedSystemUiVisibility( + decorView, + uiOptions & ~lightNavigationBar + ); + return; } - private void removeShortcut(String id, CallbackContext callback) { - try { - List < String > list = new ArrayList < String > (); - list.add(id); - ShortcutManagerCompat.removeDynamicShortcuts(context, list); - callback.success(); - } catch (Exception e) { - callback.error(e.toString()); - } + uiOptions = Objects.requireNonNull( + decorView.getWindowInsetsController() + ).getSystemBarsAppearance(); + lightNavigationBar = + WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS; + + if (themeType.equals("light")) { + decorView + .getWindowInsetsController() + .setSystemBarsAppearance( + uiOptions | lightNavigationBar, + lightNavigationBar + ); + return; } - private void setUiTheme( - final String systemBarColor, - final JSONObject scheme, - final CallbackContext callback - ) { - this.systemBarColor = Color.parseColor(systemBarColor); - this.theme = new Theme(scheme); + decorView + .getWindowInsetsController() + .setSystemBarsAppearance( + uiOptions & ~lightNavigationBar, + lightNavigationBar + ); + } + + private int deprecatedFlagUiLightStatusBar() { + return View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; + } + + private int getDeprecatedSystemUiVisibility(View decorView) { + return decorView.getSystemUiVisibility(); + } + + private void setDeprecatedSystemUiVisibility(View decorView, int visibility) { + decorView.setSystemUiVisibility(visibility); + } + + private void getCordovaIntent(CallbackContext callback) { + Intent intent = activity.getIntent(); + if (isReservedAuthIntent(intent)) { + callback.sendPluginResult( + new PluginResult(PluginResult.Status.OK, new JSONObject()) + ); + return; + } + callback.sendPluginResult( + new PluginResult(PluginResult.Status.OK, getIntentJson(intent)) + ); + } + + private void setIntentHandler(CallbackContext callback) { + intentHandler = callback; + PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); + result.setKeepCallback(true); + callback.sendPluginResult(result); + } + + @Override + public void onNewIntent(Intent intent) { + if (isReservedAuthIntent(intent)) { + return; + } + if (intentHandler != null) { + PluginResult result = new PluginResult( + PluginResult.Status.OK, + getIntentJson(intent) + ); + result.setKeepCallback(true); + intentHandler.sendPluginResult(result); + } + } - final Window window = activity.getWindow(); - // Method and constants not available on all SDKs but we want to be able to compile this code with any SDK - window.clearFlags(0x04000000); // SDK 19: WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - window.addFlags(0x80000000); // SDK 21: WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); + private boolean isReservedAuthIntent(Intent intent) { + Uri data = intent != null ? intent.getData() : null; + if (data == null || !"acode".equals(data.getScheme())) { + return false; + } + String host = data.getHost(); + String path = data.getPath(); + return "auth".equals(host) && "/callback".equals(path); + } + + private JSONObject getIntentJson(Intent intent) { + JSONObject json = new JSONObject(); + try { + json.put("action", intent.getAction()); + json.put("data", intent.getDataString()); + json.put("type", intent.getType()); + json.put("package", intent.getPackage()); + json.put("uris", getIntentUris(intent)); + json.put("extras", getExtrasJson(intent.getExtras())); + } catch (JSONException | RuntimeException e) { + e.printStackTrace(); + } + return json; + } + + private JSONArray getIntentUris(Intent intent) { + Set uris = new LinkedHashSet<>(); + String action = intent.getAction(); + if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_EDIT.equals(action)) { + if (intent.getData() != null) uris.add(intent.getData()); + } else if (!Intent.ACTION_SEND.equals(action) && !Intent.ACTION_SEND_MULTIPLE.equals(action)) { + return new JSONArray(); + } + try { + Object stream = intent.getExtras() == null ? null : intent.getExtras().get(Intent.EXTRA_STREAM); + if (stream instanceof Uri) uris.add((Uri) stream); + else if (stream instanceof ArrayList) { + for (Object item : (ArrayList) stream) { + if (item instanceof Uri) uris.add((Uri) item); + } + } + } catch (RuntimeException error) { + Log.w(TAG, "Unable to read shared streams", error); + } + ClipData clip = intent.getClipData(); + if (clip != null) { + for (int i = 0; i < clip.getItemCount(); i++) { + Uri uri = clip.getItemAt(i).getUri(); + if (uri != null) uris.add(uri); + } + } + JSONArray result = new JSONArray(); + for (Uri uri : uris) { + if (!"content".equals(uri.getScheme()) && !"file".equals(uri.getScheme())) continue; + result.put(uri.toString()); + int grants = intent.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); + if ("content".equals(uri.getScheme()) && grants != 0 && + (intent.getFlags() & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0) { try { - // Using reflection makes sure any 5.0+ device will work without having to compile with SDK level 21 - - window - .getClass() - .getMethod("setNavigationBarColor", int.class) - .invoke(window, this.systemBarColor); - - window - .getClass() - .getMethod("setStatusBarColor", int.class) - .invoke(window, this.systemBarColor); - - window.getDecorView().setBackgroundColor(this.systemBarColor); - - if (Build.VERSION.SDK_INT < 30) { - setStatusBarStyle(window); - setNavigationBarStyle(window); - } else { - String themeType = theme.getType(); - WindowInsetsController controller = window.getInsetsController(); - int appearance = - WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS | - WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS; - - if (themeType.equals("light")) { - controller.setSystemBarsAppearance(appearance, appearance); - } else { - controller.setSystemBarsAppearance(0, appearance); - } - } - callback.success("OK"); - } catch (IllegalArgumentException error) { - callback.error(error.toString()); - } catch (Exception error) { - callback.error(error.toString()); + context.getContentResolver().takePersistableUriPermission(uri, grants); + } catch (SecurityException | IllegalArgumentException ignored) { + // Temporary access remains valid when a provider cannot persist the grant. } + } } + return result; + } - private void setStatusBarStyle(final Window window) { - String themeType = theme.getType(); - View decorView = window.getDecorView(); - int uiOptions; - int lightStatusBar; - - if (SDK_INT <= 30) { - uiOptions = getDeprecatedSystemUiVisibility(decorView); - lightStatusBar = deprecatedFlagUiLightStatusBar(); - - if (themeType.equals("light")) { - setDeprecatedSystemUiVisibility(decorView, uiOptions | lightStatusBar); - return; - } - setDeprecatedSystemUiVisibility(decorView, uiOptions & ~lightStatusBar); - return; + private JSONObject getExtrasJson(Bundle extras) { + JSONObject json = new JSONObject(); + if (extras != null) { + for (String key : extras.keySet()) { + try { + Object value = extras.get(key); + if (value instanceof String) { + json.put(key, (String) value); + } else if (value instanceof Integer) { + json.put(key, (Integer) value); + } else if (value instanceof Long) { + json.put(key, (Long) value); + } else if (value instanceof Double) { + json.put(key, (Double) value); + } else if (value instanceof Float) { + json.put(key, (Float) value); + } else if (value instanceof Boolean) { + json.put(key, (Boolean) value); + } else if (value instanceof Bundle) { + json.put(key, getExtrasJson((Bundle) value)); + } else if (value != null) { + json.put(key, value.toString()); + } + } catch (JSONException e) { + e.printStackTrace(); } + } + } + return json; + } - uiOptions = Objects.requireNonNull(decorView.getWindowInsetsController()).getSystemBarsAppearance(); - lightStatusBar = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS; + private Uri getContentProviderUri(String fileUri) { + return this.getContentProviderUri(fileUri, ""); + } - if (themeType.equals("light")) { - decorView.getWindowInsetsController().setSystemBarsAppearance(uiOptions | lightStatusBar, lightStatusBar); - return; - } - - decorView.getWindowInsetsController().setSystemBarsAppearance(uiOptions & ~lightStatusBar, lightStatusBar); + private Uri getContentProviderUri(String fileUri, String filename) { + if (fileUri == null || fileUri.isEmpty()) { + return null; } - private void setNavigationBarStyle(final Window window) { - String themeType = theme.getType(); - View decorView = window.getDecorView(); - int uiOptions; - - if (SDK_INT <= 30) { - uiOptions = getDeprecatedSystemUiVisibility(decorView); - // 0x80000000 FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS - // 0x00000010 SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR + Uri uri = Uri.parse(fileUri); + if (uri == null) { + return null; + } - if (themeType.equals("light")) { - setDeprecatedSystemUiVisibility(decorView, uiOptions | 0x80000000 | 0x00000010); - return; - } - setDeprecatedSystemUiVisibility(decorView, uiOptions | (0x80000000 & ~0x00000010)); - return; + if ("file".equalsIgnoreCase(uri.getScheme())) { + File originalFile = new File(uri.getPath()); + if (!originalFile.exists()) { + Log.e("System", "File does not exist for URI: " + fileUri); + return null; + } + + String authority = getFileProviderAuthority(); + if (authority == null) { + Log.e("System", "No FileProvider authority available."); + return null; + } + + try { + return FileProvider.getUriForFile(context, authority, originalFile); + } catch (IllegalArgumentException | SecurityException ex) { + try { + File cacheCopy = ensureShareableCopy(originalFile, filename); + return FileProvider.getUriForFile(context, authority, cacheCopy); + } catch (Exception copyError) { + Log.e("System", "Failed to expose file via FileProvider", copyError); + return null; } + } + } + return uri; + } + + private File ensureShareableCopy(File source, String displayName) + throws IOException { + File cacheRoot = new File(context.getCacheDir(), "shared"); + if (!cacheRoot.exists() && !cacheRoot.mkdirs()) { + throw new IOException("Unable to create shared cache directory"); + } - uiOptions = Objects.requireNonNull(decorView.getWindowInsetsController()).getSystemBarsAppearance(); - int lightNavigationBar = WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS; + if (displayName != null && !displayName.isEmpty()) { + displayName = new File(displayName).getName(); + } + if (displayName == null || displayName.isEmpty()) { + displayName = source.getName(); + } + if (displayName == null || displayName.isEmpty()) { + displayName = "shared-file"; + } - if (themeType.equals("light")) { - decorView.getWindowInsetsController().setSystemBarsAppearance(uiOptions | lightNavigationBar, lightNavigationBar); - return; - } + File target = new File(cacheRoot, displayName); + target = ensureUniqueFile(target); + copyFile(source, target); + return target; + } - decorView.getWindowInsetsController().setSystemBarsAppearance(uiOptions & ~lightNavigationBar, lightNavigationBar); + private File ensureUniqueFile(File target) { + if (!target.exists()) { + return target; } - private int deprecatedFlagUiLightStatusBar() { - return View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; + String name = target.getName(); + String prefix = name; + String suffix = ""; + int dotIndex = name.lastIndexOf('.'); + if (dotIndex > 0) { + prefix = name.substring(0, dotIndex); + suffix = name.substring(dotIndex); } - private int getDeprecatedSystemUiVisibility(View decorView) { - return decorView.getSystemUiVisibility(); + int index = 1; + File candidate = target; + while (candidate.exists()) { + candidate = new File( + target.getParentFile(), + prefix + "-" + index + suffix + ); + index++; } + return candidate; + } - private void setDeprecatedSystemUiVisibility(View decorView, int visibility) { - decorView.setSystemUiVisibility(visibility); + private void copyFile(File source, File destination) throws IOException { + try ( + InputStream in = new FileInputStream(source); + OutputStream out = new FileOutputStream(destination) + ) { + byte[] buffer = new byte[8192]; + int length; + while ((length = in.read(buffer)) != -1) { + out.write(buffer, 0, length); + } + out.flush(); } - - private void getCordovaIntent(CallbackContext callback) { - Intent intent = activity.getIntent(); - callback.sendPluginResult( - new PluginResult(PluginResult.Status.OK, getIntentJson(intent)) - ); + } + + private void grantUriPermissions(Intent intent, Uri uri, int flags) { + if (uri == null) return; + PackageManager pm = context.getPackageManager(); + List resInfoList = pm.queryIntentActivities( + intent, + PackageManager.MATCH_DEFAULT_ONLY + ); + for (ResolveInfo resolveInfo : resInfoList) { + String packageName = resolveInfo.activityInfo.packageName; + context.grantUriPermission(packageName, uri, flags); } + } - private void setIntentHandler(CallbackContext callback) { - intentHandler = callback; - PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); - result.setKeepCallback(true); - callback.sendPluginResult(result); + private String resolveMimeType(String currentMime, Uri uri, String filename) { + if ( + currentMime != null && + !currentMime.isEmpty() && + !currentMime.equals("*/*") + ) { + return currentMime; } - @Override - public void onNewIntent(Intent intent) { - if (intentHandler != null) { - PluginResult result = new PluginResult( - PluginResult.Status.OK, - getIntentJson(intent) - ); - result.setKeepCallback(true); - intentHandler.sendPluginResult(result); - } + String mime = null; + if (uri != null) { + mime = context.getContentResolver().getType(uri); } - private JSONObject getIntentJson(Intent intent) { - JSONObject json = new JSONObject(); - try { - json.put("action", intent.getAction()); - json.put("data", intent.getDataString()); - json.put("type", intent.getType()); - json.put("package", intent.getPackage()); - json.put("extras", getExtrasJson(intent.getExtras())); - } catch (JSONException e) { - e.printStackTrace(); - } - return json; + if ((mime == null || mime.isEmpty()) && filename != null) { + mime = getMimeTypeFromExtension(filename); } - private JSONObject getExtrasJson(Bundle extras) { - JSONObject json = new JSONObject(); - if (extras != null) { - for (String key: extras.keySet()) { - try { - Object value = extras.get(key); - if (value instanceof String) { - json.put(key, (String) value); - } else if (value instanceof Integer) { - json.put(key, (Integer) value); - } else if (value instanceof Long) { - json.put(key, (Long) value); - } else if (value instanceof Double) { - json.put(key, (Double) value); - } else if (value instanceof Float) { - json.put(key, (Float) value); - } else if (value instanceof Boolean) { - json.put(key, (Boolean) value); - } else if (value instanceof Bundle) { - json.put(key, getExtrasJson((Bundle) value)); - } else { - json.put(key, value.toString()); - } - } catch (JSONException e) { - e.printStackTrace(); - } - } - } - return json; + if ((mime == null || mime.isEmpty()) && uri != null) { + String path = uri.getPath(); + if (path != null) { + mime = getMimeTypeFromExtension(path); + } } - private Uri getContentProviderUri(String fileUri) { - return this.getContentProviderUri(fileUri, ""); - } + return (mime != null && !mime.isEmpty()) ? mime : "*/*"; + } - private Uri getContentProviderUri(String fileUri, String filename) { - Uri uri = Uri.parse(fileUri); - String Id = context.getPackageName(); - if (fileUri.matches("file:///(.*)")) { - File file = new File(uri.getPath()); - if (filename.equals("")) { - return FileProvider.getUriForFile(context, Id + ".provider", file); - } + private String getFileProviderAuthority() { + if (fileProviderAuthority != null && !fileProviderAuthority.isEmpty()) { + return fileProviderAuthority; + } - return FileProvider.getUriForFile( - context, - Id + ".provider", - file, - filename - ); + try { + PackageManager pm = context.getPackageManager(); + PackageInfo packageInfo = pm.getPackageInfo( + context.getPackageName(), + PackageManager.GET_PROVIDERS + ); + if (packageInfo.providers != null) { + for (ProviderInfo providerInfo : packageInfo.providers) { + if ( + providerInfo != null && + providerInfo.name != null && + providerInfo.name.equals(FileProvider.class.getName()) + ) { + fileProviderAuthority = providerInfo.authority; + break; + } } - return uri; + } + } catch (PackageManager.NameNotFoundException error) { + Log.w( + TAG, + "Unable to inspect package providers for FileProvider authority.", + error + ); } - private boolean isPackageInstalled( - String packageName, - PackageManager packageManager, - CallbackContext callback - ) { - try { - packageManager.getPackageInfo(packageName, 0); - return true; - } catch (PackageManager.NameNotFoundException e) { - return false; - } + if (fileProviderAuthority == null || fileProviderAuthority.isEmpty()) { + fileProviderAuthority = context.getPackageName() + ".provider"; } - private void getGlobalSetting(String setting, CallbackContext callback) { - int value = (int) Global.getFloat( - context.getContentResolver(), - setting, -1 - ); - callback.success(value); + return fileProviderAuthority; + } + + private boolean isPackageInstalled( + String packageName, + PackageManager packageManager, + CallbackContext callback + ) { + try { + packageManager.getPackageInfo(packageName, 0); + return true; + } catch (PackageManager.NameNotFoundException e) { + return false; } + } + + private void getGlobalSetting(String setting, CallbackContext callback) { + int value = (int) Global.getFloat( + context.getContentResolver(), + setting, + -1 + ); + callback.success(value); + } + + private void clearCache(CallbackContext callback) { + webView.clearCache(true); + callback.success("Cache cleared"); + } + + private void setInputType(String type) { + int mode = -1; + if (type.equals("NO_SUGGESTIONS")) { + mode = 0; + } else if (type.equals("NO_SUGGESTIONS_AGGRESSIVE")) { + mode = 1; + } + webView.setInputType(mode); + } - private void clearCache(CallbackContext callback) { - webView.clearCache(true); - callback.success("Cache cleared"); + private void setNativeContextMenuDisabled(boolean disabled) { + if (webView == null) { + return; } + webView.setNativeContextMenuDisabled(disabled); + } + + /** + * Dynamically changes the app icon by toggling activity-alias components. + * + *

The launcher icon is always represented by an activity-alias (including + * the default icon) so that the running MainActivity component never has to + * be disabled. Disabling the currently running component would make Android + * force-stop/restart the app, so only aliases are toggled here. + * + * @param iconName Icon id (e.g. "midnight_circuit") or "default" to restore + * the original launcher icon. + * @param callback Callback invoked with the result. + */ + private void setAppIcon(String iconName, CallbackContext callback) { + try { + String packageName = context.getPackageName(); + PackageManager pm = context.getPackageManager(); + String key = iconName == null ? "default" : iconName.toLowerCase(); + + String targetAlias = APP_ICON_ALIASES.get(key); + if (targetAlias == null) { + callback.error("Unknown app icon: " + iconName); + return; + } + + pm.setComponentEnabledSetting( + new ComponentName(packageName, packageName + "." + targetAlias), + PackageManager.COMPONENT_ENABLED_STATE_ENABLED, + PackageManager.DONT_KILL_APP + ); - private void setInputType(String type) { - int mode = -1; - if (type.equals("NO_SUGGESTIONS")) { - mode = 0; - } else if (type.equals("NO_SUGGESTIONS_AGGRESSIVE")) { - mode = 1; + for (Map.Entry entry : APP_ICON_ALIASES.entrySet()) { + if (entry.getKey().equals(key)) { + continue; } - webView.setInputType(mode); + pm.setComponentEnabledSetting( + new ComponentName(packageName, packageName + "." + entry.getValue()), + PackageManager.COMPONENT_ENABLED_STATE_DISABLED, + PackageManager.DONT_KILL_APP + ); + } + callback.success(); + } catch (Exception e) { + callback.error(e.toString()); + } + } + + private void extractAsset( + String assetName, + String destinationPath, + CallbackContext callback + ) { + try ( + InputStream in = context.getAssets().open(assetName); + OutputStream out = new FileOutputStream(destinationPath) + ) { + byte[] buffer = new byte[8192]; + int length; + while ((length = in.read(buffer)) != -1) { + out.write(buffer, 0, length); + } + out.flush(); + callback.success(); + } catch (IOException e) { + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + callback.error(sw.toString()); } -} \ No newline at end of file + } +} diff --git a/src/plugins/system/plugin.xml b/src/plugins/system/plugin.xml index 2ddfb25a1b..8999352033 100644 --- a/src/plugins/system/plugin.xml +++ b/src/plugins/system/plugin.xml @@ -17,6 +17,10 @@ + + + + @@ -41,5 +45,7 @@ + + - \ No newline at end of file + diff --git a/src/plugins/system/readme.md b/src/plugins/system/readme.md deleted file mode 100644 index b0cca56d24..0000000000 --- a/src/plugins/system/readme.md +++ /dev/null @@ -1,11 +0,0 @@ -# Util plugin for cordova apps - -Using this plugin, cordova apps can: - -- Enable/disable full screen -- Share file -- Get webview information -- Send email -- Clear cache - -## Installation diff --git a/src/plugins/system/system.d.ts b/src/plugins/system/system.d.ts index 05b1a98882..ed15e281e1 100644 --- a/src/plugins/system/system.d.ts +++ b/src/plugins/system/system.d.ts @@ -19,7 +19,16 @@ interface ShortCut { data: string; } +interface FileShortcut { + id: string; + label: string; + description?: string; + icon?: string; + uri: string; +} + interface Intent { + uris?: string[]; action: string; data: string; type: string; @@ -29,10 +38,40 @@ interface Intent { }; } +interface RewardStatus { + adFreeUntil: number; + lastExpiredRewardUntil: number; + isActive: boolean; + remainingMs: number; + redemptionsToday: number; + remainingRedemptions: number; + maxRedemptionsPerDay: number; + maxActivePassMs: number; + hasPendingExpiryNotice: boolean; + expiryNoticePendingUntil: number; + canRedeem: boolean; + redeemDisabledReason: string; + grantedDurationMs?: number; + appliedDurationMs?: number; + offerId?: string; +} + type FileAction = 'VIEW' | 'EDIT' | 'SEND' | 'RUN'; type OnFail = (err: string) => void; type OnSuccessBool = (res: boolean) => void; +interface HttpStreamOptions { + method?: string; + headers?: Record; + body?: string; + bodyIsBase64?: boolean; + followRedirects?: boolean; + connectTimeout?: number; + readTimeout?: number; + chunkSize?: number; + signal?: AbortSignal; +} + interface System { /** * Get information about current webview @@ -131,6 +170,18 @@ interface System { * @param onFail */ pinShortcut(id: string, onSuccess: OnSuccessBool, onFail: OnFail): void; + + /** + * Pin a shortcut for a specific file to the home screen + * @param shortcut Shortcut configuration + * @param onSuccess + * @param onFail + */ + pinFileShortcut( + shortcut: FileShortcut, + onSuccess: OnSuccessBool, + onFail: OnFail, + ): void; /** * Gets android version * @param onSuccess @@ -188,19 +239,20 @@ interface System { */ openInBrowser(src: string): void; /** - * Launches and app - * @param app the package name of the app - * @param className the full class name of the activity - * @param data Data to pass to the app - * @param onSuccess - * @param onFail + * Launch an Android application activity. + * + * @param app Package name of the application (e.g. `com.example.app`) + * @param className Fully qualified activity class name (e.g. `com.example.app.MainActivity`) + * @param extras Optional key-value pairs passed as Android Intent extras + * @param onSuccess Called when the activity launches successfully + * @param onFail Called if launching the activity fails */ launchApp( app: string, className: string, - data: string, - onSuccess: OnSuccessBool, - onFail: OnFail, + extras?: Record, + onSuccess?: OnSuccessBool, + onFail?: OnFail, ): void; /** @@ -235,6 +287,49 @@ interface System { * @param onFail */ getCordovaIntent(onSuccess: (intent: Intent) => void, onFail: OnFail): void; + getRewardStatus( + onSuccess: (status: RewardStatus | string) => void, + onFail: OnFail, + ): void; + redeemReward( + offerId: string, + onSuccess: (status: RewardStatus | string) => void, + onFail: OnFail, + ): void; + /** + * Enable/disable native WebView long-press context behavior. + * Use this when rendering a custom editor context menu. + * @param disabled + * @param onSuccess + * @param onFail + */ + setNativeContextMenuDisabled( + disabled: boolean, + onSuccess?: () => void, + onFail?: OnFail, + ): void; + /** + * Perform an HTTP request and stream the response body to JavaScript. + * + * The response body is exposed as a WHATWG `ReadableStream` of `Uint8Array` + * chunks. The native layer does not buffer the whole response and performs + * no SSE/provider specific parsing. A 4xx/5xx status is a normal response; + * only transport failures reject the promise. Cancelling the returned + * stream's reader (or aborting `options.signal`) cancels the underlying + * native HTTP request. + * + * @param url Request URL + * @param options Request options + * @returns A `Response` whose `body` is a `ReadableStream` of `Uint8Array` chunks + */ + httpStream(url: string, options?: HttpStreamOptions): Promise; + /* + * Change the app icon at runtime. + * @param iconName Icon id, e.g. "midnight_circuit", or "default" to restore the original icon + * @param onSuccess + * @param onFail + */ + setAppIcon(iconName: string, onSuccess: OnSuccessBool, onFail: OnFail): void; } interface Window{ diff --git a/src/plugins/system/www/plugin.js b/src/plugins/system/www/plugin.js index 7f02d67be2..e10bc20062 100644 --- a/src/plugins/system/www/plugin.js +++ b/src/plugins/system/www/plugin.js @@ -21,6 +21,22 @@ module.exports = { writeText: function (path, content, success, error) { cordova.exec(success, error, 'System', 'writeText', [path, content]); }, + deleteFile: function (path, success, error) { + cordova.exec(success, error, 'System', 'deleteFile', [path]); + }, + setExec: function (path, executable, success, error) { + cordova.exec(success, error, 'System', 'setExec', [path, String(executable)]); + }, + getInstaller: function (success, error) { + cordova.exec(success, error, 'System', 'getInstaller', []); + }, + shareText: function (text, success, error) { + cordova.exec(success, error, 'System', 'shareText', [text]); + }, + getNativeLibraryPath: function (success, error) { + cordova.exec(success, error, 'System', 'getNativeLibraryPath', []); + }, + getNativeLibraryPath: function (success, error) { cordova.exec(success, error, 'System', 'getNativeLibraryPath', []); @@ -29,6 +45,15 @@ module.exports = { getFilesDir: function (success, error) { cordova.exec(success, error, 'System', 'getFilesDir', []); }, + getRewardStatus: function (success, error) { + cordova.exec(success, error, 'System', 'getRewardStatus', []); + }, + redeemReward: function (offerId, success, error) { + cordova.exec(success, error, 'System', 'redeemReward', [offerId]); + }, + extractAsset: function (assetName, destinationPath, success, error) { + cordova.exec(success, error, 'System', 'extractAsset', [assetName, destinationPath]); + }, getParentPath: function (path, success, error) { cordova.exec(success, error, 'System', 'getParentPath', [path]); @@ -89,6 +114,9 @@ module.exports = { pinShortcut: function (id, onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'System', 'pin-shortcut', [id]); }, + pinFileShortcut: function (shortcut, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'System', 'pin-file-shortcut', [shortcut]); + }, manageAllFiles: function (onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'System', 'manage-all-files', []); }, @@ -110,8 +138,30 @@ module.exports = { openInBrowser: function (src) { cordova.exec(null, null, 'System', 'open-in-browser', [src]); }, - launchApp: function (app, className, data, onSuccess, onFail) { - cordova.exec(onSuccess, onFail, 'System', 'launch-app', [app, className, data]); + /** + * Launch an Android application activity. + * + * @param {string} app - Package name of the application (e.g. `com.example.app`). + * @param {string} className - Fully qualified activity class name (e.g. `com.example.app.MainActivity`). + * @param {Object} [extras] - Optional key-value pairs passed as Intent extras. + * @param {(message: string) => void} [onSuccess] - Callback invoked when the activity launches successfully. + * @param {(error: any) => void} [onFail] - Callback invoked if launching the activity fails. + * + * @example + * System.launchApp( + * "com.example.app", + * "com.example.app.MainActivity", + * { + * user: "example", + * age: 20, + * premium: true + * }, + * (msg) => console.log(msg), + * (err) => console.error(err) + * ); + */ + launchApp: function (app, className, extras, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'System', 'launch-app', [app, className, extras]); }, inAppBrowser: function (url, title, showButtons, disableCache) { var myInAppBrowser = { @@ -120,22 +170,48 @@ module.exports = { }; cordova.exec(function (data) { - try { - var dataTag = data.split(':')[0]; - var dataUrl = data.split(':')[1]; - if (dataTag === 'onOpenExternalBrowser') { + if (typeof data !== 'string') { + console.warn('System.inAppBrowser: invalid callback payload', data); + return; + } + var separatorIndex = data.indexOf(':'); + if (separatorIndex < 0) { + console.warn('System.inAppBrowser: malformed callback payload', data); + return; + } + var dataTag = data.slice(0, separatorIndex); + var dataUrl = data.slice(separatorIndex + 1); + if (dataTag === 'onOpenExternalBrowser') { + if (typeof myInAppBrowser.onOpenExternalBrowser === 'function') { myInAppBrowser.onOpenExternalBrowser(dataUrl); + } else { + console.warn('System.inAppBrowser: onOpenExternalBrowser handler is not set'); } - } catch (error) { } + } }, function (err) { - try { - onError(err); - } catch (error) { } + if (typeof myInAppBrowser.onError === 'function') { + myInAppBrowser.onError(err); + return; + } + console.warn('System.inAppBrowser error callback not handled', err); }, 'System', 'in-app-browser', [url, title, !!showButtons, disableCache]); return myInAppBrowser; }, setUiTheme: function (systemBarColor, theme, onSuccess, onFail) { - cordova.exec(onSuccess, onFail, 'System', 'set-ui-theme', [systemBarColor, theme]); + const color = systemBarColor.toLowerCase(); + + if (color === '#ffffff' || color === '#ffffffff') { + systemBarColor = '#fffffe'; + } + + cordova.exec((out) => { + window.statusbar.setBackgroundColor(systemBarColor); + + if (typeof onSuccess === "function") { + onSuccess(out); + } + + }, onFail, 'System', 'set-ui-theme', [systemBarColor, theme]); }, setIntentHandler: function (handler, onerror) { cordova.exec(handler, onerror, 'System', 'set-intent-handler', []); @@ -146,7 +222,290 @@ module.exports = { setInputType: function (type, onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'System', 'set-input-type', [type]); }, + setNativeContextMenuDisabled: function (disabled, onSuccess, onFail) { + cordova.exec( + onSuccess, + onFail, + 'System', + 'set-native-context-menu-disabled', + [String(!!disabled)] + ); + }, + /** + * Change the app icon at runtime. + * @param iconName Icon id, e.g. "midnight_circuit", or "default" to restore the original icon + * @param onSuccess + * @param onFail + */ + setAppIcon: function (iconName, onSuccess, onFail) { + cordova.exec(onSuccess, onFail, 'System', 'set-app-icon', [iconName]); + }, getGlobalSetting: function (key, onSuccess, onFail) { cordova.exec(onSuccess, onFail, 'System', 'get-global-setting', [key]); + }, + /** + * Compare file content with provided text in a background thread. + * @param {string} fileUri - The URI of the file to read + * @param {string} encoding - The character encoding to use + * @param {string} currentText - The text to compare against + * @returns {Promise} - Resolves to true if content differs, false if same + */ + compareFileText: function (fileUri, encoding, currentText) { + return new Promise((resolve, reject) => { + cordova.exec( + function(result) { + resolve(result === 1); + }, + reject, + 'System', + 'compare-file-text', + [fileUri, encoding, currentText] + ); + }); + }, + /** + * Compare two text strings in a background thread. + * @param {string} text1 - First text to compare + * @param {string} text2 - Second text to compare + * @returns {Promise} - Resolves to true if texts differ, false if same + */ + compareTexts: function (text1, text2) { + return new Promise((resolve, reject) => { + cordova.exec( + function(result) { + resolve(result === 1); + }, + reject, + 'System', + 'compare-texts', + [text1, text2] + ); + }); + }, + /** + * Make an HTTP request and receive the response body as a WHATWG + * `ReadableStream` of `Uint8Array` chunks, as bytes arrive from the server. + * + * The native layer does not buffer the whole response and performs no SSE / + * provider specific parsing; it simply forwards raw byte chunks. Chunk + * boundaries are arbitrary and may split multi-byte UTF-8 characters or SSE + * frames. The consumer is responsible for decoding / parsing the stream. + * + * @param {string} url - Request URL + * @param {Object} [options] + * @param {string} [options.method="GET"] - HTTP method + * @param {Object} [options.headers] - Request headers + * @param {string} [options.body] - Request body. Sent as UTF-8 text unless + * `bodyIsBase64` is set, in which case it is decoded from base64. + * @param {boolean} [options.bodyIsBase64=false] + * @param {boolean} [options.followRedirects=true] + * @param {number} [options.connectTimeout=30000] - Connect timeout in ms + * @param {number} [options.readTimeout=0] - Read timeout in ms (0 = none) + * @param {number} [options.chunkSize=32768] - Requested native chunk size in bytes + * @param {AbortSignal} [options.signal] - When aborted, the underlying native + * request is cancelled. If the headers have not yet arrived the returned + * promise rejects with an `AbortError`; otherwise the response stream is + * errored with an `AbortError`. + * @returns {Promise} Resolves with a `Response` whose `body` is a + * `ReadableStream` delivering `Uint8Array` chunks. A 4xx/5xx HTTP status + * is a normal response (not a rejected promise); only transport failures + * reject. Cancelling the returned stream's reader (or aborting + * `options.signal`) cancels the underlying native HTTP request. + */ + httpStream: function (url, options) { + options = options || {}; + var signal = options.signal || null; + + var nativeOptions = {}; + for (var key in options) { + if (key !== 'signal') nativeOptions[key] = options[key]; + } + + return new Promise(function (resolve, reject) { + var requestId = "httpStream_" + Date.now() + "_" + Math.random().toString(36).slice(2, 10); + var HIGH_WATER_MARK = 65536; + var controller = null; + var headersReceived = false; + var started = false; + var cancelSent = false; + var terminal = false; + var receivedBytes = 0; + var ackedBytes = 0; + + function sendCancel() { + if (cancelSent) return; + cancelSent = true; + cordova.exec(null, null, 'System', 'http-stream-cancel', [requestId]); + } + + function teardownSignal() { + if (signal) { + try { + signal.removeEventListener('abort', onAbort); + } catch (e) {} + } + } + + function finish() { + terminal = true; + teardownSignal(); + } + + function fail(err) { + if (terminal) return; + finish(); + if (headersReceived && controller) { + controller.error(err); + } else { + reject(err); + } + } + + function onAbort() { + if (terminal) return; + if (started) sendCancel(); + var err = new Error('The http stream was aborted'); + err.name = 'AbortError'; + fail(err); + } + + function ackConsumed() { + if (terminal || !controller) return; + var desired = controller.desiredSize; + if (desired === null) return; + var buffered = Math.max(0, HIGH_WATER_MARK - desired); + var consumed = receivedBytes - buffered; + var delta = consumed - ackedBytes; + if (delta > 0) { + ackedBytes = consumed; + cordova.exec(null, null, 'System', 'http-stream-ack', [requestId, delta]); + } + } + + function headersFromPairs(pairs) { + var h = new Headers(); + if (!pairs) return h; + if (!Array.isArray(pairs)) { + for (var name in pairs) { + try { + h.append(name, pairs[name]); + } catch (e) {} + } + return h; + } + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + if (!pair || pair.length < 2) continue; + try { + h.append(pair[0], pair[1]); + } catch (e) {} + } + return h; + } + + var stream = new ReadableStream({ + start: function (c) { + controller = c; + }, + pull: function () { + ackConsumed(); + }, + cancel: function () { + finish(); + if (started) sendCancel(); + } + }, { + highWaterMark: HIGH_WATER_MARK, + size: function (chunk) { + return chunk.byteLength; + } + }); + + if (signal) { + if (signal.aborted) { + onAbort(); + } else { + signal.addEventListener('abort', onAbort); + } + } + if (terminal) return; + + started = true; + cordova.exec( + function (event) { + if (!event || typeof event !== 'object' || terminal) return; + + switch (event.type) { + case 'headers': { + headersReceived = true; + var status = event.status; + var cannotHaveBody = status === 204 || status === 205 || status === 304; + var headers = headersFromPairs(event.headers || []); + var response; + if (cannotHaveBody) { + response = new Response(null, { + status: status, + statusText: event.statusText || '', + headers: headers + }); + } else { + response = new Response(stream, { + status: status, + statusText: event.statusText || '', + headers: headers + }); + } + if (event.url) { + Object.defineProperty(response, 'url', { value: event.url, configurable: true }); + } + resolve(response); + break; + } + case 'data': { + if (controller && event.chunk) { + var bytes = event.b64 + ? base64ToBytes(event.chunk) + : latin1ToBytes(event.chunk); + controller.enqueue(bytes); + receivedBytes += bytes.byteLength; + } + break; + } + case 'complete': { + finish(); + if (controller) controller.close(); + break; + } + case 'error': { + fail(new Error(event.message || 'Stream failed')); + break; + } + } + }, + function (err) { + fail(typeof err === 'string' ? new Error(err) : err); + }, + 'System', + 'http-stream-start', + [requestId, url, nativeOptions] + ); + }); + } +}; + +function base64ToBytes(base64) { + var binary = atob(base64); + var bytes = new Uint8Array(binary.length); + for (var i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes; +} + +function latin1ToBytes(text) { + var bytes = new Uint8Array(text.length); + for (var i = 0; i < text.length; i++) { + bytes[i] = text.charCodeAt(i); } -}; \ No newline at end of file + return bytes; +} diff --git a/src/plugins/terminal/plugin.xml b/src/plugins/terminal/plugin.xml index f6e159ccd2..35cc968ebf 100644 --- a/src/plugins/terminal/plugin.xml +++ b/src/plugins/terminal/plugin.xml @@ -12,22 +12,35 @@ + + + + + + + + + + + + + + - + android:exported="false" /> @@ -57,6 +70,9 @@ - + + + + \ No newline at end of file diff --git a/src/plugins/terminal/scripts/init-alpine.sh b/src/plugins/terminal/scripts/init-alpine.sh index 38bcfe2c94..130ae9588c 100644 --- a/src/plugins/terminal/scripts/init-alpine.sh +++ b/src/plugins/terminal/scripts/init-alpine.sh @@ -1,13 +1,39 @@ -set -e # Exit immediately on failure - - export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/share/bin:/usr/share/sbin:/usr/local/bin:/usr/local/sbin:/system/bin:/system/xbin:$PREFIX/local/bin export PS1="\[\e[38;5;46m\]\u\[\033[39m\]@localhost \[\033[39m\]\w \[\033[0m\]\\$ " -export HOME=/home +export HOME=/public export TERM=xterm-256color +INSTALLING=false +FAILSAFE=false + +# Parse internal flags +while [ $# -gt 0 ]; do + case "$1" in + --installing) + INSTALLING=true + shift + ;; + --failsafe) + FAILSAFE=true + shift + ;; + --) + shift + break + ;; + *) + break + ;; + esac +done -required_packages="bash" +# If a command was supplied, execute it and exit +# without it Executor will break +if [ "$INSTALLING" != true ] && [ $# -gt 0 ] && [ "${1#--}" = "$1" ]; then + exec "$@" +fi + +required_packages="bash command-not-found tzdata wget" missing_packages="" for pkg in $required_packages; do @@ -33,14 +59,29 @@ if [ ! -f /linkerconfig/ld.config.txt ]; then fi -if [ "$1" = "--installing" ]; then +if [ "$INSTALLING" = true ]; then + echo "Configuring timezone..." + + if [ -n "$ANDROID_TZ" ] && [ -f "/usr/share/zoneinfo/$ANDROID_TZ" ]; then + ln -sf "/usr/share/zoneinfo/$ANDROID_TZ" /etc/localtime + echo "$ANDROID_TZ" > /etc/timezone + echo "Timezone set to: $ANDROID_TZ" + else + echo "Failed to detect timezone" + fi + mkdir -p "$PREFIX/.configured" + + if [ ! -f "$HOME/.bashrc" ]; then + touch "$HOME/.bashrc" && chmod 644 "$HOME/.bashrc" + fi + echo "Installation completed." exit 0 fi -if [ "$#" -eq 0 ]; then + echo "$$" > "$PREFIX/pid" chmod +x "$PREFIX/axs" @@ -58,33 +99,259 @@ Working with packages: EOF fi - # Create initrc if it doesn't exist - if [ ! -e "$PREFIX/alpine/initrc" ]; then - cat < "$PREFIX/alpine/initrc" -if [[ -f ~/.bashrc ]]; then - source ~/.bashrc + # Create acode CLI tool + if [ ! -e "$PREFIX/alpine/usr/local/bin/acode" ]; then + mkdir -p "$PREFIX/alpine/usr/local/bin" + cat <<'ACODE_CLI' > "$PREFIX/alpine/usr/local/bin/acode" +#!/bin/bash +# acode - Open files/folders in Acode editor +# Uses OSC escape sequences to communicate with the Acode terminal + +usage() { + echo "Usage: acode [file/folder...]" + echo "" + echo "Open files or folders in Acode editor." + echo "" + echo "Examples:" + echo " acode file.txt # Open a file" + echo " acode . # Open current folder" + echo " acode ~/project # Open a folder" + echo " acode -h, --help # Show this help" +} + +get_abs_path() { + local path="$1" + local abs_path="" + + if command -v realpath >/dev/null 2>&1; then + abs_path=$(realpath -- "$path" 2>/dev/null) + fi + + if [[ -z "$abs_path" ]]; then + if [[ -d "$path" ]]; then + abs_path=$(cd -- "$path" 2>/dev/null && pwd -P) + elif [[ -e "$path" ]]; then + local dir_name file_name + dir_name=$(dirname -- "$path") + file_name=$(basename -- "$path") + abs_path="$(cd -- "$dir_name" 2>/dev/null && pwd -P)/$file_name" + elif [[ "$path" == /* ]]; then + abs_path="$path" + else + abs_path="$PWD/$path" + fi + fi + + echo "$abs_path" +} + +open_in_acode() { + local path=$(get_abs_path "$1") + local type="file" + [[ -d "$path" ]] && type="folder" + + # Send OSC 7777 escape sequence: \e]7777;cmd;type;path\a + # The terminal component will intercept and handle this + printf '\e]7777;open;%s;%s\a' "$type" "$path" +} + +if [[ $# -eq 0 ]]; then + open_in_acode "." + exit 0 fi -if [[ -f /etc/bash/bashrc ]]; then - source /etc/bash/bashrc +for arg in "$@"; do + case "$arg" in + -h|--help) + usage + exit 0 + ;; + *) + if [[ -e "$arg" ]]; then + open_in_acode "$arg" + else + echo "Error: '$arg' does not exist" >&2 + exit 1 + fi + ;; + esac +done +ACODE_CLI + chmod +x "$PREFIX/alpine/usr/local/bin/acode" + fi + + # Create initrc if it doesn't exist + #initrc runs in bash so we can use bash features +if [ ! -e "$PREFIX/alpine/initrc" ]; then + cat <<'EOF' > "$PREFIX/alpine/initrc" +# Source rc files if they exist + +if [ -f "/etc/profile" ]; then + source "/etc/profile" fi -export PATH=\$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/usr/share/bin:/usr/share/sbin:/usr/local/bin:/usr/local/sbin -export HOME=/home +# Environment setup +export PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/usr/share/bin:/usr/share/sbin:/usr/local/bin:/usr/local/sbin + +export HOME=/public export TERM=xterm-256color -export SHELL=\$(command -v bash) +SHELL=/bin/bash export PIP_BREAK_SYSTEM_PACKAGES=1 +# Default prompt with fish-style path shortening (~/p/s/components) +# To use custom prompts (Starship, Oh My Posh, etc.), just init them in ~/.bashrc: +# eval "$(starship init bash)" +_shorten_path() { + local path="$PWD" + + if [[ "$HOME" != "/" && "$path" == "$HOME" ]]; then + echo "~" + return + elif [[ "$HOME" != "/" && "$path" == "$HOME/"* ]]; then + path="~${path#$HOME}" + fi + + [[ "$path" == "~" ]] && echo "~" && return + + local parts result="" + IFS='/' read -ra parts <<< "$path" + local len=${#parts[@]} + + for ((i=0; i/dev/null)" + else + cmd_path="$(command -v "$cmd" 2>/dev/null)" + + # Resolve symlinks/relative paths + if [[ -n "$cmd_path" ]]; then + cmd_path="$(realpath "$cmd_path" 2>/dev/null)" + fi fi - echo 'export PS1="\[\e[38;5;46m\]\u\[\e[0m\]@localhost \[\e[0m\]\w \[\e[0m\]\\$ "' >> $PREFIX/alpine/initrc - chmod +x "$PREFIX/alpine/initrc" - "$PREFIX/axs" -c "bash --rcfile /initrc -i" + [[ -z "$cmd_path" ]] && return + [[ ! -f "$cmd_path" ]] && return + + if [[ "$cmd_path" == /storage/* ]] || \ + [[ "$cmd_path" == /sdcard/* ]]; then + echo -e "\e[1;31m[!] ATTENTION REQUIRED\e[0m + +\e[1;31mThe binary is located in:\e[0m + \e[36m$cmd_path\e[0m + +\e[1;31mBinaries cannot be executed reliably from /sdcard or /storage.\e[0m +These locations are backed by Android's external storage layer and do not support normal Linux executable permissions. + +Move your project or binary to a directory under: + \e[1;32m/home/\e[0m + +Example: + \e[1;32mmv myproject ~/myproject\e[0m + \e[1;32mcd ~/myproject\e[0m + +Then run the binary again. +" >&2 + fi +} + +_acode_preexec() { + # Skip commands executed by the trap itself + [[ "$BASH_COMMAND" == trap* ]] && return + + local cmd="${BASH_COMMAND%% *}" + check_binary_execution "$cmd" +} + +# Preserve any existing DEBUG trap and append our handler instead of overwriting it. +# This avoids clobbering user-installed preexec hooks (starship, fzf, bash-preexec, etc.). +__acode_existing_debug_trap="$(trap -p DEBUG 2>/dev/null)" +if [[ -n "${__acode_existing_debug_trap}" ]]; then + __acode_existing_cmd="$(printf "%s" "${__acode_existing_debug_trap}" | sed -E "s/.*'((.*)?)'.*/\1/")" else - exec "$@" -fi \ No newline at end of file + __acode_existing_cmd="" +fi + +# Only add our handler if it's not already present +if [[ "${__acode_existing_cmd}" != *"_acode_preexec"* ]]; then + if [[ -n "${__acode_existing_cmd}" ]]; then + trap "${__acode_existing_cmd}; _acode_preexec" DEBUG + else + trap '_acode_preexec' DEBUG + fi +fi +unset __acode_existing_debug_trap __acode_existing_cmd + +# Command-not-found handler +command_not_found_handle() { + cmd="$1" + pkg="" + green="\e[1;32m" + reset="\e[0m" + + pkg=$(apk search -x "cmd:$cmd" 2>/dev/null | awk -F'-[0-9]' '{print $1}' | head -n 1) + + if [ -n "$pkg" ]; then + echo -e "The program '$cmd' is not installed.\nInstall it by executing:\n ${green}apk add $pkg${reset}" >&2 + else + echo "The program '$cmd' is not installed and no package provides it." >&2 + fi + + return 127 +} + +# Replicate behaviour of termux (non standard) +alias clear='reset' + +# Source user configs AFTER defaults (so user can override everything) +if [ -f /etc/bash/bashrc ]; then + source /etc/bash/bashrc +fi + +if [ -f "$HOME/.bashrc" ]; then + source "$HOME/.bashrc" +fi + +EOF +fi + +# Add PS1 only if not already present +if ! grep -q 'PS1=' "$PREFIX/alpine/initrc"; then + # Smart path shortening (fish-style: ~/p/s/components) + echo 'PS1="\[\033[1;32m\]\u\[\033[0m\]@localhost \[\033[1;34m\]\$_PS1_PATH\[\033[0m\] \[\$([ \$_PS1_EXIT -ne 0 ] && echo \"\033[31m\")\]\$\[\033[0m\] "' >> "$PREFIX/alpine/initrc" + # Simple prompt (uncomment below and comment above if you prefer full paths) + # echo 'PS1="\[\033[1;32m\]\u\[\033[0m\]@localhost \[\033[1;34m\]\w\[\033[0m\] \$ "' >> "$PREFIX/alpine/initrc" +fi + + +chmod +x "$PREFIX/alpine/initrc" + +if [ "$FAILSAFE" != true ]; then + #everytime a terminal is started initrc will run + "$PREFIX/axs" -c "bash --rcfile /initrc -i" +fi diff --git a/src/plugins/terminal/scripts/init-sandbox.sh b/src/plugins/terminal/scripts/init-sandbox.sh index 3f491f47d9..1da53a95b4 100644 --- a/src/plugins/terminal/scripts/init-sandbox.sh +++ b/src/plugins/terminal/scripts/init-sandbox.sh @@ -39,16 +39,19 @@ fi ARGS="--kill-on-exit" -for system_mnt in /apex /odm /product /system /system_ext /vendor \ - /linkerconfig/ld.config.txt \ - /linkerconfig/com.android.art/ld.config.txt \ - /plat_property_contexts /property_contexts; do + + +for system_mnt in /apex /odm /product /system /system_ext /vendor /linkerconfig/ld.config.txt /linkerconfig/com.android.art/ld.config.txt /plat_property_contexts /property_contexts; do if [ -e "$system_mnt" ]; then system_mnt=$(realpath "$system_mnt") ARGS="$ARGS -b ${system_mnt}" fi done + + + + unset system_mnt ARGS="$ARGS -b /sdcard" @@ -59,23 +62,58 @@ ARGS="$ARGS -b /dev/urandom:/dev/random" ARGS="$ARGS -b /proc" ARGS="$ARGS -b /sys" ARGS="$ARGS -b $PREFIX" +ARGS="$ARGS -b $NATIVE_DIR" ARGS="$ARGS -b $PREFIX/public:/public" +ARGS="$ARGS -b $PREFIX/public:/home" +ARGS="$ARGS -b $PREFIX/public:/root" ARGS="$ARGS -b $PREFIX/alpine/tmp:/dev/shm" -if [ -e "/proc/self/fd" ]; then +# PRoot canonicalizes every -b host path with realpath(3). The magic links +# under /proc/self/fd only resolve when the descriptor points at a real file: +# for pipes, sockets, anon inodes or memfds the link target is not a path +# ("pipe:[123]"), so realpath(3) fails with ENOENT, proot drops the binding and +# prints `can't sanitize binding "/proc/self/fd/N"`. `[ -e ]` follows the magic +# link to the underlying inode and therefore returns true for those descriptors, +# which is why it does not filter them out. Test the link target the same way +# realpath(3) does instead. +# +# Probe through this shell's own pid ($$), not /proc/self: readlink(1) runs as a +# child process, so for fd 2 its /proc/self/fd/2 is the /dev/null of the +# `2>/dev/null` redirect below rather than the stderr proot inherits. $$ is +# unchanged by the exec at the end of this script, so it always names the +# process proot will run as. +SELF_PID=$$ + +can_bind() { + # Directories (e.g. /proc/self/fd) are canonicalizable as-is. + if [ -d "$1" ]; then + return 0 + fi + + # A /proc/self/fd/N magic link is only canonicalizable when it resolves to + # an existing absolute path; "pipe:[N]", "socket:[N]" and friends are not. + target=$(readlink "$1" 2>/dev/null) || return 1 + + case "$target" in + /*) [ -e "$target" ] ;; + *) return 1 ;; + esac +} + +if can_bind "/proc/$SELF_PID/fd"; then ARGS="$ARGS -b /proc/self/fd:/dev/fd" fi -if [ -e "/proc/self/fd/0" ]; then +if can_bind "/proc/$SELF_PID/fd/0"; then ARGS="$ARGS -b /proc/self/fd/0:/dev/stdin" fi -if [ -e "/proc/self/fd/1" ]; then +if can_bind "/proc/$SELF_PID/fd/1"; then ARGS="$ARGS -b /proc/self/fd/1:/dev/stdout" fi -if [ -e "/proc/self/fd/2" ]; then +if can_bind "/proc/$SELF_PID/fd/2"; then ARGS="$ARGS -b /proc/self/fd/2:/dev/stderr" fi @@ -87,4 +125,30 @@ ARGS="$ARGS --sysvipc" ARGS="$ARGS -L" -$PROOT $ARGS /bin/sh $PREFIX/init-alpine.sh "$@" +FAILSAFE=false +INSTALLING=false + +for arg in "$@"; do + case "$arg" in + --failsafe) + FAILSAFE=true + ;; + --installing) + INSTALLING=true + ;; + esac +done + +if [ "$FAILSAFE" = true ] && [ "$INSTALLING" != true ]; then + echo "$$" > "$PREFIX/pid" + + LINKER="/system/bin/linker64" + ARCH="$(uname -m)" + if [ "$ARCH" != "aarch64" ] && [ "$ARCH" != "x86_64" ]; then + LINKER="/system/bin/linker" + fi + + exec "$LINKER" "$PREFIX/axs" -c "sh" +else + exec "$PROOT" $ARGS /bin/sh "$PREFIX/init-alpine.sh" "$@" +fi \ No newline at end of file diff --git a/src/plugins/terminal/scripts/rm-wrapper.sh b/src/plugins/terminal/scripts/rm-wrapper.sh new file mode 100644 index 0000000000..07d195fdc7 --- /dev/null +++ b/src/plugins/terminal/scripts/rm-wrapper.sh @@ -0,0 +1,25 @@ +#!/bin/sh + +unlink_recursive() { + path="$1" + + # Try to recurse into it as a directory first + for entry in "$path"/* "$path"/.[!.]* "$path"/..?*; do + case "$entry" in + *'*'*|*'?'*) continue ;; + esac + unlink_recursive "$entry" + done 2>/dev/null + + unlink "$path" 2>/dev/null || : +} + +for target in "$@"; do + unlink_recursive "$target" +done + +# Run busybox rm, capture stderr, and filter out the "No such file or directory" message +err="$(busybox rm "$@" 2>&1 >/dev/null)" + +# Print only real errors +printf "%s\n" "$err" | grep -v "No such file or directory" \ No newline at end of file diff --git a/src/plugins/terminal/src/android/AlpineDocumentProvider.java b/src/plugins/terminal/src/android/AlpineDocumentProvider.java index 38fdc67127..97a4dd50ab 100644 --- a/src/plugins/terminal/src/android/AlpineDocumentProvider.java +++ b/src/plugins/terminal/src/android/AlpineDocumentProvider.java @@ -20,6 +20,7 @@ import java.util.LinkedList; import java.util.Locale; import com.foxdebug.acode.R; +import com.foxdebug.acode.rk.exec.terminal.*; public class AlpineDocumentProvider extends DocumentsProvider { @@ -60,7 +61,7 @@ public Cursor queryRoots(String[] projection) { MatrixCursor result = new MatrixCursor( projection != null ? projection : DEFAULT_ROOT_PROJECTION ); - String applicationName = "Acode"; + String applicationName = getApplicationLabel(); MatrixCursor.RowBuilder row = result.newRow(); row.add(DocumentsContract.Root.COLUMN_ROOT_ID, getDocIdForFile(BASE_DIR)); @@ -75,7 +76,7 @@ public Cursor queryRoots(String[] projection) { row.add(DocumentsContract.Root.COLUMN_TITLE, applicationName); row.add(DocumentsContract.Root.COLUMN_MIME_TYPES, ALL_MIME_TYPES); row.add(DocumentsContract.Root.COLUMN_AVAILABLE_BYTES, BASE_DIR.getFreeSpace()); - row.add(DocumentsContract.Root.COLUMN_ICON, R.mipmap.ic_launcher); + row.add(DocumentsContract.Root.COLUMN_ICON, resolveLauncherIcon()); return result; } @@ -172,6 +173,33 @@ public void deleteDocument(String documentId) throws FileNotFoundException { } } + @Override + public String renameDocument(String documentId, String displayName) throws FileNotFoundException { + File file = getFileForDocId(documentId); + File parent = file.getParentFile(); + if (parent == null) { + throw new FileNotFoundException("Failed to rename root document with id " + documentId); + } + if (displayName == null || displayName.trim().isEmpty()) { + throw new FileNotFoundException("Failed to rename document with id " + documentId); + } + if (displayName.equals(file.getName())) { + return documentId; + } + if (displayName.contains(File.separator)) { + throw new FileNotFoundException("Invalid display name for rename: " + displayName); + } + + File target = new File(parent, displayName); + if (target.exists()) { + throw new FileNotFoundException("Target already exists: " + target.getAbsolutePath()); + } + if (!file.renameTo(target)) { + throw new FileNotFoundException("Failed to rename document with id " + documentId); + } + return getDocIdForFile(target); + } + @Override public String getDocumentType(String documentId) throws FileNotFoundException { File file = getFileForDocId(documentId); @@ -258,6 +286,7 @@ private void includeFile(MatrixCursor result, String docId, File file) throws Fi File parentFile = file.getParentFile(); if (parentFile != null && parentFile.canWrite()) { flags = flags | DocumentsContract.Document.FLAG_SUPPORTS_DELETE; + flags = flags | DocumentsContract.Document.FLAG_SUPPORTS_RENAME; } String displayName = file.getName(); @@ -336,4 +365,22 @@ private static String getMimeType(File file) { return "application/octet-stream"; } } -} \ No newline at end of file + private int resolveLauncherIcon() { + Context context = getContext(); + if (context == null) return android.R.mipmap.sym_def_app_icon; + int icon = context.getResources().getIdentifier("ic_launcher", "mipmap", context.getPackageName()); + return icon != 0 ? icon : android.R.mipmap.sym_def_app_icon; + } + + private String getApplicationLabel() { + Context context = getContext(); + if (context == null) return "Acode"; + PackageManager pm = context.getPackageManager(); + try { + CharSequence label = pm.getApplicationLabel(context.getApplicationInfo()); + return label != null ? label.toString() : "Acode"; + } catch (Exception ignored) { + return "Acode"; + } + } +} diff --git a/src/plugins/terminal/src/android/BackgroundExecutor.java b/src/plugins/terminal/src/android/BackgroundExecutor.java new file mode 100644 index 0000000000..3230473af2 --- /dev/null +++ b/src/plugins/terminal/src/android/BackgroundExecutor.java @@ -0,0 +1,240 @@ +package com.foxdebug.acode.rk.exec.terminal; + +import org.apache.cordova.*; +import org.json.*; +import java.io.*; +import java.util.*; +import java.util.concurrent.*; +import com.foxdebug.acode.rk.exec.terminal.*; + +public class BackgroundExecutor extends CordovaPlugin { + + private final Map processes = new ConcurrentHashMap<>(); + private final Map processInputs = new ConcurrentHashMap<>(); + private final Map processCallbacks = new ConcurrentHashMap<>(); + private final Map processDetails = new ConcurrentHashMap<>(); + private ProcessManager processManager; + + @Override + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); + this.processManager = new ProcessManager(cordova.getContext()); + } + + @Override + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + switch (action) { + case "start": + String pid = UUID.randomUUID().toString(); + startProcess(pid, args.getString(0), args.getString(1).equals("true"), callbackContext); + return true; + case "write": + writeToProcess(args.getString(0), args.getString(1), callbackContext); + return true; + case "stop": + stopProcess(args.getString(0), callbackContext); + return true; + case "exec": + exec(args.getString(0), args.getString(1).equals("true"), callbackContext); + return true; + case "isRunning": + isProcessRunning(args.getString(0), callbackContext); + return true; + case "listProcesses": + listProcesses(callbackContext); + return true; + case "listAllProcesses": + listAllProcesses(callbackContext); + return true; + case "killProcess": + killProcess(args.getInt(0), callbackContext); + return true; + case "loadLibrary": + loadLibrary(args.getString(0), callbackContext); + return true; + case "setProotDebug": + ProcessManager.prootDebug = args.getBoolean(0); + callbackContext.success("PRoot debug " + (ProcessManager.prootDebug ? "enabled" : "disabled")); + return true; + default: + callbackContext.error("Unknown action: " + action); + return false; + } + } + + private void exec(String cmd, boolean useAlpine, CallbackContext callbackContext) { + cordova.getThreadPool().execute(() -> { + try { + ProcessManager.ExecResult result = processManager.executeCommand(cmd, useAlpine); + + if (result.isSuccess()) { + callbackContext.success(result.stdout); + } else { + callbackContext.error(result.getErrorMessage()); + } + } catch (Exception e) { + callbackContext.error("Exception: " + e.getMessage()); + } + }); + } + + private void startProcess(String pid, String cmd, boolean useAlpine, CallbackContext callbackContext) { + cordova.getThreadPool().execute(() -> { + try { + ProcessBuilder builder = processManager.createProcessBuilder(cmd, useAlpine); + Process process = builder.start(); + + long pidVal = ProcessUtils.getPid(process); + processes.put(pid, process); + processInputs.put(pid, process.getOutputStream()); + processCallbacks.put(pid, callbackContext); + processDetails.put(pid, new ProcessDetails(cmd, useAlpine, pidVal)); + + sendPluginResult(callbackContext, pid, true); + + // Stream stdout + new Thread(() -> StreamHandler.streamOutput( + process.getInputStream(), + line -> sendPluginMessage(pid, "stdout:" + line) + )).start(); + + // Stream stderr + new Thread(() -> StreamHandler.streamOutput( + process.getErrorStream(), + line -> sendPluginMessage(pid, "stderr:" + line) + )).start(); + + int exitCode = process.waitFor(); + sendPluginMessage(pid, "exit:" + exitCode); + cleanup(pid); + } catch (Exception e) { + callbackContext.error("Failed to start process: " + e.getMessage()); + } + }); + } + + private void writeToProcess(String pid, String input, CallbackContext callbackContext) { + try { + OutputStream os = processInputs.get(pid); + if (os != null) { + StreamHandler.writeToStream(os, input); + callbackContext.success("Written to process"); + } else { + callbackContext.error("Process not found or closed"); + } + } catch (IOException e) { + callbackContext.error("Write error: " + e.getMessage()); + } + } + + private void stopProcess(String pid, CallbackContext callbackContext) { + Process process = processes.get(pid); + if (process != null) { + ProcessUtils.killProcessTree(process); + cleanup(pid); + callbackContext.success("Process terminated"); + } else { + callbackContext.error("No such process"); + } + } + + private void isProcessRunning(String pid, CallbackContext callbackContext) { + Process process = processes.get(pid); + + if (process != null) { + String status = ProcessUtils.isAlive(process) ? "running" : "exited"; + if (status.equals("exited")) cleanup(pid); + callbackContext.success(status); + } else { + callbackContext.success("not_found"); + } + } + + private void listProcesses(CallbackContext callbackContext) { + JSONArray result = new JSONArray(); + + for (Map.Entry entry : processes.entrySet()) { + String id = entry.getKey(); + Process process = entry.getValue(); + if (!ProcessUtils.isAlive(process)) continue; + + ProcessDetails details = processDetails.get(id); + if (details == null) continue; + + try { + JSONObject item = new JSONObject(); + item.put("id", id); + item.put("command", details.command); + item.put("alpine", details.alpine); + item.put("startedAt", details.startedAt); + item.put("pid", details.pid); + result.put(item); + } catch (JSONException ignored) { + // These values are generated internally and should always serialize. + } + } + + callbackContext.success(result); + } + + private void loadLibrary(String path, CallbackContext callbackContext) { + callbackContext.error("This feature is no longer supported. Loading native libraries directly from JavaScript is no longer allowed due to security reasons."); + /*try { + System.load(path); + callbackContext.success("Library loaded successfully."); + } catch (Exception e) { + callbackContext.error("Failed to load library: " + e.getMessage()); + }*/ + } + + private void sendPluginResult(CallbackContext ctx, String message, boolean keepCallback) { + PluginResult result = new PluginResult(PluginResult.Status.OK, message); + result.setKeepCallback(keepCallback); + ctx.sendPluginResult(result); + } + + private void sendPluginMessage(String pid, String message) { + CallbackContext ctx = processCallbacks.get(pid); + if (ctx != null) { + sendPluginResult(ctx, message, true); + } + } + + private void cleanup(String pid) { + processes.remove(pid); + processInputs.remove(pid); + processCallbacks.remove(pid); + processDetails.remove(pid); + } + + private void listAllProcesses(CallbackContext callbackContext) { + try { + callbackContext.success(ProcessUtils.getAllProcesses()); + } catch (Exception e) { + callbackContext.error("Failed to list all processes: " + e.getMessage()); + } + } + + private void killProcess(int pid, CallbackContext callbackContext) { + try { + ProcessUtils.killProcess(pid); + callbackContext.success("Process terminated"); + } catch (Exception e) { + callbackContext.error("Failed to kill process: " + e.getMessage()); + } + } + + private static class ProcessDetails { + final String command; + final boolean alpine; + final long startedAt; + final long pid; + + ProcessDetails(String command, boolean alpine, long pid) { + this.command = command; + this.alpine = alpine; + this.startedAt = System.currentTimeMillis(); + this.pid = pid; + } + } +} diff --git a/src/plugins/terminal/src/android/Executor.java b/src/plugins/terminal/src/android/Executor.java index 3e0b4e83d7..0fd14cee8b 100644 --- a/src/plugins/terminal/src/android/Executor.java +++ b/src/plugins/terminal/src/android/Executor.java @@ -27,6 +27,11 @@ import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.app.Activity; +import com.foxdebug.acode.rk.exec.terminal.*; + +import java.net.ServerSocket; + + public class Executor extends CordovaPlugin { @@ -41,6 +46,8 @@ public class Executor extends CordovaPlugin { private static final int REQUEST_POST_NOTIFICATIONS = 1001; + + private void askNotificationPermission(Activity context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission( @@ -210,6 +217,14 @@ public void handleMessage(Message msg) { callbackContext.success(data); cleanupCallback(pid); break; + case "listProcesses": + try { + callbackContext.success(new JSONArray(data)); + } catch (JSONException error) { + callbackContext.error("Invalid process list: " + error.getMessage()); + } + cleanupCallback(pid); + break; } } } @@ -220,12 +235,15 @@ public void handleMessage(Message msg) { public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { // For actions that don't need the service, handle them directly if (action.equals("loadLibrary")) { + callbackContext.error("This feature is no longer supported. Loading native libraries directly from JavaScript is no longer allowed due to security reasons."); + /* try { System.load(args.getString(0)); callbackContext.success("Library loaded successfully."); } catch (Exception e) { callbackContext.error("Failed to load library: " + e.getMessage()); } + */ return true; } @@ -235,6 +253,82 @@ public boolean execute(String action, JSONArray args, CallbackContext callbackCo return true; } + if (action.equals("moveToBackground")) { + Intent intent = new Intent(context, TerminalService.class); + intent.setAction(TerminalService.MOVE_TO_BACKGROUND); + context.startService(intent); + callbackContext.success("Service moved to background mode"); + return true; + } + + if (action.equals("moveToForeground")) { + Intent intent = new Intent(context, TerminalService.class); + intent.setAction(TerminalService.MOVE_TO_FOREGROUND); + context.startService(intent); + callbackContext.success("Service moved to foreground mode"); + return true; + } + + if (action.equals("spawn")) { + try { + JSONArray cmdArr = args.getJSONArray(0); + String[] cmd = new String[cmdArr.length()]; + for (int i = 0; i < cmdArr.length(); i++) { + cmd[i] = cmdArr.getString(i); + } + + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + + ProcessServer server = new ProcessServer(port, cmd); + server.startAndAwait(); // blocks until onStart() fires — server is listening before port is returned + + callbackContext.success(port); + } catch (Exception e) { + e.printStackTrace(); + callbackContext.error("Failed to spawn process: " + e.getMessage()); + } + + return true; + } + + + if (action.equals("listAllProcesses")) { + try { + callbackContext.success(ProcessUtils.getAllProcesses()); + } catch (Exception e) { + callbackContext.error("Failed to list all processes: " + e.getMessage()); + } + return true; + } + + if (action.equals("killProcess")) { + try { + int targetPid = args.getInt(0); + ProcessUtils.killProcess(targetPid); + callbackContext.success("Process terminated"); + } catch (Exception e) { + callbackContext.error("Failed to kill process: " + e.getMessage()); + } + return true; + } + + if (action.equals("setProotDebug")) { + boolean enabled = args.getBoolean(0); + ProcessManager.prootDebug = enabled; + callbackContext.success("PRoot debug " + (enabled ? "enabled" : "disabled")); + return true; + } + + if (action.equals("listProcesses")) { + if (!isServiceBound || serviceMessenger == null) { + callbackContext.success(new org.json.JSONArray()); + return true; + } + } + // For all other actions, ensure service is bound first if (!ensureServiceBound(callbackContext)) { // Error already sent by ensureServiceBound @@ -267,6 +361,11 @@ public boolean execute(String action, JSONArray args, CallbackContext callbackCo callbackContextMap.put(pidCheck, callbackContext); isProcessRunning(pidCheck); return true; + case "listProcesses": + String requestId = UUID.randomUUID().toString(); + callbackContextMap.put(requestId, callbackContext); + listProcesses(requestId); + return true; default: callbackContext.error("Unknown action: " + action); return false; @@ -384,6 +483,23 @@ private void isProcessRunning(String pid) { } } + private void listProcesses(String requestId) { + Message msg = Message.obtain(null, TerminalService.MSG_LIST_PROCESSES); + msg.replyTo = handlerMessenger; + Bundle bundle = new Bundle(); + bundle.putString("id", requestId); + msg.setData(bundle); + try { + serviceMessenger.send(msg); + } catch (RemoteException e) { + CallbackContext callbackContext = getCallbackContext(requestId); + if (callbackContext != null) { + callbackContext.error("List processes error: " + e.getMessage()); + cleanupCallback(requestId); + } + } + } + private CallbackContext getCallbackContext(String id) { return callbackContextMap.get(id); } @@ -396,4 +512,4 @@ private void cleanupCallback(String id) { public void onDestroy() { super.onDestroy(); } -} \ No newline at end of file +} diff --git a/src/plugins/terminal/src/android/ProcessManager.java b/src/plugins/terminal/src/android/ProcessManager.java new file mode 100644 index 0000000000..51c94d25f7 --- /dev/null +++ b/src/plugins/terminal/src/android/ProcessManager.java @@ -0,0 +1,152 @@ +package com.foxdebug.acode.rk.exec.terminal; + +import android.content.Context; +import android.content.pm.PackageManager; +import android.os.Build; +import java.io.*; +import java.util.Map; +import java.util.TimeZone; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import com.foxdebug.acode.rk.exec.terminal.*; + +public class ProcessManager { + + private final Context context; + public static boolean prootDebug = false; + + public ProcessManager(Context context) { + this.context = context; + } + + /** + * Creates a ProcessBuilder with common environment setup + */ + public ProcessBuilder createProcessBuilder(String cmd, boolean useAlpine) { + if (useAlpine) { + refreshAxsSymlink(); + } + String xcmd = useAlpine ? "source $PREFIX/init-sandbox.sh " + cmd : cmd; + ProcessBuilder builder = new ProcessBuilder("sh", "-c", xcmd); + setupEnvironment(builder.environment()); + return builder; + } + + /** + * Play Store builds package axs as a native library. Keep the legacy + * $PREFIX/axs path valid for scripts and plugins that execute it directly. + */ + private void refreshAxsSymlink() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O || isFdroidBuild()) { + return; + } + + Path axsPath = Paths.get(context.getFilesDir().getAbsolutePath(), "axs"); + Path nativeAxsPath = Paths.get(context.getApplicationInfo().nativeLibraryDir, "libaxs.so"); + + if (!Files.exists(nativeAxsPath)) { + return; + } + + try { + if (Files.isSymbolicLink(axsPath)) { + Path currentTarget = Files.readSymbolicLink(axsPath); + if (currentTarget.equals(nativeAxsPath)) { + return; + } + } + + Files.deleteIfExists(axsPath); + Files.createSymbolicLink(axsPath, nativeAxsPath); + } catch (Exception ignored) { + // init-sandbox.sh will surface the execution error if the link is unusable. + } + } + + private boolean isFdroidBuild() { + // F-Droid builds are intentionally pinned to targetSdkVersion 28. + // This convention is also exposed to scripts through the FDROID env var. + return getTargetSdkVersion() <= 28; + } + + private int getTargetSdkVersion() { + try { + return context.getPackageManager() + .getPackageInfo(context.getPackageName(), 0) + .applicationInfo.targetSdkVersion; + } catch (PackageManager.NameNotFoundException e) { + return Build.VERSION_CODES.P; + } + } + + /** + * Sets up common environment variables + */ + private void setupEnvironment(Map env) { + env.put("PREFIX", context.getFilesDir().getAbsolutePath()); + env.put("NATIVE_DIR", context.getApplicationInfo().nativeLibraryDir); + + TimeZone tz = TimeZone.getDefault(); + env.put("ANDROID_TZ", tz.getID()); + + env.put("FDROID", String.valueOf(isFdroidBuild())); + + if (prootDebug) { + env.put("PROOT_VERBOSE", "2"); + } + } + + /** + * Reads all output from a stream + */ + public static String readStream(InputStream stream) throws IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); + StringBuilder output = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + output.append(line).append("\n"); + } + return output.toString(); + } + + /** + * Executes a command and returns the result + */ + public ExecResult executeCommand(String cmd, boolean useAlpine) throws Exception { + ProcessBuilder builder = createProcessBuilder(cmd, useAlpine); + Process process = builder.start(); + + String stdout = readStream(process.getInputStream()); + String stderr = readStream(process.getErrorStream()); + int exitCode = process.waitFor(); + + return new ExecResult(exitCode, stdout.trim(), stderr.trim()); + } + + /** + * Result container for command execution + */ + public static class ExecResult { + public final int exitCode; + public final String stdout; + public final String stderr; + + public ExecResult(int exitCode, String stdout, String stderr) { + this.exitCode = exitCode; + this.stdout = stdout; + this.stderr = stderr; + } + + public boolean isSuccess() { + return exitCode == 0; + } + + public String getErrorMessage() { + if (!stderr.isEmpty()) { + return stderr; + } + return "Command exited with code: " + exitCode; + } + } +} diff --git a/src/plugins/terminal/src/android/ProcessServer.java b/src/plugins/terminal/src/android/ProcessServer.java new file mode 100644 index 0000000000..c6c264164b --- /dev/null +++ b/src/plugins/terminal/src/android/ProcessServer.java @@ -0,0 +1,118 @@ +package com.foxdebug.acode.rk.exec.terminal; + +import org.java_websocket.WebSocket; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.server.WebSocketServer; + +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; + +class ProcessServer extends WebSocketServer { + + private final String[] cmd; + private final CountDownLatch readyLatch = new CountDownLatch(1); + private final AtomicReference startError = new AtomicReference<>(); + + private static final class ConnState { + final Process process; + final OutputStream stdin; + + ConnState(Process process, OutputStream stdin) { + this.process = process; + this.stdin = stdin; + } + } + + ProcessServer(int port, String[] cmd) { + super(new InetSocketAddress("127.0.0.1", port)); + this.cmd = cmd; + } + + void startAndAwait() throws Exception { + start(); + readyLatch.await(); + Exception err = startError.get(); + if (err != null) throw err; + } + + @Override + public void onStart() { + readyLatch.countDown(); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + if (conn == null) { + // Bind/startup failure — unblock startAndAwait() so it can throw. + startError.set(ex); + readyLatch.countDown(); + } + // Per-connection errors: do nothing. onClose fires immediately after + // for the same connection, which is the single place cleanup happens. + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + try { + Process process = new ProcessBuilder(cmd).redirectErrorStream(true).start(); + InputStream stdout = process.getInputStream(); + OutputStream stdin = process.getOutputStream(); + + conn.setAttachment(new ConnState(process, stdin)); + + new Thread(() -> { + try { + byte[] buf = new byte[8192]; + int len; + while ((len = stdout.read(buf)) != -1) { + conn.send(ByteBuffer.wrap(buf, 0, len)); + } + } catch (Exception ignored) {} + conn.close(1000, "process exited"); + }).start(); + + } catch (Exception e) { + conn.close(1011, "Failed to start process: " + e.getMessage()); + } + } + + @Override + public void onMessage(WebSocket conn, ByteBuffer msg) { + try { + ConnState state = conn.getAttachment(); + state.stdin.write(msg.array(), msg.position(), msg.remaining()); + state.stdin.flush(); + } catch (Exception ignored) {} + } + + @Override + public void onMessage(WebSocket conn, String message) { + try { + ConnState state = conn.getAttachment(); + state.stdin.write(message.getBytes(StandardCharsets.UTF_8)); + state.stdin.flush(); + } catch (Exception ignored) {} + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + try { + ConnState state = conn.getAttachment(); + if (state != null) state.process.destroy(); + } catch (Exception ignored) {} + + // stop() calls w.join() on every worker thread. If called directly from + // onClose (which runs on a WebSocketWorker thread), it deadlocks waiting + // for itself to finish. A separate thread sidesteps that entirely. + new Thread(() -> { + try { + stop(); + } catch (Exception ignored) {} + }).start(); + } +} \ No newline at end of file diff --git a/src/plugins/terminal/src/android/ProcessUtils.java b/src/plugins/terminal/src/android/ProcessUtils.java new file mode 100644 index 0000000000..003084f81e --- /dev/null +++ b/src/plugins/terminal/src/android/ProcessUtils.java @@ -0,0 +1,182 @@ +package com.foxdebug.acode.rk.exec.terminal; + +import java.lang.reflect.Field; +import java.io.*; +import java.nio.charset.StandardCharsets; +import org.json.JSONArray; +import org.json.JSONObject; +import android.util.Log; +import com.foxdebug.acode.rk.exec.terminal.*; + +public class ProcessUtils { + + /** + * Gets the PID of a process using reflection + */ + public static long getPid(Process process) { + try { + Field f = process.getClass().getDeclaredField("pid"); + f.setAccessible(true); + return f.getLong(process); + } catch (Exception e) { + return -1; + } + } + + /** + * Checks if a process is still alive + */ + public static boolean isAlive(Process process) { + try { + process.exitValue(); + return false; + } catch(IllegalThreadStateException e) { + return true; + } + } + + /** + * Forcefully kills a process and its children + */ + public static void killProcessTree(Process process) { + try { + long pid = getPid(process); + if (pid > 0) { + Runtime.getRuntime().exec(new String[]{"kill", "-9", "-" + pid}); + } + } catch (Exception error) { + Log.w("ProcessUtils", "Failed to kill process tree.", error); + } + process.destroy(); + } + + /** + * Forcefully kills a single process + */ + public static void killProcess(int pid) throws IOException, InterruptedException { + int exitCode = Runtime.getRuntime().exec(new String[]{"kill", "-9", String.valueOf(pid)}).waitFor(); + if (exitCode != 0) { + throw new IOException("kill -9 " + pid + " exited with code " + exitCode); + } + } + + /** + * Reads the cmdline file for a given process folder + */ + private static String readCmdline(File cmdlineFile) { + try (FileInputStream fis = new FileInputStream(cmdlineFile)) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int len; + while ((len = fis.read(buffer)) != -1) { + bos.write(buffer, 0, len); + if (bos.size() > 8192) break; // Limit to 8KB + } + byte[] bytes = bos.toByteArray(); + if (bytes.length == 0) return ""; + + // Replace null bytes with spaces, ignoring trailing nulls + int end = bytes.length; + while (end > 0 && bytes[end - 1] == 0) { + end--; + } + for (int i = 0; i < end; i++) { + if (bytes[i] == 0) { + bytes[i] = ' '; + } + } + return new String(bytes, 0, end, StandardCharsets.UTF_8); + } catch (IOException ignored) { + return ""; + } + } + + /** + * Lists all processes running under the current app UID + */ + public static JSONArray getAllProcesses() { + JSONArray processList = new JSONArray(); + int myUid = android.os.Process.myUid(); + int myPid = android.os.Process.myPid(); + File procDir = new File("/proc"); + File[] files = procDir.listFiles(); + if (files == null) { + return processList; + } + + for (File file : files) { + if (file.isDirectory()) { + String name = file.getName(); + if (name.matches("\\d+")) { + int pid = Integer.parseInt(name); + try { + File statusFile = new File(file, "status"); + if (!statusFile.exists()) continue; + + String procName = ""; + String procState = ""; + int ppid = -1; + long rss = 0; + boolean uidMatches = false; + + try (BufferedReader reader = new BufferedReader(new FileReader(statusFile))) { + String line; + while ((line = reader.readLine()) != null) { + if (line.startsWith("Name:")) { + procName = line.substring(5).trim(); + } else if (line.startsWith("State:")) { + procState = line.substring(6).trim(); + } else if (line.startsWith("PPid:")) { + try { + ppid = Integer.parseInt(line.substring(5).trim()); + } catch (NumberFormatException ignored) {} + } else if (line.startsWith("Uid:")) { + String[] uids = line.substring(4).trim().split("\\s+"); + if (uids.length > 0) { + try { + int uid = Integer.parseInt(uids[0]); + if (uid == myUid) { + uidMatches = true; + } + } catch (NumberFormatException ignored) {} + } + } else if (line.startsWith("VmRSS:")) { + String rssStr = line.substring(6).trim(); + rssStr = rssStr.replaceAll("[^0-9]", ""); + try { + rss = Long.parseLong(rssStr); // in kB + } catch (NumberFormatException ignored) {} + } + } + } + + // Skip processes that do not belong to our app UID + if (!uidMatches) { + continue; + } + + String cmdline = readCmdline(new File(file, "cmdline")); + if (cmdline.isEmpty()) { + cmdline = procName; + } + + JSONObject procObj = new JSONObject(); + procObj.put("pid", pid); + procObj.put("ppid", ppid); + procObj.put("name", procName); + procObj.put("command", cmdline); + procObj.put("state", procState); + procObj.put("memory", rss); // in kB + procObj.put("isSelf", pid == myPid); + procObj.put("startedAt", file.lastModified()); + + processList.put(procObj); + } catch (Exception ignored) { + // Ignore processes we cannot access + } + } + } + } + return processList; + } +} diff --git a/src/plugins/terminal/src/android/StreamHandler.java b/src/plugins/terminal/src/android/StreamHandler.java new file mode 100644 index 0000000000..ab4c643c73 --- /dev/null +++ b/src/plugins/terminal/src/android/StreamHandler.java @@ -0,0 +1,31 @@ +package com.foxdebug.acode.rk.exec.terminal; + +import java.io.*; +import com.foxdebug.acode.rk.exec.terminal.*; +public class StreamHandler { + + public interface OutputListener { + void onLine(String line); + } + + /** + * Streams output from an InputStream to a listener + */ + public static void streamOutput(InputStream inputStream, OutputListener listener) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { + String line; + while ((line = reader.readLine()) != null) { + listener.onLine(line); + } + } catch (IOException ignored) { + } + } + + /** + * Writes input to an OutputStream + */ + public static void writeToStream(OutputStream outputStream, String input) throws IOException { + outputStream.write((input + "\n").getBytes()); + outputStream.flush(); + } +} \ No newline at end of file diff --git a/src/plugins/terminal/src/android/TerminalService.java b/src/plugins/terminal/src/android/TerminalService.java index 813143f623..f662664ce1 100644 --- a/src/plugins/terminal/src/android/TerminalService.java +++ b/src/plugins/terminal/src/android/TerminalService.java @@ -16,16 +16,15 @@ import android.os.PowerManager; import android.os.RemoteException; import androidx.core.app.NotificationCompat; -import com.foxdebug.acode.R; -import java.io.BufferedReader; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; import java.io.OutputStream; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; -import java.lang.reflect.Field; +import com.foxdebug.acode.rk.exec.terminal.*; public class TerminalService extends Service { @@ -35,21 +34,37 @@ public class TerminalService extends Service { public static final int MSG_STOP_PROCESS = 3; public static final int MSG_IS_RUNNING = 4; public static final int MSG_EXEC = 5; + public static final int MSG_LIST_PROCESSES = 6; public static final String CHANNEL_ID = "terminal_exec_channel"; public static final String ACTION_EXIT_SERVICE = "com.foxdebug.acode.ACTION_EXIT_SERVICE"; + public static final String MOVE_TO_BACKGROUND = "com.foxdebug.acode.MOVE_TO_BACKGROUND"; + public static final String MOVE_TO_FOREGROUND = "com.foxdebug.acode.MOVE_TO_FOREGROUND"; public static final String ACTION_TOGGLE_WAKE_LOCK = "com.foxdebug.acode.ACTION_TOGGLE_WAKE_LOCK"; + public static boolean Default_Foreground = true; private final Map processes = new ConcurrentHashMap<>(); private final Map processInputs = new ConcurrentHashMap<>(); private final Map clientMessengers = new ConcurrentHashMap<>(); + private final Map processDetails = new ConcurrentHashMap<>(); private final java.util.concurrent.ExecutorService threadPool = Executors.newCachedThreadPool(); private final Messenger serviceMessenger = new Messenger(new ServiceHandler()); private PowerManager.WakeLock wakeLock; private boolean isWakeLockHeld = false; + private ProcessManager processManager; + + @Override + public void onCreate() { + super.onCreate(); + processManager = new ProcessManager(this); + if(Default_Foreground){ + createNotificationChannel(); + updateNotification(); + } + } @Override public IBinder onBind(Intent intent) { @@ -66,6 +81,13 @@ public int onStartCommand(Intent intent, int flags, int startId) { return START_NOT_STICKY; } else if (ACTION_TOGGLE_WAKE_LOCK.equals(action)) { toggleWakeLock(); + } else if(MOVE_TO_BACKGROUND.equals(action)){ + Default_Foreground = false; + stopForeground(true); + } else if(MOVE_TO_FOREGROUND.equals(action)){ + Default_Foreground = true; + createNotificationChannel(); + updateNotification(); } } return START_STICKY; @@ -83,7 +105,7 @@ public void handleMessage(Message msg) { String cmd = bundle.getString("cmd"); String alpine = bundle.getString("alpine"); clientMessengers.put(id, clientMessenger); - startProcess(id, cmd, alpine); + startProcess(id, cmd, "true".equals(alpine)); break; case MSG_WRITE_TO_PROCESS: String input = bundle.getString("input"); @@ -99,7 +121,10 @@ public void handleMessage(Message msg) { String execCmd = bundle.getString("cmd"); String execAlpine = bundle.getString("alpine"); clientMessengers.put(id, clientMessenger); - exec(id, execCmd, execAlpine); + exec(id, execCmd, "true".equals(execAlpine)); + break; + case MSG_LIST_PROCESSES: + listProcesses(id, clientMessenger); break; } } @@ -133,28 +158,30 @@ private void releaseWakeLock() { } } - private void startProcess(String pid, String cmd, String alpine) { + private void startProcess(String pid, String cmd, boolean useAlpine) { threadPool.execute(() -> { try { - String xcmd = alpine.equals("true") ? "source $PREFIX/init-sandbox.sh " + cmd : cmd; - ProcessBuilder builder = new ProcessBuilder("sh", "-c", xcmd); - - Map env = builder.environment(); - env.put("PREFIX", getFilesDir().getAbsolutePath()); - env.put("NATIVE_DIR", getApplicationInfo().nativeLibraryDir); - - try { - int target = getPackageManager().getPackageInfo(getPackageName(), 0).applicationInfo.targetSdkVersion; - env.put("FDROID", String.valueOf(target <= 28)); - } catch (Exception e) { - e.printStackTrace(); - } - + ProcessBuilder builder = processManager.createProcessBuilder(cmd, useAlpine); Process process = builder.start(); + + long pidVal = ProcessUtils.getPid(process); processes.put(pid, process); processInputs.put(pid, process.getOutputStream()); - threadPool.execute(() -> streamOutput(process.getInputStream(), pid, "stdout")); - threadPool.execute(() -> streamOutput(process.getErrorStream(), pid, "stderr")); + processDetails.put(pid, new ProcessDetails(cmd, useAlpine, pidVal)); + + // Stream stdout + threadPool.execute(() -> + StreamHandler.streamOutput(process.getInputStream(), + line -> sendMessageToClient(pid, "stdout", line)) + ); + + // Stream stderr + threadPool.execute(() -> + StreamHandler.streamOutput(process.getErrorStream(), + line -> sendMessageToClient(pid, "stderr", line)) + ); + + // Wait for process completion threadPool.execute(() -> { try { int exitCode = process.waitFor(); @@ -173,50 +200,17 @@ private void startProcess(String pid, String cmd, String alpine) { }); } - private void exec(String execId, String cmd, String alpine) { + private void exec(String execId, String cmd, boolean useAlpine) { threadPool.execute(() -> { try { - String xcmd = alpine.equals("true") ? "source $PREFIX/init-sandbox.sh " + cmd : cmd; - ProcessBuilder builder = new ProcessBuilder("sh", "-c", xcmd); - Map env = builder.environment(); - env.put("PREFIX", getFilesDir().getAbsolutePath()); - env.put("NATIVE_DIR", getApplicationInfo().nativeLibraryDir); - - try { - int target = getPackageManager().getPackageInfo(getPackageName(), 0).applicationInfo.targetSdkVersion; - env.put("FDROID", String.valueOf(target <= 28)); - } catch (Exception e) { - e.printStackTrace(); - } - - Process process = builder.start(); - BufferedReader stdOutReader = new BufferedReader( - new InputStreamReader(process.getInputStream())); - StringBuilder stdOut = new StringBuilder(); - String line; - while ((line = stdOutReader.readLine()) != null) { - stdOut.append(line).append("\n"); - } - - BufferedReader stdErrReader = new BufferedReader( - new InputStreamReader(process.getErrorStream())); - StringBuilder stdErr = new StringBuilder(); - while ((line = stdErrReader.readLine()) != null) { - stdErr.append(line).append("\n"); - } - - int exitCode = process.waitFor(); - - if (exitCode == 0) { - sendExecResultToClient(execId, true, stdOut.toString().trim()); + ProcessManager.ExecResult result = processManager.executeCommand(cmd, useAlpine); + + if (result.isSuccess()) { + sendExecResultToClient(execId, true, result.stdout); } else { - String errorOutput = stdErr.toString().trim(); - if (errorOutput.isEmpty()) { - errorOutput = "Command exited with code: " + exitCode; - } - sendExecResultToClient(execId, false, errorOutput); + sendExecResultToClient(execId, false, result.getErrorMessage()); } - + cleanup(execId); } catch (Exception e) { sendExecResultToClient(execId, false, "Exception: " + e.getMessage()); @@ -225,16 +219,6 @@ private void exec(String execId, String cmd, String alpine) { }); } - private void streamOutput(InputStream inputStream, String pid, String streamType) { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { - String line; - while ((line = reader.readLine()) != null) { - sendMessageToClient(pid, streamType, line); - } - } catch (IOException ignored) { - } - } - private void sendMessageToClient(String id, String action, String data) { Messenger clientMessenger = clientMessengers.get(id); if (clientMessenger != null) { @@ -274,62 +258,96 @@ private void writeToProcess(String pid, String input) { try { OutputStream os = processInputs.get(pid); if (os != null) { - os.write((input + "\n").getBytes()); - os.flush(); + StreamHandler.writeToStream(os, input); } } catch (IOException e) { e.printStackTrace(); } } - private long getPid(Process process) { - try { - Field f = process.getClass().getDeclaredField("pid"); - f.setAccessible(true); - return f.getLong(process); - } catch (Exception e) { - return -1; - } -} - - private void stopProcess(String pid) { Process process = processes.get(pid); if (process != null) { - try { - Runtime.getRuntime().exec("kill -9 -" + getPid(process)); - } catch (Exception ignored) {} - process.destroy(); + ProcessUtils.killProcessTree(process); cleanup(pid); } } - private void isProcessRunning(String pid, Messenger clientMessenger) { - Process process = processes.get(pid); - String status = process != null && isProcessAlive(process) ? "running" : "not_found"; - sendMessageToClient(pid, "isRunning", status); - } + private void listProcesses(String requestId, Messenger clientMessenger) { + JSONArray result = new JSONArray(); + + for (Map.Entry entry : processes.entrySet()) { + String id = entry.getKey(); + Process process = entry.getValue(); + if (!ProcessUtils.isAlive(process)) continue; + + ProcessDetails details = processDetails.get(id); + if (details == null) continue; + + try { + JSONObject item = new JSONObject(); + item.put("id", id); + item.put("command", details.command); + item.put("alpine", details.alpine); + item.put("startedAt", details.startedAt); + item.put("pid", details.pid); + result.put(item); + } catch (JSONException ignored) { + // These values are generated internally and should always serialize. + } + } - private boolean isProcessAlive(Process process) { try { - process.exitValue(); - return false; - } catch(IllegalThreadStateException e) { - return true; + Message reply = Message.obtain(); + Bundle bundle = new Bundle(); + bundle.putString("id", requestId); + bundle.putString("action", "listProcesses"); + bundle.putString("data", result.toString()); + reply.setData(bundle); + clientMessenger.send(reply); + } catch (RemoteException ignored) { + // The requesting WebView is no longer available. } } + private void isProcessRunning(String pid, Messenger clientMessenger) { + boolean running = + processes.containsKey(pid) && + ProcessUtils.isAlive(processes.get(pid)); + + try { + Message reply = Message.obtain(); + Bundle bundle = new Bundle(); + bundle.putString("id", pid); + bundle.putString("action", "isRunning"); + bundle.putString("data", running ? "running" : "stopped"); + reply.setData(bundle); + clientMessenger.send(reply); + } catch (RemoteException e) { + // nothing else to do + } +} + + private void cleanup(String id) { processes.remove(id); processInputs.remove(id); clientMessengers.remove(id); + processDetails.remove(id); } - @Override - public void onCreate() { - super.onCreate(); - createNotificationChannel(); - updateNotification(); + private static class ProcessDetails { + final String command; + final boolean alpine; + final long startedAt; + final long pid; + + ProcessDetails(String command, boolean alpine, long pid) { + this.command = command; + this.alpine = alpine; + this.startedAt = System.currentTimeMillis(); + this.pid = pid; + } } private void createNotificationChannel() { @@ -360,13 +378,15 @@ private void updateNotification() { String contentText = "Executor service" + (isWakeLockHeld ? " (wakelock held)" : ""); String wakeLockButtonText = isWakeLockHeld ? "Release Wake Lock" : "Acquire Wake Lock"; + int notificationIcon = resolveDrawableId("ic_notification", "ic_launcher_foreground", "ic_launcher"); + Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Acode Service") .setContentText(contentText) - .setSmallIcon(R.drawable.ic_launcher_foreground) + .setSmallIcon(notificationIcon) .setOngoing(true) - .addAction(R.drawable.ic_launcher_foreground, wakeLockButtonText, wakeLockPendingIntent) - .addAction(R.drawable.ic_launcher_foreground, "Exit", exitPendingIntent) + .addAction(notificationIcon, wakeLockButtonText, wakeLockPendingIntent) + .addAction(notificationIcon, "Exit", exitPendingIntent) .build(); startForeground(1, notification); @@ -379,15 +399,21 @@ public void onDestroy() { releaseWakeLock(); for (Process process : processes.values()) { - try { - Runtime.getRuntime().exec("kill -9 -" + getPid(process)); - } catch (Exception ignored) {} - process.destroyForcibly(); + ProcessUtils.killProcessTree(process); } processes.clear(); processInputs.clear(); clientMessengers.clear(); + processDetails.clear(); threadPool.shutdown(); } -} \ No newline at end of file + + private int resolveDrawableId(String... names) { + for (String name : names) { + int id = getResources().getIdentifier(name, "drawable", getPackageName()); + if (id != 0) return id; + } + return android.R.drawable.sym_def_app_icon; + } +} diff --git a/src/plugins/terminal/www/Executor.js b/src/plugins/terminal/www/Executor.js index 78103fafcd..541dcbdadc 100644 --- a/src/plugins/terminal/www/Executor.js +++ b/src/plugins/terminal/www/Executor.js @@ -1,14 +1,42 @@ /** - * @module Executor + * @class Executor * @description - * This module provides an interface to run shell commands from a Cordova app. + * This class provides an interface to run shell commands from a Cordova app. * It supports real-time process streaming, writing input to running processes, * stopping them, and executing one-time commands. */ const exec = require('cordova/exec'); -const Executor = { +class Executor { + constructor(BackgroundExecutor = false) { + this.ExecutorType = BackgroundExecutor ? "BackgroundExecutor" : "Executor"; + } + + /** + * Spawns a process and exposes it as a raw WebSocket stream. + * + * @param {string[]} cmd - Command and arguments to execute (e.g. `["sh", "-c", "echo hi"]`). + * @param {(ws: WebSocket) => void} callback - Called with the connected WebSocket once the + * process is ready. Use `ws.send()` to write to stdin and `ws.onmessage` to read stdout. + */ + spawnStream(cmd, callback, onError) { + exec((port) => { + const ws = new WebSocket(`ws://127.0.0.1:${port}`); + ws.binaryType = "arraybuffer"; + + ws.onopen = () => { + callback(ws); + }; + + ws.onerror = (e) => { + if (onError) onError(e); + }; + + }, (err) => { if (onError) onError(err); }, "Executor", "spawn", [cmd]); + } + + /** * Starts a shell process and enables real-time streaming of stdout, stderr, and exit status. * @@ -17,137 +45,233 @@ const Executor = { * - `"stdout"`: Standard output line. * - `"stderr"`: Standard error line. * - `"exit"`: Exit code of the process. - * @param {boolean} alpine - Whether to run the command inside the Alpine sandbox environment (`true`) or on Android directly (`false`). + * @param {boolean} [alpine=false] - Whether to run the command inside the Alpine sandbox environment (`true`) or on Android directly (`false`). * @returns {Promise} Resolves with a unique process ID (UUID) used for future references like `write()` or `stop()`. * * @example - * Executor.start('sh', (type, data) => { - * console.log(`[${type}] ${data}`); + * const executor = new Executor(); + * executor.start('sh', (type, data) => { + * //console.log(`[${type}] ${data}`); * }).then(uuid => { - * Executor.write(uuid, 'echo Hello World'); - * Executor.stop(uuid); + * executor.write(uuid, 'echo Hello World'); + * executor.stop(uuid); * }); */ - - - start(command, onData) { - this.start(command, onData, false); - }, - - start(command, onData, alpine) { - console.log("start: " + command); - + start(command, onData, alpine = false) { return new Promise((resolve, reject) => { let first = true; - exec(async (message) => { - console.log(message); - if (first) { - first = false; - await new Promise(resolve => setTimeout(resolve, 100)); - // First message is always the process UUID - resolve(message); - } else { - const match = message.match(/^([^:]+):(.*)$/); - if (match) { - const prefix = match[1]; // e.g. "stdout" - const message = match[2].trim(); // output - onData(prefix, message); + exec( + async (message) => { + //console.log(message); + if (first) { + first = false; + await new Promise(resolve => setTimeout(resolve, 100)); + // First message is always the process UUID + resolve(message); } else { - onData("unknown", message); + const match = message.match(/^([^:]+):(.*)$/); + if (match) { + const prefix = match[1]; // e.g. "stdout" + const content = match[2]; // output + onData(prefix, content); + } else { + onData("unknown", message); + } } - } - }, + }, reject, - "Executor", + this.ExecutorType, "start", [command, String(alpine)] ); }); - }, + } /** * Sends input to a running process's stdin. * - * @param {string} uuid - The process ID returned by {@link Executor.start}. + * @param {string} uuid - The process ID returned by {@link Executor#start}. * @param {string} input - Input string to send (e.g., shell commands). * @returns {Promise} Resolves once the input is written. * * @example - * Executor.write(uuid, 'ls /sdcard'); + * executor.write(uuid, 'ls /sdcard'); */ write(uuid, input) { - console.log("write: " + input + " to " + uuid); + //console.log("write: " + input + " to " + uuid); + return new Promise((resolve, reject) => { + exec(resolve, reject, this.ExecutorType, "write", [uuid, input]); + }); + } + + /** + * Moves the executor service to the background (stops foreground notification). + * + * @returns {Promise} Resolves when the service is moved to background. + * + * @example + * executor.moveToBackground(); + */ + moveToBackground() { + return new Promise((resolve, reject) => { + exec(resolve, reject, this.ExecutorType, "moveToBackground", []); + }); + } + + /** + * Moves the executor service to the foreground (shows notification). + * + * @returns {Promise} Resolves when the service is moved to foreground. + * + * @example + * executor.moveToForeground(); + */ + moveToForeground() { return new Promise((resolve, reject) => { - exec(resolve, reject, "Executor", "write", [uuid, input]); + exec(resolve, reject, this.ExecutorType, "moveToForeground", []); }); - }, + } /** * Terminates a running process. * - * @param {string} uuid - The process ID returned by {@link Executor.start}. + * @param {string} uuid - The process ID returned by {@link Executor#start}. * @returns {Promise} Resolves when the process has been stopped. * * @example - * Executor.stop(uuid); + * executor.stop(uuid); */ stop(uuid) { return new Promise((resolve, reject) => { - exec(resolve, reject, "Executor", "stop", [uuid]); + exec(resolve, reject, this.ExecutorType, "stop", [uuid]); }); - }, + } /** * Checks if a process is still running. * - * @param {string} uuid - The process ID returned by {@link Executor.start}. + * @param {string} uuid - The process ID returned by {@link Executor#start}. * @returns {Promise} Resolves `true` if the process is running, `false` otherwise. * * @example - * const isAlive = await Executor.isRunning(uuid); + * const isAlive = await executor.isRunning(uuid); */ isRunning(uuid) { return new Promise((resolve, reject) => { - exec((result) => { - resolve(result === "running"); - }, reject, "Executor", "isRunning", [uuid]); + exec( + (result) => { + resolve(result === "running"); + }, + reject, + this.ExecutorType, + "isRunning", + [uuid] + ); + }); + } + + /** + * Lists the processes currently managed by this executor. + * + * @returns {Promise>} + */ + listProcesses() { + return new Promise((resolve, reject) => { + exec( + (processes) => resolve(processes.map((process) => ({ + ...process, + background: this.ExecutorType === "BackgroundExecutor", + }))), + reject, + this.ExecutorType, + "listProcesses", + [] + ); + }); + } + + /** + * Lists all running OS processes under the app's user ID. + * + * @returns {Promise>} + */ + listAllProcesses() { + return new Promise((resolve, reject) => { + exec(resolve, reject, this.ExecutorType, "listAllProcesses", []); + }); + } + + /** + * Forcefully kills a process by its native PID. + * + * @param {number} pid - Native process ID to kill. + * @returns {Promise} Resolves when the process is terminated. + */ + killProcess(pid) { + return new Promise((resolve, reject) => { + exec(resolve, reject, this.ExecutorType, "killProcess", [pid]); }); - }, + } + /** + * Stops the executor service completely. + * + * @returns {Promise} Resolves when the service has been stopped. + * + * Note: This does not gurantee that all running processes have been killed, but the service will no longer be active. Use with caution. + * + * @example + * executor.stopService(); + */ stopService() { return new Promise((resolve, reject) => { - exec(resolve, reject, "Executor", "stopService", []); + exec(resolve, reject, this.ExecutorType, "stopService", []); }); - }, + } /** * Executes a shell command once and waits for it to finish. - * Unlike {@link Executor.start}, this does not stream output. + * Unlike {@link Executor#start}, this does not stream output. * * @param {string} command - The shell command to execute. - * @param {boolean} alpine - Whether to run the command in the Alpine sandbox (`true`) or Android environment (`false`). + * @param {boolean} [alpine=false] - Whether to run the command in the Alpine sandbox (`true`) or Android environment (`false`). * @returns {Promise} Resolves with standard output on success, rejects with an error or standard error on failure. * * @example - * Executor.execute('ls -l') - * .then(console.log) + * executor.execute('ls -l') + * .then(//console.log) * .catch(console.error); */ - execute(command) { - this.execute(command, false); - } - , - execute(command, alpine) { + execute(command, alpine = false) { return new Promise((resolve, reject) => { - exec(resolve, reject, "Executor", "exec", [command, String(alpine)]); + exec(resolve, reject, this.ExecutorType, "exec", [command, String(alpine)]); }); - }, + } + /** + * Loads a native library from the specified path. + * + * @param {string} path - The path to the native library to load. + * @returns {Promise} Resolves when the library has been loaded. + * + * @example + * executor.loadLibrary('/path/to/library.so'); + */ loadLibrary(path) { return new Promise((resolve, reject) => { - exec(resolve, reject, "Executor", "loadLibrary", [path]); + exec(resolve, reject, this.ExecutorType, "loadLibrary", [path]); }); } -}; -module.exports = Executor; + setProotDebug(enabled) { + return new Promise((resolve, reject) => { + exec(resolve, reject, this.ExecutorType, "setProotDebug", [enabled]); + }); + } +} + +//backward compatibility +const executorInstance = new Executor(); +executorInstance.BackgroundExecutor = new Executor(true); + +module.exports = executorInstance; diff --git a/src/plugins/terminal/www/Terminal.js b/src/plugins/terminal/www/Terminal.js index cf05ddb8b4..21ffde3755 100644 --- a/src/plugins/terminal/www/Terminal.js +++ b/src/plugins/terminal/www/Terminal.js @@ -8,49 +8,79 @@ const Terminal = { * @param {Function} [err_logger=console.error] - Function to log errors. * @returns {Promise} - Returns true if installation completes with exit code 0, void if not installing */ - async startAxs(installing = false, logger = console.log, err_logger = console.error) { + async startAxs(installing = false, logger = console.log, err_logger = console.error,failsafe = false) { const filesDir = await new Promise((resolve, reject) => { system.getFilesDir(resolve, reject); }); - if (installing) { - return new Promise((resolve, reject) => { - readAsset("init-alpine.sh", async (content) => { - system.writeText(`${filesDir}/init-alpine.sh`, content, logger, err_logger); - }); + const failsafeArg = failsafe ? "--failsafe" : ""; - readAsset("init-sandbox.sh", (content) => { - system.writeText(`${filesDir}/init-sandbox.sh`, content, logger, err_logger); + const [initAlpine, rmWrapper, initSandbox] = await Promise.all([ + readAsset("init-alpine.sh"), + readAsset("rm-wrapper.sh"), + readAsset("init-sandbox.sh"), + ]); - Executor.start("sh", (type, data) => { - logger(`${type} ${data}`); + await this.migrateLegacyHome(); - // Check for exit code during installation - if (type === "exit") { - resolve(data === "0"); - } - }).then(async (uuid) => { - await Executor.write(uuid, `source ${filesDir}/init-sandbox.sh ${installing ? "--installing" : ""}; exit`); - }).catch((error) => { - err_logger("Failed to start AXS:", error); - resolve(false); - }); - }); - }); - } else { - readAsset("init-alpine.sh", async (content) => { - system.writeText(`${filesDir}/init-alpine.sh`, content, logger, err_logger); - }); + const isFdroid = await Executor.execute("echo $FDROID"); + + if(isFdroid !== "true"){ +//the symlink must be updated everytime because the symlinks to native libs can break after app updates + await Executor.execute("rm -f $PREFIX/axs && ln -s $NATIVE_DIR/libaxs.so $PREFIX/axs") +} + + + await writeText(`${filesDir}/init-alpine.sh`, initAlpine); + await writeText(`${filesDir}/init-sandbox.sh`, initSandbox); - readAsset("init-sandbox.sh", (content) => { - system.writeText(`${filesDir}/init-sandbox.sh`, content, logger, err_logger); + await deleteFile(`${filesDir}/alpine/bin/rm`).catch(() => {}); + await writeText(`${filesDir}/alpine/bin/rm`, rmWrapper); + await setExec(`${filesDir}/alpine/bin/rm`, true); + + if (installing) { + return new Promise((resolve, reject) => { + let lastError = ""; Executor.start("sh", (type, data) => { + //console[type === "stderr" ? "error" : "log"](`[AXS] ${data}`); logger(`${type} ${data}`); + + if (type === "stderr" && data) { + lastError = lastError ? `${lastError}\n${data}` : data; + } + + // Check for exit code during installation + if (type === "exit") { + const success = data === "0"; + if (!success) { + this.lastInstallError = lastError + ? `Sandbox configuration failed with exit code ${data}: ${lastError}` + : `Sandbox configuration failed with exit code ${data}`; + } + resolve(success); + } }).then(async (uuid) => { - await Executor.write(uuid, `source ${filesDir}/init-sandbox.sh ${installing ? "--installing" : ""}; exit`); + await Executor.write(uuid, `source ${filesDir}/init-sandbox.sh ${installing ? "--installing" : ""} ${failsafeArg}; exit`); + }).catch((error) => { + const message = `Failed to start AXS: ${formatError(error)}`; + this.lastInstallError = message; + err_logger(message); + resolve(false); }); }); + } else { + try { + const uuid = await Executor.start("sh", (type, data) => { + //console[type === "stderr" ? "error" : "log"](`[AXS] ${data}`); + logger(`${type} ${data}`); + }); + await Executor.write(uuid, `source ${filesDir}/init-sandbox.sh ${installing ? "--installing" : ""} ${failsafeArg}; exit`); + } catch (error) { + const message = `Failed to start AXS: ${formatError(error)}`; + err_logger(message); + throw new Error(message); + } } }, @@ -79,7 +109,7 @@ const Terminal = { if (!pidExists) return false; - const result = await Executor.execute(`kill -0 $(cat $PREFIX/pid) 2>/dev/null && echo "true" || echo "false"`); + const result = await Executor.BackgroundExecutor.execute(`kill -0 $(cat $PREFIX/pid) 2>/dev/null && echo "true" || echo "false"`); return String(result).toLowerCase() === "true"; }, @@ -93,6 +123,10 @@ const Terminal = { async install(logger = console.log, err_logger = console.error) { if (!(await this.isSupported())) return false; + const isFdroid = await Executor.execute("echo $FDROID"); + + this.lastInstallError = ""; + try { //cleanup before insatll await this.uninstall(); @@ -109,130 +143,242 @@ const Terminal = { }); try { - let alpineUrl; - let axsUrl; - let prootUrl; - let libTalloc; - let libproot = null; - let libproot32 = null; - - if (arch === "arm64-v8a") { - libproot = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm64/libproot.so"; - libproot32 = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm64/libproot32.so"; - libTalloc = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm64/libtalloc.so"; - prootUrl = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm64/libproot-xed.so"; - axsUrl = `https://github.com/bajrangCoder/acodex_server/releases/latest/download/axs-musl-android-arm64`; - alpineUrl = "https://dl-cdn.alpinelinux.org/alpine/v3.21/releases/aarch64/alpine-minirootfs-3.21.0-aarch64.tar.gz"; - } else if (arch === "armeabi-v7a") { - libproot = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm32/libproot.so"; - libTalloc = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm32/libtalloc.so"; - prootUrl = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm32/libproot-xed.so"; - axsUrl = `https://github.com/bajrangCoder/acodex_server/releases/latest/download/axs-musl-android-armv7`; - alpineUrl = "https://dl-cdn.alpinelinux.org/alpine/v3.21/releases/armhf/alpine-minirootfs-3.21.0-armhf.tar.gz"; - } else if (arch === "x86_64") { - libproot = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/x64/libproot.so"; - libproot32 = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/x64/libproot32.so"; - libTalloc = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/x64/libtalloc.so"; - prootUrl = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/x64/libproot-xed.so"; - axsUrl = `https://github.com/bajrangCoder/acodex_server/releases/latest/download/axs-musl-android-x86_64`; - alpineUrl = "https://dl-cdn.alpinelinux.org/alpine/v3.21/releases/x86_64/alpine-minirootfs-3.21.0-x86_64.tar.gz"; - } else { - throw new Error(`Unsupported architecture: ${arch}`); - } + const architectures = { + "arm64-v8a": { + libraryDirectory: "arm64", + axsArchitecture: "arm64", + alpineDirectory: "aarch64", + alpineFilename: "alpine-minirootfs-3.21.0-aarch64.tar.gz", + hasLibproot32: true + }, + + "armeabi-v7a": { + libraryDirectory: "arm32", + axsArchitecture: "armv7", + alpineDirectory: "armhf", + alpineFilename: "alpine-minirootfs-3.21.0-armhf.tar.gz", + hasLibproot32: false + }, + + "x86_64": { + libraryDirectory: "x64", + axsArchitecture: "x86_64", + alpineDirectory: "x86_64", + alpineFilename: "alpine-minirootfs-3.21.0-x86_64.tar.gz", + hasLibproot32: true + } + }; - logger("⬇️ Downloading sandbox filesystem..."); - await new Promise((resolve, reject) => { - cordova.plugin.http.downloadFile( - alpineUrl, {}, {}, - cordova.file.dataDirectory + "alpine.tar.gz", - resolve, reject - ); - }); + const architecture = architectures[arch]; - logger("⬇️ Downloading axs..."); - await new Promise((resolve, reject) => { - cordova.plugin.http.downloadFile( - axsUrl, {}, {}, - cordova.file.dataDirectory + "axs", - resolve, reject - ); - }); + if (!architecture) { + throw new Error(`Unsupported architecture: ${arch}`); + } + + if(isFdroid === "true") { + const buildUrl = (...parts) => parts.join(""); + + + const strings = { + protocol: ["ht", "tps", ":", "//"], + + rawGithubDomain: [ + "raw", + ".", + "github", + "usercontent", + ".", + "com" + ], + + githubDomain: [ + "git", + "hub", + ".", + "com" + ], + + alpineDomain: [ + "dl", + "-", + "cdn", + ".", + "alpine", + "linux", + ".", + "org" + ], + + acodeFoundation: [ + "Acode", + "-", + "Foundation" + ], + + acodeRepo: [ + "A", + "code" + ], + + bajrangCoder: [ + "bajrang", + "Coder" + ], + + acodexServer: [ + "acodex", + "_", + "server" + ], + + libraries: { + proot: ["li", "bp", "root", ".", "so"], + proot32: ["li", "bp", "root", "32", ".", "so"], + talloc: ["li", "bt", "alloc", ".", "so"], + prootXed: ["li", "bp", "root", "-", "xed", ".", "so"] + } + }; + + const rawGithubBase = buildUrl( + ...strings.protocol, + ...strings.rawGithubDomain, + "/", + ...strings.acodeFoundation, + "/", + ...strings.acodeRepo, + "/main/src/plugins/proot/libs/" + ); + + const githubReleaseBase = buildUrl( + ...strings.protocol, + ...strings.githubDomain, + "/", + ...strings.bajrangCoder, + "/", + ...strings.acodexServer, + "/releases/latest/download/" + ); + + const alpineBase = buildUrl( + ...strings.protocol, + ...strings.alpineDomain, + "/alpine/v3.21/releases/" + ); + + const libraryBaseUrl = buildUrl( + rawGithubBase, + architecture.libraryDirectory, + "/" + ); + + const libproot = buildUrl( + libraryBaseUrl, + ...strings.libraries.proot + ); + + const libTalloc = buildUrl( + libraryBaseUrl, + ...strings.libraries.talloc + ); + + const prootUrl = buildUrl( + libraryBaseUrl, + ...strings.libraries.prootXed + ); + + const libproot32 = architecture.hasLibproot32 + ? buildUrl( + libraryBaseUrl, + ...strings.libraries.proot32 + ) + : null; + + const axsUrl = buildUrl( + githubReleaseBase, + "axs-pie-android-", + architecture.axsArchitecture + ); + + const alpineUrl = buildUrl( + alpineBase, + architecture.alpineDirectory, + "/", + architecture.alpineFilename + ); + + logger("⬇️ Downloading sandbox filesystem..."); + await downloadFile(alpineUrl, cordova.file.dataDirectory + "alpine.tar.gz", "Sandbox filesystem"); + + logger("⬇️ Downloading axs..."); + await downloadFile(axsUrl, cordova.file.dataDirectory + "axs", "AXS"); - const isFdroid = await Executor.execute("echo $FDROID"); - if (isFdroid === "true") { - logger("🐧 F-Droid flavor detected, downloading additional files..."); logger("⬇️ Downloading compatibility layer..."); - await new Promise((resolve, reject) => { - cordova.plugin.http.downloadFile( - prootUrl, {}, {}, - cordova.file.dataDirectory + "libproot-xed.so", - resolve, reject - ); - }); + await downloadFile(prootUrl, cordova.file.dataDirectory + "libproot-xed.so", "Compatibility layer"); logger("⬇️ Downloading supporting library..."); - await new Promise((resolve, reject) => { - cordova.plugin.http.downloadFile( - libTalloc, {}, {}, - cordova.file.dataDirectory + "libtalloc.so.2", - resolve, reject - ); - }); + await downloadFile(libTalloc, cordova.file.dataDirectory + "libtalloc.so.2", "Supporting library"); if (libproot != null) { - await new Promise((resolve, reject) => { - cordova.plugin.http.downloadFile( - libproot, {}, {}, - cordova.file.dataDirectory + "libproot.so", - resolve, reject - ); - }); + await downloadFile(libproot, cordova.file.dataDirectory + "libproot.so", "proot loader"); } if (libproot32 != null) { - await new Promise((resolve, reject) => { - cordova.plugin.http.downloadFile( - libproot32, {}, {}, - cordova.file.dataDirectory + "libproot32.so", - resolve, reject - ); - }); + await downloadFile(libproot32, cordova.file.dataDirectory + "libproot32.so", "32-bit proot loader"); } - } + logger("✅ All downloads completed"); + }else{ + logger("📦 Extracting assets..."); + await new Promise((resolve, reject) => { + system.extractAsset(`alpine_assets/${architecture.libraryDirectory}/alpine.rootfs`, `${filesDir}/alpine.tar.gz`, resolve, (e)=>{ + console.error(`Failed to extract alpine.tar.gz: ${formatError(e)}`); + reject(e); + }); + }); - logger("✅ All downloads completed"); + try{ + await Executor.execute("rm -f $PREFIX/axs && ln -s $NATIVE_DIR/libaxs.so $PREFIX/axs") + }catch(e){ + err_logger(`${formatError(e)}`); + } + } + logger("📁 Setting up directories..."); - await new Promise((resolve, reject) => { - system.mkdirs(`${filesDir}/.downloaded`, resolve, reject); - }); + await ensureDir(`${filesDir}/.downloaded`); const alpineDir = `${filesDir}/alpine`; - await new Promise((resolve, reject) => { - system.mkdirs(alpineDir, resolve, reject); - }); + await ensureDir(alpineDir); + logger("📦 Extracting sandbox filesystem..."); await Executor.execute(`tar --no-same-owner -xf ${filesDir}/alpine.tar.gz -C ${alpineDir}`); logger("⚙️ Applying basic configuration..."); - system.writeText(`${alpineDir}/etc/resolv.conf`, `nameserver 8.8.4.4 \nnameserver 8.8.8.8`); + await writeText(`${alpineDir}/etc/resolv.conf`, `nameserver 8.8.4.4 \nnameserver 8.8.8.8`); + + const rmWrapper = await readAsset("rm-wrapper.sh"); + await deleteFile(`${alpineDir}/bin/rm`).catch(() => {}); + await writeText(`${alpineDir}/bin/rm`, rmWrapper); + await setExec(`${alpineDir}/bin/rm`, true); logger("✅ Extraction complete"); - await new Promise((resolve, reject) => { - system.mkdirs(`${filesDir}/.extracted`, resolve, reject); - }); + await ensureDir(`${filesDir}/.extracted`); logger("⚙️ Updating sandbox enviroment..."); const installResult = await this.startAxs(true, logger, err_logger); + if (!installResult) { + throw new Error(this.lastInstallError || "Sandbox configuration failed."); + } return installResult; } catch (e) { - err_logger("Installation failed:", e); + const message = formatError(e); + this.lastInstallError = message; + err_logger(`Installation failed: ${message}`); console.error("Installation failed:", e); return false; } @@ -309,21 +455,16 @@ const Terminal = { reject("Alpine is not installed."); return; } - const cmd = ` set -e - - INCLUDE_FILES="alpine .downloaded .extracted axs" + INCLUDE_FILES="alpine .downloaded .extracted .configured axs" if [ "$FDROID" = "true" ]; then INCLUDE_FILES="$INCLUDE_FILES libtalloc.so.2 libproot-xed.so" fi - - EXCLUDE="--exclude=alpine/data --exclude=alpine/system --exclude=alpine/vendor --exclude=alpine/sdcard --exclude=alpine/storage --exclude=alpine/public" - + EXCLUDE="--exclude=alpine/data --exclude=alpine/system --exclude=alpine/vendor --exclude=alpine/sdcard --exclude=alpine/storage --exclude=alpine/public --exclude=alpine/apex --exclude=alpine/odm --exclude=alpine/product --exclude=alpine/system_ext --exclude=alpine/linkerconfig --exclude=alpine/proc --exclude=alpine/sys --exclude=alpine/dev --exclude=alpine/run --exclude=alpine/tmp" tar -cf "$PREFIX/aterm_backup.tar" -C "$PREFIX" $EXCLUDE $INCLUDE_FILES echo "ok" `; - const result = await Executor.execute(cmd); if (result === "ok") { resolve(cordova.file.dataDirectory + "aterm_backup.tar"); @@ -357,9 +498,9 @@ const Terminal = { } const cmd = ` - sleep 2 + set -e - INCLUDE_FILES="$PREFIX/alpine $PREFIX/.downloaded $PREFIX/.extracted $PREFIX/axs" + INCLUDE_FILES="$PREFIX/alpine $PREFIX/.downloaded $PREFIX/.extracted $PREFIX/.configured $PREFIX/axs" if [ "$FDROID" = "true" ]; then INCLUDE_FILES="$INCLUDE_FILES $PREFIX/libtalloc.so.2 $PREFIX/libproot-xed.so" @@ -369,11 +510,11 @@ const Terminal = { rm -rf -- "$item" done - tar -xf "$PREFIX/aterm_backup.bin" -C "$PREFIX" + tar -xf $PREFIX/aterm_backup.* -C "$PREFIX" echo "ok" `; - const result = await Executor.execute(cmd); + const result = await Executor.BackgroundExecutor.execute(cmd); if (result === "ok") { resolve(result); } else { @@ -407,7 +548,7 @@ const Terminal = { const cmd = ` set -e - INCLUDE_FILES="$PREFIX/alpine $PREFIX/.downloaded $PREFIX/.extracted $PREFIX/axs" + INCLUDE_FILES="$PREFIX/alpine $PREFIX/.downloaded $PREFIX/.extracted $PREFIX/.configured $PREFIX/axs" if [ "$FDROID" = "true" ]; then INCLUDE_FILES="$INCLUDE_FILES $PREFIX/libtalloc.so.2 $PREFIX/libproot-xed.so" @@ -419,27 +560,156 @@ const Terminal = { echo "ok" `; - const result = await Executor.execute(cmd); + const result = await Executor.BackgroundExecutor.execute(cmd); if (result === "ok") { resolve(result); } else { reject(result); } }); - } + }, + + /** + * Migrates the legacy terminal home directories into public/MIGRATE. + * Older builds stored user files under alpine/home and alpine/root. + * After /home, /root and /public were merged into a single public + * directory, any files still left in the old locations are copied + * into public/MIGRATE (keeping their source structure) so nothing is + * hidden or lost. This is a no-op once the migration has run. + * @returns {Promise} + */ + async migrateLegacyHome() { + if (this._legacyHomeMigrated) return; + try { + const cmd = ` + MIGRATE="$PREFIX/public/MIGRATE" + + # Already migrated + [ -e "$MIGRATE/.migrated" ] && exit 0 + + COPIED=false + + if [ -d "$PREFIX/alpine/home" ] && [ -n "$(find "$PREFIX/alpine/home" -mindepth 1 -maxdepth 1 2>/dev/null | head -n 1)" ]; then + mkdir -p "$MIGRATE/home" + if cp -a "$PREFIX/alpine/home/." "$MIGRATE/home/"; then + COPIED=true + else + exit 1 + fi + fi + + if [ -d "$PREFIX/alpine/root" ] && [ -n "$(find "$PREFIX/alpine/root" -mindepth 1 -maxdepth 1 2>/dev/null | head -n 1)" ]; then + mkdir -p "$MIGRATE/root" + if cp -a "$PREFIX/alpine/root/." "$MIGRATE/root/"; then + COPIED=true + else + exit 1 + fi + fi + + # Mark as migrated so this only runs once + if [ "$COPIED" = "true" ]; then + touch "$MIGRATE/.migrated" + fi + `; + await Executor.BackgroundExecutor.execute(cmd); + this._legacyHomeMigrated = true; + } catch (error) { + console.error("Failed to migrate legacy terminal home:", formatError(error)); + } + }, + + formatError }; function readAsset(assetPath, callback) { const assetUrl = "file:///android_asset/" + assetPath; - window.resolveLocalFileSystemURL(assetUrl, fileEntry => { - fileEntry.file(file => { - const reader = new FileReader(); - reader.onloadend = () => callback(reader.result); - reader.readAsText(file); - }, console.error); - }, console.error); + const promise = new Promise((resolve, reject) => { + window.resolveLocalFileSystemURL(assetUrl, fileEntry => { + fileEntry.file(file => { + const reader = new FileReader(); + reader.onloadend = () => resolve(reader.result); + reader.onerror = () => reject(reader.error || new Error(`Failed to read ${assetPath}`)); + reader.readAsText(file); + }, reject); + }, reject); + }); + + if (callback) { + promise.then(callback).catch(console.error); + } + + return promise; +} + +function fileExists(path) { + return new Promise((resolve, reject) => { + system.fileExists(path, false, (result) => { + resolve(result == 1); + }, reject); + }); +} + +async function ensureDir(path) { + if (await fileExists(path)) return; + + await new Promise((resolve, reject) => { + system.mkdirs(path, resolve, reject); + }); +} + +function writeText(path, content) { + return new Promise((resolve, reject) => { + system.writeText(path, content, resolve, reject); + }); +} + +function deleteFile(path) { + return new Promise((resolve, reject) => { + system.deleteFile(path, resolve, reject); + }); +} + +function setExec(path, executable) { + return new Promise((resolve, reject) => { + system.setExec(path, executable, resolve, reject); + }); +} + +function downloadFile(url, destination, label) { + return new Promise((resolve, reject) => { + cordova.plugin.http.downloadFile( + url, {}, {}, + destination, + resolve, + (error) => reject(new Error(`${label} download failed: ${formatError(error)}`)) + ); + }); +} + +function formatError(error) { + if (error == null) return "Unknown error"; + if (error instanceof Error) return error.message || String(error); + if (typeof error === "string") return error || "Unknown error"; + if (typeof error === "object") { + const parts = []; + if (error.status != null) parts.push(`status ${error.status}`); + if (error.error) parts.push(String(error.error)); + if (error.message) parts.push(String(error.message)); + if (error.exception) parts.push(String(error.exception)); + if (error.url) parts.push(`URL: ${error.url}`); + if (parts.length) return parts.join(" - "); + + try { + return JSON.stringify(error); + } catch (jsonError) { + return String(error); + } + } + + return String(error); } -module.exports = Terminal; \ No newline at end of file +module.exports = Terminal; diff --git a/src/plugins/websocket/www/websocket.js b/src/plugins/websocket/www/websocket.js index f1d1e93b1b..acf883149d 100644 --- a/src/plugins/websocket/www/websocket.js +++ b/src/plugins/websocket/www/websocket.js @@ -58,13 +58,21 @@ class WebSocketInstance extends EventTarget { if (event.type === 'close') { this.readyState = WebSocketInstance.CLOSED; - const closeEvent = new CloseEvent('close', { code: event.data?.code, reason: event.data?.reason }); + const closeData = event && event.data ? event.data : {}; + const closeEvent = new CloseEvent('close', { + code: closeData.code, + reason: closeData.reason, + }); if (this.onclose) this.onclose(closeEvent); this.dispatchEvent(closeEvent); } if (event.type === 'error') { - const errorEvent = new Event('error', { message: event?.data }); + const errorMessage = event && event.data ? event.data : undefined; + const errorEvent = new Event('error'); + if (errorMessage !== undefined) { + errorEvent.message = errorMessage; + } if (this.onerror) this.onerror(errorEvent); this.dispatchEvent(errorEvent); } diff --git a/src/plugins/webview/package.json b/src/plugins/webview/package.json new file mode 100644 index 0000000000..67641909fa --- /dev/null +++ b/src/plugins/webview/package.json @@ -0,0 +1,11 @@ +{ + "name": "cordova-plugin-acode-webview", + "version": "2.0.0", + "description": "Acode WebView Plugin API - Create and manage isolated WebView instances", + "main": "", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "Apache-2.0" +} diff --git a/src/plugins/webview/plugin.xml b/src/plugins/webview/plugin.xml new file mode 100644 index 0000000000..e12862da9c --- /dev/null +++ b/src/plugins/webview/plugin.xml @@ -0,0 +1,33 @@ + + + cordova-plugin-acode-webview + Acode WebView Plugin API - Create and manage isolated WebView instances + Apache 2.0 + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/plugins/webview/src/android/com/foxdebug/webview/ProfileManager.java b/src/plugins/webview/src/android/com/foxdebug/webview/ProfileManager.java new file mode 100644 index 0000000000..1968d6aebd --- /dev/null +++ b/src/plugins/webview/src/android/com/foxdebug/webview/ProfileManager.java @@ -0,0 +1,252 @@ +package com.foxdebug.webview; + +import android.util.Log; +import android.webkit.CookieManager; +import android.webkit.WebStorage; +import android.webkit.WebView; +import androidx.webkit.Profile; +import androidx.webkit.ProfileStore; +import androidx.webkit.WebStorageCompat; +import androidx.webkit.WebViewCompat; +import androidx.webkit.WebViewFeature; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Incognito / profile isolation built on AndroidX WebKit's multi-profile API. + * + *

WebView profiles provide a genuinely separate cookie jar and web-storage + * area, which is what "incognito" needs. Support depends on the installed + * WebView provider ({@link WebViewFeature#MULTI_PROFILE}); when it is missing + * {@link #acquire} returns {@code null} and the instance falls back to the + * best-effort behaviour documented on {@code WebViewInstance}. + * + *

A profile is acquired when the instance is created (so its isolation state + * is known before the lazily created fullscreen WebView exists) and bound to + * the WebView once it is constructed. Profiles are reference counted so several + * instances can share one. Data is cleared when the last instance goes away, + * and auto-generated incognito profiles are also deleted. + */ +final class ProfileManager { + + private static final String TAG = "AcodeWebView"; + private static final String EPHEMERAL_PREFIX = "acode_incognito_"; + private static final int MAX_NAME_LENGTH = 64; + + /** + * Profile names are passed to the WebView provider verbatim, so they must be + * canonical. Anything else is rejected instead of being rewritten, which + * would let two different requested names collide onto one shared profile. + */ + private static final Pattern VALID_NAME = Pattern.compile("[A-Za-z0-9_-]{1," + MAX_NAME_LENGTH + "}"); + + private static final Map refCounts = new HashMap<>(); + + private ProfileManager() {} + + static boolean isSupported() { + try { + return WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE); + } catch (Throwable t) { + return false; + } + } + + static boolean canDeleteBrowsingData() { + try { + return WebViewFeature.isFeatureSupported(WebViewFeature.DELETE_BROWSING_DATA); + } catch (Throwable t) { + return false; + } + } + + /** True when {@code name} can be used verbatim as a WebView profile name. */ + static boolean isValidName(String name) { + return name != null && VALID_NAME.matcher(name).matches(); + } + + /** True for the reserved namespace used by auto-generated incognito profiles. */ + static boolean isReservedName(String name) { + return name != null && name.startsWith(EPHEMERAL_PREFIX); + } + + /** + * Validates a caller-supplied profile name. Rejecting (rather than rewriting) + * guarantees distinct requested names never select the same profile. + */ + static void requireValidUserName(String name) { + if (!isValidName(name)) { + throw new IllegalArgumentException( + "Unsupported profileName: \"" + name + + "\". Use 1-" + MAX_NAME_LENGTH + " characters from A-Z, a-z, 0-9, \"_\" or \"-\"." + ); + } + if (isReservedName(name)) { + throw new IllegalArgumentException( + "Unsupported profileName: \"" + name + "\" uses the reserved \"" + + EPHEMERAL_PREFIX + "\" prefix." + ); + } + } + + /** Name for an auto-generated, ephemeral incognito profile. */ + static String ephemeralName(String id) { + StringBuilder builder = new StringBuilder(EPHEMERAL_PREFIX); + String source = id != null ? id : ""; + for (int i = 0; i < source.length() && builder.length() < MAX_NAME_LENGTH; i++) { + char c = source.charAt(i); + if (Character.isLetterOrDigit(c) || c == '_' || c == '-') { + builder.append(c); + } + } + return builder.toString(); + } + + /** + * Creates (or joins) the named profile and takes a reference. Runs on the UI + * thread, before the WebView exists. Returns null when isolation is not + * available; callers then use the documented fallback. + */ + static Profile acquire(String profileName) { + if (profileName == null || !isSupported()) return null; + try { + ProfileStore store = ProfileStore.getInstance(); + Profile profile = store.getOrCreateProfile(profileName); + if (profile == null) return null; + + CookieManager cookies = profile.getCookieManager(); + if (cookies != null) { + cookies.setAcceptCookie(true); + } + + refCounts.merge(profileName, 1, Integer::sum); + return profile; + } catch (Throwable t) { + // Any provider-side failure degrades to the non-isolated fallback rather + // than failing instance creation. + Log.w(TAG, "Profile isolation unavailable for \"" + profileName + "\"", t); + return null; + } + } + + /** + * Binds an acquired profile to a freshly constructed WebView. Must run on the + * UI thread and before the WebView loads any content. + */ + static boolean bind(WebView view, Profile profile) { + if (view == null || profile == null) return false; + try { + WebViewCompat.setProfile(view, profile.getName()); + return true; + } catch (Throwable t) { + Log.w(TAG, "Could not bind profile \"" + profile.getName() + "\"", t); + return false; + } + } + + /** + * Releases one reference to a profile. When the last reference is gone the + * profile's browsing data is cleared and, if it was auto-generated for + * incognito, the profile itself is deleted. + */ + static void release(String profileName, boolean ephemeral, boolean clearData) { + if (profileName == null) return; + + Integer count = refCounts.get(profileName); + if (count == null) return; + if (count > 1) { + refCounts.put(profileName, count - 1); + return; + } + refCounts.remove(profileName); + + if (!clearData && !ephemeral) return; + + try { + ProfileStore store = ProfileStore.getInstance(); + Profile profile = store.getProfile(profileName); + if (profile == null) { + if (ephemeral) deleteQuietly(profileName); + return; + } + clearProfile(profile, () -> { + if (ephemeral) deleteQuietly(profileName); + }); + } catch (Throwable t) { + Log.w(TAG, "Could not release profile \"" + profileName + "\"", t); + } + } + + /** + * Deletes auto-generated incognito profiles left behind by a previous + * process (for example when the app was killed before cleanup ran). + */ + static void cleanupEphemeralProfiles() { + if (!isSupported()) return; + try { + ProfileStore store = ProfileStore.getInstance(); + List names = new ArrayList<>(store.getAllProfileNames()); + for (String name : names) { + if (name == null || !name.startsWith(EPHEMERAL_PREFIX)) continue; + Profile profile = store.getProfile(name); + if (profile == null) { + deleteQuietly(name); + } else { + clearProfile(profile, () -> deleteQuietly(name)); + } + } + } catch (Throwable t) { + Log.w(TAG, "Could not clean up ephemeral profiles", t); + } + } + + private static void clearProfile(Profile profile, Runnable onDone) { + try { + CookieManager cookies = profile.getCookieManager(); + if (cookies != null) { + cookies.removeAllCookies(null); + } + } catch (Throwable t) { + Log.w(TAG, "Could not clear profile cookies", t); + } + + WebStorage storage = null; + try { + storage = profile.getWebStorage(); + } catch (Throwable t) { + Log.w(TAG, "Could not access profile web storage", t); + } + + if (storage == null) { + if (onDone != null) onDone.run(); + return; + } + + if (canDeleteBrowsingData()) { + try { + WebStorageCompat.deleteBrowsingData(storage, onDone); + return; + } catch (Throwable t) { + Log.w(TAG, "deleteBrowsingData failed; falling back to deleteAllData", t); + } + } + + try { + storage.deleteAllData(); + } catch (Throwable t) { + Log.w(TAG, "Could not clear profile web storage", t); + } + if (onDone != null) onDone.run(); + } + + private static void deleteQuietly(String profileName) { + try { + ProfileStore.getInstance().deleteProfile(profileName); + } catch (Throwable t) { + Log.w(TAG, "Could not delete profile \"" + profileName + "\"", t); + } + } +} diff --git a/src/plugins/webview/src/android/com/foxdebug/webview/WebViewActivity.java b/src/plugins/webview/src/android/com/foxdebug/webview/WebViewActivity.java new file mode 100644 index 0000000000..849eaea57f --- /dev/null +++ b/src/plugins/webview/src/android/com/foxdebug/webview/WebViewActivity.java @@ -0,0 +1,141 @@ +package com.foxdebug.webview; + +import android.app.Activity; +import android.os.Build; +import android.os.Bundle; +import android.view.View; +import android.view.ViewGroup; +import android.webkit.WebView; +import android.widget.FrameLayout; + +/** + * Hosts a "fullscreen" {@link WebViewInstance}: it shows the instance's WebView + * and renders fullscreen custom views (video, canvas, …) on top of it. + */ +public class WebViewActivity extends Activity { + + private WebView webView; + private String webviewId; + private FrameLayout container; + private View customView; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + webviewId = getIntent().getStringExtra("webviewId"); + + // The plugin registers itself in pluginInitialize(), so the singleton is + // always available while the app is alive. + WebViewPlugin plugin = WebViewPlugin.getInstance(); + WebViewInstance instance = plugin != null ? plugin.getInstance(webviewId) : null; + if (instance == null) { + finish(); + return; + } + + instance.createWebView(this); + webView = instance.getWebView(); + if (webView == null) { + finish(); + return; + } + instance.setHostingActivity(this); + + String title = instance.getTitle(); + if (title != null && !title.isEmpty()) { + setTitle(title); + } + + if (webView.getParent() != null) { + ((ViewGroup) webView.getParent()).removeView(webView); + } + container = new FrameLayout(this); + // Edge-to-edge is enforced on newer Android versions, so pad the content + // out from under the status and navigation bars. + WebViewInstance.applySystemBarInsets(container); + container.addView(webView, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT + )); + setContentView(container); + + if (Build.VERSION.SDK_INT >= 30) { + getWindow().setDecorFitsSystemWindows(false); + } + } + + /** Renders a fullscreen custom view (e.g. a

Instances are created by {@link WebViewPlugin} and can either be + * "fullscreen" (hosted by a {@link WebViewActivity}) or "hidden" (headless). + * Isolation is always on: file/content access is disabled and navigation is + * restricted to http(s). Incognito additionally routes the WebView through a + * private WebView profile when the provider supports it. + */ +public class WebViewInstance { + + private static final String TAG = "WebViewInstance"; + private static final String BRIDGE_NAME = "AcodeWebViewNative"; + + private static final String EVENT_PAGE_STARTED = "pageStarted"; + private static final String EVENT_PAGE_FINISHED = "pageFinished"; + private static final String EVENT_PAGE_COMMIT_VISIBLE = "pageCommitVisible"; + private static final String EVENT_PROGRESS = "progressChanged"; + private static final String EVENT_TITLE_CHANGED = "titleChanged"; + private static final String EVENT_FAVICON_CHANGED = "faviconChanged"; + private static final String EVENT_HISTORY_CHANGED = "historyChanged"; + private static final String EVENT_SCROLL_CHANGED = "scrollChanged"; + private static final String EVENT_NAVIGATION_REQUESTED = "navigationRequested"; + private static final String EVENT_NAVIGATION_BLOCKED = "navigationBlocked"; + private static final String EVENT_RESOURCE_ERROR = "resourceError"; + private static final String EVENT_HTTP_ERROR = "httpError"; + private static final String EVENT_SSL_ERROR = "sslError"; + private static final String EVENT_CONSOLE_MESSAGE = "consoleMessage"; + private static final String EVENT_JS_ALERT = "jsAlert"; + private static final String EVENT_JS_CONFIRM = "jsConfirm"; + private static final String EVENT_JS_PROMPT = "jsPrompt"; + private static final String EVENT_JS_BEFORE_UNLOAD = "jsBeforeUnload"; + private static final String EVENT_PERMISSION_REQUEST = "permissionRequest"; + private static final String EVENT_GEOLOCATION_PERMISSION = "geolocationPermissionRequest"; + private static final String EVENT_FULLSCREEN_CHANGED = "fullscreenChanged"; + private static final String EVENT_WINDOW_REQUESTED = "windowRequested"; + private static final String EVENT_DOWNLOAD_REQUESTED = "downloadRequested"; + private static final String EVENT_DOWNLOAD_STARTED = "downloadStarted"; + private static final String EVENT_DOWNLOAD_FAILED = "downloadFailed"; + private static final String EVENT_RENDER_PROCESS_GONE = "renderProcessGone"; + private static final String EVENT_READY = "ready"; + + private static final long SCROLL_EVENT_INTERVAL_MS = 80; + + /** + * Page-side messaging bridge. Installed at document start when the provider + * supports it, and re-injected on page started/finished as a fallback. It is + * idempotent, so the guard keeps callbacks registered by the page intact + * across injections. + */ + private static final String BRIDGE_JS = + "(function(){" + + "if(window.webview&&window.webview.__acodeBridge){return;}" + + "var callbacks=[];" + + "window.webview={" + + "__acodeBridge:true," + + "platform:'android'," + + "onMessage:function(cb){if(typeof cb==='function'){callbacks.push(cb);}}," + + "offMessage:function(cb){callbacks=callbacks.filter(function(c){return c!==cb;});}," + + "postMessage:function(msg){" + + "var data=(typeof msg==='string')?msg:JSON.stringify(msg);" + + "window.AcodeWebViewNative.postMessage(String(data));" + + "}," + + "_dispatch:function(msg){" + + "callbacks.slice().forEach(function(cb){try{cb(msg);}catch(e){console.error(e);}});" + + "}" + + "};" + + "})();"; + + final String id; + final WebViewOptions options; + final WebViewPlugin plugin; + + private WebView webView; + private WebViewActivity hostingActivity = null; + private boolean destroyed = false; + + /** Resolved WebView profile name, or null when isolation is unavailable. */ + private String profileName = null; + private Profile profile = null; + private boolean profileIsolated = false; + private boolean ephemeralProfile = false; + + private String pendingUrl = null; + private Map pendingHeaders = null; + private String pendingHtml = null; + private JSONObject pendingHtmlOptions = null; + + private String currentUrl = ""; + private String currentTitle = ""; + private int progress = 0; + private boolean loading = false; + + private View customView = null; + private WebChromeClient.CustomViewCallback customViewCallback = null; + private ScriptHandler documentStartScript = null; + private long lastScrollEventAt = 0L; + + WebViewInstance(String id, WebViewOptions options, WebViewPlugin plugin) { + this.id = id; + this.options = options; + this.plugin = plugin; + // Acquire the profile up front so isolation metadata is final before the + // (lazily created) fullscreen WebView exists. + acquireProfile(); + } + + public WebView getWebView() { + return webView; + } + + String getTitle() { + return options.title; + } + + boolean isFullscreen() { + return "fullscreen".equals(options.mode); + } + + boolean isIncognito() { + return options.incognito; + } + + boolean isIsolated() { + return profileIsolated; + } + + /** Resolved WebView profile name, or null when no profile is in use. */ + String getProfileName() { + return profileName; + } + + WebViewActivity getHostingActivity() { + return hostingActivity; + } + + void setHostingActivity(WebViewActivity activity) { + hostingActivity = activity; + } + + void clearHostingActivity(WebViewActivity activity) { + if (hostingActivity == activity) { + hostingActivity = null; + } + } + + /** + * Creates the native WebView. Idempotent: a recreated hosting activity reuses + * the existing WebView (and its page state) instead of leaking a new one. + */ + void createWebView(Activity activity) { + if (webView != null) return; + + webView = new ScrollAwareWebView(activity); + bindProfile(); + options.applyTo(webView, activity); + configureClients(activity); + installBridge(); + applyPendingContent(); + Payload ready = data() + .put("mode", options.mode) + .put("isolated", profileIsolated) + .put("profileName", profileName != null ? profileName : JSONObject.NULL); + emit(EVENT_READY, ready); + } + + /** True once the native WebView exists and can accept evaluate(). */ + boolean isReady() { + return webView != null && !destroyed; + } + + /** + * Resolves and acquires the WebView profile before any WebView exists. This + * makes {@link #isIsolated()} and {@link #getProfileName()} final at creation + * time, including for fullscreen instances whose WebView is created later. + */ + private void acquireProfile() { + String requested = options.profileName; + boolean explicit = requested != null && !requested.trim().isEmpty(); + + if (options.incognito) { + profileName = explicit ? requested.trim() : ProfileManager.ephemeralName(id); + ephemeralProfile = !explicit; + } else if (explicit) { + profileName = requested.trim(); + ephemeralProfile = false; + } + + if (profileName == null) return; + + profile = ProfileManager.acquire(profileName); + profileIsolated = profile != null; + if (!profileIsolated) { + // Multi-profile is unavailable on this provider. Fall back to + // best-effort incognito (no cache) without pretending to be isolated. + profileName = null; + ephemeralProfile = false; + } + } + + /** Binds the acquired profile to the freshly constructed WebView. */ + private void bindProfile() { + if (profile == null) return; + if (ProfileManager.bind(webView, profile)) return; + + // Binding failed: drop the reference and fall back to the non-isolated + // behaviour rather than leaking the profile. + ProfileManager.release(profileName, ephemeralProfile, false); + profile = null; + profileName = null; + ephemeralProfile = false; + profileIsolated = false; + } + + /** + * Cookie manager backing this instance. Isolated profiles use their own jar + * so downloads and other native requests never cross the profile boundary. + */ + CookieManager getCookieManager() { + try { + if (profile != null) { + CookieManager scoped = profile.getCookieManager(); + if (scoped != null) return scoped; + } + } catch (Throwable t) { + Log.w(TAG, "Could not access profile cookie manager", t); + } + return CookieManager.getInstance(); + } + + private void configureClients(Activity activity) { + webView.setWebViewClient(new InstanceWebViewClient()); + webView.setWebChromeClient(new InstanceWebChromeClient()); + webView.setFocusable(true); + webView.setFocusableInTouchMode(true); + webView.addJavascriptInterface(new JsBridge(), BRIDGE_NAME); + + if (options.allowDownloads) { + webView.setDownloadListener(new InstanceDownloadListener(activity)); + } + } + + private void installBridge() { + try { + if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) { + documentStartScript = WebViewCompat.addDocumentStartJavaScript( + webView, + BRIDGE_JS, + Collections.singleton("*") + ); + if (documentStartScript != null) return; + } + } catch (Throwable t) { + Log.w(TAG, "Document-start script unavailable; falling back to injection", t); + } + injectBridge(webView); + } + + private static void injectBridge(WebView view) { + view.evaluateJavascript(BRIDGE_JS, null); + } + + private void applyPendingContent() { + if (webView == null) return; + if (pendingUrl != null) { + String url = pendingUrl; + Map headers = pendingHeaders; + clearPending(); + if (headers != null && !headers.isEmpty()) { + webView.loadUrl(url, headers); + } else { + webView.loadUrl(url); + } + } else if (pendingHtml != null) { + String html = pendingHtml; + JSONObject htmlOptions = pendingHtmlOptions; + clearPending(); + loadHtmlNow(html, htmlOptions); + } + } + + private void clearPending() { + pendingUrl = null; + pendingHeaders = null; + pendingHtml = null; + pendingHtmlOptions = null; + } + + private void loadHtmlNow(String html, JSONObject htmlOptions) { + String baseUrl = null; + String mimeType = "text/html"; + String encoding = "UTF-8"; + String historyUrl = null; + + if (htmlOptions != null) { + baseUrl = sanitizeUrl(optString(htmlOptions, "baseUrl")); + mimeType = htmlOptions.optString("mimeType", mimeType); + encoding = htmlOptions.optString("encoding", encoding); + historyUrl = sanitizeUrl(optString(htmlOptions, "historyUrl")); + } + + webView.loadDataWithBaseURL(baseUrl, html, mimeType, encoding, historyUrl); + } + + // --------------------------------------------------------------------------- + // Page actions + // --------------------------------------------------------------------------- + + void loadURL(String url, JSONObject headers, final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + + final String safeUrl = sanitizeUrl(url); + if (safeUrl == null) { + callbackContext.error("Blocked URL: only http:// and https:// URLs are allowed"); + return; + } + + final Map headerMap = toStringMap(headers); + + if (webView == null) { + pendingUrl = safeUrl; + pendingHeaders = headerMap; + pendingHtml = null; + pendingHtmlOptions = null; + callbackContext.success(); + return; + } + + runOnUiThread(() -> { + if (headerMap != null && !headerMap.isEmpty()) { + webView.loadUrl(safeUrl, headerMap); + } else { + webView.loadUrl(safeUrl); + } + callbackContext.success(); + }); + } + + void loadHTML(String html, JSONObject htmlOptions, final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + + if (webView == null) { + pendingHtml = html; + pendingHtmlOptions = htmlOptions; + pendingUrl = null; + pendingHeaders = null; + callbackContext.success(); + return; + } + + runOnUiThread(() -> { + loadHtmlNow(html, htmlOptions); + callbackContext.success(); + }); + } + + void evaluate(String js, final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (rejectIfNotReady(callbackContext)) return; + + runOnUiThread(() -> webView.evaluateJavascript(js, value -> + callbackContext.success(decodeJsResult(value)) + )); + } + + /** + * evaluateJavascript() delivers the result as a JSON-encoded string. Decode + * it properly instead of stripping quotes by hand so escapes (newlines, + * unicode, quotes) survive the round trip. + */ + private static String decodeJsResult(String value) { + if (value == null) return null; + try { + Object parsed = new JSONTokener(value).nextValue(); + if (parsed == JSONObject.NULL) return null; + return String.valueOf(parsed); + } catch (JSONException e) { + return value; + } + } + + void postMessage(String message, final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (rejectIfNotReady(callbackContext)) return; + + // JSONObject.quote() produces a safe JS string literal for any input, so a + // malicious or sloppy payload cannot break out of the string and inject + // code into the page context. The page receives a parsed value for JSON + // payloads and the raw string otherwise. + final String js = + "(function(){" + + "var raw=" + JSONObject.quote(message) + ";" + + "var msg;try{msg=JSON.parse(raw);}catch(e){msg=raw;}" + + "if(window.webview&&window.webview._dispatch){window.webview._dispatch(msg);}" + + "})();"; + + runOnUiThread(() -> { + webView.evaluateJavascript(js, null); + callbackContext.success(); + }); + } + + void show(final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (!isFullscreen()) { + callbackContext.error( + "Hidden WebViews cannot be shown; use mode \"fullscreen\" to display content" + ); + return; + } + runOnUiThread(() -> plugin.showFullscreenActivity(id)); + callbackContext.success(); + } + + void hide(final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (!isFullscreen()) { + // A hidden (headless) WebView is already hidden. + callbackContext.success(); + return; + } + hideFullscreen(callbackContext); + } + + /** + * Hiding a fullscreen WebView moves its hosting activity (and its task) to + * the background. Nothing is destroyed, so show() brings the same WebView + * back with its page state intact. The instance is only destroyed when the + * user actually closes it (back button/task removal) or destroy() is called. + */ + private void hideFullscreen(CallbackContext callbackContext) { + runOnUiThread(() -> { + if (hostingActivity != null + && !hostingActivity.isFinishing() + && !hostingActivity.isDestroyed()) { + hostingActivity.moveTaskToBack(true); + } + }); + callbackContext.success(); + } + + void reload(final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (rejectIfNotReady(callbackContext)) return; + runOnUiThread(() -> { + webView.reload(); + callbackContext.success(); + }); + } + + void stopLoading(final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (rejectIfNotReady(callbackContext)) return; + runOnUiThread(() -> { + webView.stopLoading(); + callbackContext.success(); + }); + } + + void goBack(final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (rejectIfNotReady(callbackContext)) return; + runOnUiThread(() -> { + boolean moved = webView.canGoBack(); + if (moved) webView.goBack(); + sendBooleanResult(callbackContext, moved); + }); + } + + void goForward(final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (rejectIfNotReady(callbackContext)) return; + runOnUiThread(() -> { + boolean moved = webView.canGoForward(); + if (moved) webView.goForward(); + sendBooleanResult(callbackContext, moved); + }); + } + + void canGoBack(final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (rejectIfNotReady(callbackContext)) return; + runOnUiThread(() -> sendBooleanResult(callbackContext, webView.canGoBack())); + } + + void canGoForward(final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (rejectIfNotReady(callbackContext)) return; + runOnUiThread(() -> sendBooleanResult(callbackContext, webView.canGoForward())); + } + + void clearCache(final boolean includeDiskFiles, final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (rejectIfNotReady(callbackContext)) return; + runOnUiThread(() -> { + webView.clearCache(includeDiskFiles); + callbackContext.success(); + }); + } + + void clearHistory(final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (rejectIfNotReady(callbackContext)) return; + runOnUiThread(() -> { + webView.clearHistory(); + callbackContext.success(); + }); + } + + void clearFormData(final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + if (rejectIfNotReady(callbackContext)) return; + runOnUiThread(() -> { + webView.clearFormData(); + callbackContext.success(); + }); + } + + void setUserAgent(final String userAgent, final String mode, final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + + final JSONObject partial = new JSONObject(); + try { + partial.put("userAgent", userAgent != null ? userAgent : JSONObject.NULL); + if (mode != null && !mode.isEmpty()) { + partial.put("userAgentMode", mode); + } + } catch (JSONException e) { + callbackContext.error(e.getMessage()); + return; + } + + applySettings(partial, callbackContext); + } + + void getUserAgent(final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + runOnUiThread(() -> { + if (destroyed) { + callbackContext.error("WebView has been destroyed"); + return; + } + if (webView == null) { + // The WebView has not been created yet (fullscreen not shown); report + // the configured value instead of failing. + callbackContext.success(optString(options.settings(), "userAgent")); + return; + } + callbackContext.success(webView.getSettings().getUserAgentString()); + }); + } + + void updateSettings(final JSONObject partial, final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + applySettings(partial, callbackContext); + } + + /** + * Applies a settings batch on the UI thread — WebSettings and WebView methods + * must be touched there — and completes the callback once it is applied. + */ + private void applySettings(final JSONObject partial, final CallbackContext callbackContext) { + runOnUiThread(() -> { + if (destroyed) { + callbackContext.error("WebView has been destroyed"); + return; + } + try { + JSONObject settings = options.update(webView, appContext(), partial); + callbackContext.success(settings); + } catch (Exception e) { + callbackContext.error(e.getMessage()); + } + }); + } + + void getSettings(final CallbackContext callbackContext) { + if (rejectIfDestroyed(callbackContext)) return; + runOnUiThread(() -> { + if (destroyed) { + callbackContext.error("WebView has been destroyed"); + return; + } + callbackContext.success(options.settings()); + }); + } + + void getInfo(final CallbackContext callbackContext) { + try { + final JSONObject info = new JSONObject(); + info.put("id", id); + info.put("mode", options.mode); + info.put("incognito", options.incognito); + info.put("isolated", profileIsolated); + info.put("destroyed", destroyed); + info.put("ready", isReady()); + if (profileName != null) { + info.put("profileName", profileName); + } + info.put("url", currentUrl); + info.put("title", currentTitle); + info.put("progress", progress); + info.put("loading", loading); + info.put("canGoBack", false); + info.put("canGoForward", false); + info.put("userAgent", optString(options.settings(), "userAgent")); + + if (destroyed || webView == null) { + callbackContext.success(info); + return; + } + + runOnUiThread(() -> { + try { + String url = webView.getUrl(); + if (url != null) currentUrl = url; + String pageTitle = webView.getTitle(); + if (pageTitle != null) currentTitle = pageTitle; + info.put("url", currentUrl); + info.put("title", currentTitle); + info.put("canGoBack", webView.canGoBack()); + info.put("canGoForward", webView.canGoForward()); + info.put("userAgent", webView.getSettings().getUserAgentString()); + } catch (JSONException e) { + Log.w(TAG, "Could not build full WebView info", e); + } + callbackContext.success(info); + }); + } catch (JSONException e) { + callbackContext.error(e.getMessage()); + } + } + + // --------------------------------------------------------------------------- + // Lifecycle + // --------------------------------------------------------------------------- + + void destroy() { + if (destroyed) return; + destroyed = true; + + // Finish the hosting fullscreen activity, if any. Its onDestroy() calls + // destroy() again, which is a no-op now that destroyed is set. + WebViewActivity hosting = hostingActivity; + hostingActivity = null; + if (hosting != null && !hosting.isFinishing()) { + hosting.finish(); + } + + runOnUiThread(() -> { + exitCustomView(); + + if (documentStartScript != null) { + try { + documentStartScript.remove(); + } catch (Throwable t) { + Log.w(TAG, "Could not remove document-start script", t); + } + documentStartScript = null; + } + + if (webView != null) { + // On providers without multi-profile support, incognito can at least + // drop the shared HTTP cache and saved form data. + if (options.incognito && !profileIsolated) { + try { + webView.clearCache(true); + webView.clearFormData(); + } catch (Throwable t) { + Log.w(TAG, "Fallback incognito cleanup failed", t); + } + } + try { + if (webView.getParent() != null) { + ((ViewGroup) webView.getParent()).removeView(webView); + } + } catch (Throwable ignored) {} + try { + webView.removeJavascriptInterface(BRIDGE_NAME); + webView.setDownloadListener(null); + webView.setWebChromeClient(null); + webView.setWebViewClient(null); + webView.stopLoading(); + webView.loadUrl("about:blank"); + webView.destroy(); + } catch (Throwable t) { + Log.w(TAG, "Error destroying WebView", t); + } + } + webView = null; + + if (profileName != null) { + ProfileManager.release(profileName, ephemeralProfile, options.incognito); + profileName = null; + } + profile = null; + profileIsolated = false; + }); + } + + private void onPageFinished(WebView view) { + // Navigation replaced the page's JS context, so re-inject (no-op when the + // document-start script is already installed). + injectBridge(view); + String url = view.getUrl(); + currentUrl = url != null ? url : ""; + String pageTitle = view.getTitle(); + currentTitle = pageTitle != null ? pageTitle : ""; + loading = false; + emit(EVENT_PAGE_FINISHED, data() + .put("url", currentUrl) + .put("title", currentTitle)); + } + + private void onPageStarted(String url) { + currentUrl = url != null ? url : ""; + loading = true; + emit(EVENT_PAGE_STARTED, data().put("url", currentUrl)); + } + + private void onScrollChanged(int x, int y, int oldX, int oldY) { + long now = SystemClock.uptimeMillis(); + if (now - lastScrollEventAt < SCROLL_EVENT_INTERVAL_MS) return; + lastScrollEventAt = now; + emit(EVENT_SCROLL_CHANGED, data() + .put("scrollX", x) + .put("scrollY", y) + .put("oldScrollX", oldX) + .put("oldScrollY", oldY)); + } + + // --------------------------------------------------------------------------- + // Fullscreen custom views (video, canvas, …) + // --------------------------------------------------------------------------- + + void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) { + if (customView != null) { + callback.onCustomViewHidden(); + return; + } + customView = view; + customViewCallback = callback; + + WebViewActivity hosting = hostingActivity; + if (hosting == null || hosting.isFinishing()) { + // Headless instance: there is nowhere to render the view. Release it so + // the page is not left waiting. + exitCustomView(); + emit(EVENT_FULLSCREEN_CHANGED, data().put("fullscreen", true).put("supported", false)); + return; + } + + hosting.showCustomView(view); + emit(EVENT_FULLSCREEN_CHANGED, data().put("fullscreen", true).put("supported", true)); + } + + void onHideCustomView() { + if (customView == null) return; + exitCustomView(); + emit(EVENT_FULLSCREEN_CHANGED, data().put("fullscreen", false)); + } + + boolean isInCustomView() { + return customView != null; + } + + void exitCustomView() { + WebViewActivity hosting = hostingActivity; + if (hosting != null && !hosting.isFinishing()) { + hosting.hideCustomView(); + } + WebChromeClient.CustomViewCallback callback = customViewCallback; + customView = null; + customViewCallback = null; + if (callback != null) { + try { + callback.onCustomViewHidden(); + } catch (Throwable ignored) {} + } + } + + // --------------------------------------------------------------------------- + // Helpers + // --------------------------------------------------------------------------- + + /** + * Cordova's boolean callback overload is not available on every supported + * Android platform version, so send the boolean explicitly. + */ + private static void sendBooleanResult(CallbackContext callbackContext, boolean value) { + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, value)); + } + + private boolean rejectIfDestroyed(CallbackContext callbackContext) { + if (!destroyed) return false; + callbackContext.error("WebView has been destroyed"); + return true; + } + + private boolean rejectIfNotReady(CallbackContext callbackContext) { + if (webView != null) return false; + callbackContext.error("WebView is not ready"); + return true; + } + + private Context appContext() { + WebViewActivity hosting = hostingActivity; + if (hosting != null) return hosting; + WebView view = webView; + if (view != null) return view.getContext(); + return plugin.getContext(); + } + + private void emit(String event, Payload data) { + plugin.sendEventToCordova(id, event, data.json); + } + + private static Payload data() { + return new Payload(); + } + + /** + * Tiny fluent builder for event payloads. org.json's put() throws a checked + * exception; swallowing it here keeps the many event call sites readable. + */ + private static final class Payload { + final JSONObject json = new JSONObject(); + + Payload put(String key, Object value) { + try { + json.put(key, value); + } catch (JSONException e) { + Log.w(TAG, "Could not add \"" + key + "\" to event payload", e); + } + return this; + } + } + + void download(String url, String userAgent, String mimeType, String fileName) { + // Pass this instance so the download uses its profile-scoped cookie jar. + boolean started = plugin.download(this, url, userAgent, mimeType, fileName); + if (started) { + emit(EVENT_DOWNLOAD_STARTED, data() + .put("url", url) + .put("fileName", fileName) + .put("mimeType", mimeType)); + } else { + emit(EVENT_DOWNLOAD_FAILED, data().put("url", url).put("fileName", fileName)); + } + } + + private static void runOnUiThread(Runnable runnable) { + new Handler(Looper.getMainLooper()).post(runnable); + } + + private static Map toStringMap(JSONObject object) { + if (object == null || object.length() == 0) return null; + Map map = new HashMap<>(); + java.util.Iterator keys = object.keys(); + while (keys.hasNext()) { + String key = keys.next(); + Object value = object.opt(key); + if (value != null && value != JSONObject.NULL) { + map.put(key, String.valueOf(value)); + } + } + return map.isEmpty() ? null : map; + } + + private static String optString(JSONObject object, String key) { + if (object == null || !object.has(key) || object.isNull(key)) return null; + return object.optString(key, null); + } + + private static final Pattern SCHEME_PATTERN = + Pattern.compile("^([a-zA-Z][a-zA-Z0-9+\\-.]*)://"); + + /** + * Allows only http and https URLs, so hosted pages can never reach local + * files, app content providers or execute javascript: URLs. Input without a + * "scheme://" prefix ("example.com", "localhost:8080/page") is treated as a + * host and loaded over https; anything that is not clearly a URL degrades + * into a harmless failed https load. + */ + private static String sanitizeUrl(String url) { + if (url == null) return null; + String trimmed = url.trim(); + if (trimmed.isEmpty()) return null; + Matcher matcher = SCHEME_PATTERN.matcher(trimmed); + if (matcher.find()) { + String scheme = matcher.group(1); + if (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")) { + return trimmed; + } + return null; // file://, content://, intent://, etc. + } + return "https://" + trimmed; + } + + // --------------------------------------------------------------------------- + // Native WebView / client implementations + // --------------------------------------------------------------------------- + + /** Emits throttled scroll events; WebView does not expose a scroll listener. */ + private class ScrollAwareWebView extends WebView { + ScrollAwareWebView(Context context) { + super(context); + } + + @Override + protected void onScrollChanged(int l, int t, int oldl, int oldt) { + super.onScrollChanged(l, t, oldl, oldt); + WebViewInstance.this.onScrollChanged(l, t, oldl, oldt); + } + } + + private class InstanceWebViewClient extends WebViewClient { + + @Override + public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { + return handleNavigation(request.getUrl()); + } + + @SuppressWarnings("deprecation") + @Override + public boolean shouldOverrideUrlLoading(WebView view, String url) { + return handleNavigation(Uri.parse(url)); + } + + /** + * Blocks all navigation when allowNavigation is false. Even when it is + * true, only http(s) targets may load inside the WebView; other schemes + * (file:, content:, intent:, javascript:, tel:, ...) are blocked so hostile + * pages cannot escape the sandbox or launch other apps. Every decision is + * announced through navigationRequested/navigationBlocked. + */ + private boolean handleNavigation(Uri uri) { + String url = uri != null ? uri.toString() : ""; + String scheme = uri != null ? uri.getScheme() : null; + boolean httpScheme = scheme != null + && (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")); + boolean allowed = options.allowNavigation && httpScheme; + + emit(EVENT_NAVIGATION_REQUESTED, data().put("url", url).put("allowed", allowed)); + + if (!allowed) { + String reason = !options.allowNavigation ? "navigation-disabled" : "unsupported-scheme"; + emit(EVENT_NAVIGATION_BLOCKED, data().put("url", url).put("reason", reason)); + } + return !allowed; + } + + @Override + public void onPageStarted(WebView view, String url, Bitmap favicon) { + super.onPageStarted(view, url, favicon); + // Best effort fallback: gets the bridge in before the page's scripts run + // on providers without document-start script support. + injectBridge(view); + WebViewInstance.this.onPageStarted(url); + } + + @Override + public void onPageFinished(WebView view, String url) { + super.onPageFinished(view, url); + WebViewInstance.this.onPageFinished(view); + } + + @Override + public void onPageCommitVisible(WebView view, String url) { + super.onPageCommitVisible(view, url); + if (url != null) currentUrl = url; + emit(EVENT_PAGE_COMMIT_VISIBLE, data().put("url", url != null ? url : "")); + } + + @Override + public void onReceivedError( + WebView view, + WebResourceRequest request, + WebResourceError error + ) { + super.onReceivedError(view, request, error); + emit(EVENT_RESOURCE_ERROR, data() + .put("url", request.getUrl() != null ? request.getUrl().toString() : "") + .put("errorCode", error.getErrorCode()) + .put("description", String.valueOf(error.getDescription())) + .put("isForMainFrame", request.isForMainFrame())); + } + + @SuppressWarnings("deprecation") + @Override + public void onReceivedError( + WebView view, + int errorCode, + String description, + String failingUrl + ) { + super.onReceivedError(view, errorCode, description, failingUrl); + emit(EVENT_RESOURCE_ERROR, data() + .put("url", failingUrl != null ? failingUrl : "") + .put("errorCode", errorCode) + .put("description", description != null ? description : "") + .put("isForMainFrame", true)); + } + + @Override + public void onReceivedHttpError( + WebView view, + WebResourceRequest request, + WebResourceResponse errorResponse + ) { + super.onReceivedHttpError(view, request, errorResponse); + emit(EVENT_HTTP_ERROR, data() + .put("url", request.getUrl() != null ? request.getUrl().toString() : "") + .put("statusCode", errorResponse.getStatusCode()) + .put("reasonPhrase", errorResponse.getReasonPhrase() != null + ? errorResponse.getReasonPhrase() : "") + .put("isForMainFrame", request.isForMainFrame())); + } + + @Override + public void onReceivedSslError(WebView view, SslErrorHandler handler, android.net.http.SslError error) { + emit(EVENT_SSL_ERROR, data() + .put("url", error.getUrl() != null ? error.getUrl() : "") + .put("primaryError", error.getPrimaryError()) + .put("description", String.valueOf(error))); + // Never proceed past a certificate error. + handler.cancel(); + } + + @Override + public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { + super.doUpdateVisitedHistory(view, url, isReload); + emit(EVENT_HISTORY_CHANGED, data() + .put("url", url != null ? url : "") + .put("isReload", isReload) + .put("canGoBack", view.canGoBack()) + .put("canGoForward", view.canGoForward())); + } + + @Override + public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) { + boolean didCrash = detail != null && detail.didCrash(); + emit(EVENT_RENDER_PROCESS_GONE, data().put("didCrash", didCrash)); + // The WebView can no longer be used; tear the instance down. + plugin.removeInstance(id); + destroy(); + return true; + } + } + + private class InstanceWebChromeClient extends WebChromeClient { + + @Override + public void onProgressChanged(WebView view, int newProgress) { + super.onProgressChanged(view, newProgress); + progress = newProgress; + loading = newProgress < 100; + emit(EVENT_PROGRESS, data().put("progress", newProgress).put("url", currentUrl)); + } + + @Override + public void onReceivedTitle(WebView view, String pageTitle) { + super.onReceivedTitle(view, pageTitle); + currentTitle = pageTitle != null ? pageTitle : ""; + emit(EVENT_TITLE_CHANGED, data().put("title", currentTitle)); + } + + @Override + public void onReceivedIcon(WebView view, Bitmap icon) { + super.onReceivedIcon(view, icon); + Payload payload = data().put("url", currentUrl); + if (icon != null) { + payload.put("width", icon.getWidth()); + payload.put("height", icon.getHeight()); + } + emit(EVENT_FAVICON_CHANGED, payload); + } + + @Override + public boolean onConsoleMessage(ConsoleMessage consoleMessage) { + emit(EVENT_CONSOLE_MESSAGE, data() + .put("message", consoleMessage.message() != null ? consoleMessage.message() : "") + .put("level", consoleLevel(consoleMessage.messageLevel())) + .put("sourceId", consoleMessage.sourceId() != null ? consoleMessage.sourceId() : "") + .put("lineNumber", consoleMessage.lineNumber())); + return false; + } + + @Override + public boolean onJsAlert(WebView view, String url, String message, android.webkit.JsResult result) { + emit(EVENT_JS_ALERT, data().put("url", url).put("message", message)); + return false; // Let the WebView show its default dialog. + } + + @Override + public boolean onJsConfirm(WebView view, String url, String message, android.webkit.JsResult result) { + emit(EVENT_JS_CONFIRM, data().put("url", url).put("message", message)); + return false; + } + + @Override + public boolean onJsPrompt( + WebView view, + String url, + String message, + String defaultValue, + android.webkit.JsPromptResult result + ) { + emit(EVENT_JS_PROMPT, data() + .put("url", url) + .put("message", message) + .put("defaultValue", defaultValue != null ? defaultValue : "")); + return false; + } + + @Override + public boolean onJsBeforeUnload( + WebView view, + String url, + String message, + android.webkit.JsResult result + ) { + emit(EVENT_JS_BEFORE_UNLOAD, data().put("url", url).put("message", message)); + return false; + } + + @Override + public void onPermissionRequest(final PermissionRequest request) { + Payload payload = data(); + payload.put("origin", request.getOrigin() != null ? request.getOrigin().toString() : ""); + payload.put( + "resources", + new org.json.JSONArray(java.util.Arrays.asList(request.getResources())) + ); + emit(EVENT_PERMISSION_REQUEST, payload); + // Deny by default: hosted content never gets camera/mic/etc. implicitly. + request.deny(); + } + + @Override + public void onGeolocationPermissionsShowPrompt( + String origin, + GeolocationPermissions.Callback callback + ) { + emit(EVENT_GEOLOCATION_PERMISSION, data().put("origin", origin != null ? origin : "")); + boolean allow = options.settings().optBoolean("geolocation", false); + callback.invoke(origin, allow, false); + } + + @Override + public void onShowCustomView(View view, CustomViewCallback callback) { + WebViewInstance.this.onShowCustomView(view, callback); + } + + @Override + public void onHideCustomView() { + WebViewInstance.this.onHideCustomView(); + } + + @Override + public boolean onCreateWindow( + WebView view, + boolean isDialog, + boolean isUserGesture, + android.os.Message resultMsg + ) { + // Popups are not supported; announce and let the page keep running. + emit(EVENT_WINDOW_REQUESTED, data().put("url", view.getUrl() != null ? view.getUrl() : "")); + return false; + } + } + + private static String consoleLevel(ConsoleMessage.MessageLevel level) { + if (level == null) return "log"; + switch (level) { + case TIP: + return "tip"; + case LOG: + return "log"; + case WARNING: + return "warning"; + case ERROR: + return "error"; + case DEBUG: + return "debug"; + default: + return "log"; + } + } + + private class InstanceDownloadListener implements DownloadListener { + private final Context context; + + InstanceDownloadListener(Context context) { + this.context = context; + } + + @Override + public void onDownloadStart( + final String url, + final String userAgent, + String contentDisposition, + final String mimeType, + long contentLength + ) { + if (destroyed) return; + if (context instanceof Activity && ((Activity) context).isFinishing()) return; + + // DownloadManager can only fetch http(s) URLs. + String scheme = Uri.parse(url).getScheme(); + if (scheme == null + || !(scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https"))) { + runOnUiThread(() -> Toast.makeText( + context, + "This download type is not supported", + Toast.LENGTH_SHORT + ).show()); + return; + } + + final String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType); + String size = formatSize(contentLength); + + emit(EVENT_DOWNLOAD_REQUESTED, data() + .put("url", url) + .put("fileName", fileName) + .put("mimeType", mimeType != null ? mimeType : "") + .put("contentLength", contentLength) + .put("userAgent", userAgent != null ? userAgent : "") + .put("contentDisposition", contentDisposition != null ? contentDisposition : "")); + + final String message = size.isEmpty() + ? "Do you want to download \"" + fileName + "\"?" + : "Do you want to download \"" + fileName + "\" (" + size + ")?"; + + runOnUiThread(() -> new AlertDialog.Builder(context) + .setTitle("Download file") + .setMessage(message) + .setPositiveButton("Download", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + WebViewInstance.this.download(url, userAgent, mimeType, fileName); + } + }) + .setNegativeButton("Cancel", null) + .show()); + } + } + + private static String formatSize(long bytes) { + if (bytes <= 0) return ""; + if (bytes < 1024) return bytes + " B"; + if (bytes < 1024 * 1024) return String.format(Locale.US, "%.1f KB", bytes / 1024.0); + if (bytes < 1024L * 1024 * 1024) { + return String.format(Locale.US, "%.1f MB", bytes / (1024.0 * 1024)); + } + return String.format(Locale.US, "%.1f GB", bytes / (1024.0 * 1024 * 1024)); + } + + /** + * Pads the view so content stays clear of the status and navigation bars. + * Required on API 35+ where edge-to-edge is enforced for the app; on older + * versions the window usually consumes the insets first, making the padding + * zero and this a no-op. + */ + @SuppressWarnings("deprecation") + static void applySystemBarInsets(final View view) { + view.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() { + @Override + public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) { + int left, top, right, bottom; + if (Build.VERSION.SDK_INT >= 30) { + Insets bars = insets.getInsets(WindowInsets.Type.systemBars()); + left = bars.left; + top = bars.top; + right = bars.right; + bottom = bars.bottom; + } else { + left = insets.getSystemWindowInsetLeft(); + top = insets.getSystemWindowInsetTop(); + right = insets.getSystemWindowInsetRight(); + bottom = insets.getSystemWindowInsetBottom(); + } + v.setPadding(left, top, right, bottom); + return insets; + } + }); + } + + public class JsBridge { + @JavascriptInterface + public void postMessage(String message) { + plugin.sendMessageToCordova(id, message); + } + } +} diff --git a/src/plugins/webview/src/android/com/foxdebug/webview/WebViewOptions.java b/src/plugins/webview/src/android/com/foxdebug/webview/WebViewOptions.java new file mode 100644 index 0000000000..a2ea79216f --- /dev/null +++ b/src/plugins/webview/src/android/com/foxdebug/webview/WebViewOptions.java @@ -0,0 +1,537 @@ +package com.foxdebug.webview; + +import android.content.Context; +import android.graphics.Color; +import android.util.Log; +import android.webkit.CookieManager; +import android.webkit.WebSettings; +import android.webkit.WebView; +import androidx.webkit.WebSettingsCompat; +import androidx.webkit.WebViewFeature; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import org.json.JSONObject; + +/** + * Configuration for a {@link WebViewInstance}. + * + *

Behavioural options (mode, title, visibility, isolation) are kept as typed + * fields. Web settings are kept in a normalized {@link JSONObject} so they can + * be merged on partial updates and handed back to the caller verbatim. + * + *

Only a known allow-list of settings is ever read, so a caller cannot + * switch on file/content access or otherwise break the navigation sandbox. + * Those stay pinned to the isolation-safe defaults in {@link #applyPartial}. + */ +final class WebViewOptions { + + private static final String TAG = "WebViewOptions"; + + static final String DEFAULT_MODE = "hidden"; + static final String DEFAULT_USER_AGENT_MODE = "default"; + static final String DEFAULT_CACHE_MODE = "default"; + static final String DEFAULT_MIXED_CONTENT_MODE = "never-allow"; + static final String DEFAULT_ALGORITHMIC_DARKENING = "auto"; + + /** Settings that may be changed at runtime through updateSettings(). */ + private static final Set SETTING_KEYS = new HashSet<>(Arrays.asList( + "userAgent", + "userAgentMode", + "javaScript", + "domStorage", + "databaseStorage", + "cacheMode", + "mediaPlaybackRequiresUserGesture", + "loadImages", + "mixedContentMode", + "textZoom", + "initialScale", + "useWideViewPort", + "loadWithOverviewMode", + "supportZoom", + "builtInZoomControls", + "displayZoomControls", + "geolocation", + "safeBrowsing", + "algorithmicDarkening", + "acceptThirdPartyCookies", + "backgroundColor" + )); + + final String mode; + final String title; + final boolean visible; + final boolean incognito; + final String profileName; + final boolean allowNavigation; + final boolean allowDownloads; + + /** Normalized, complete web-settings snapshot. */ + private final JSONObject values; + + private WebViewOptions( + String mode, + String title, + boolean visible, + boolean incognito, + String profileName, + boolean allowNavigation, + boolean allowDownloads, + JSONObject values + ) { + this.mode = mode; + this.title = title; + this.visible = visible; + this.incognito = incognito; + this.profileName = profileName; + this.allowNavigation = allowNavigation; + this.allowDownloads = allowDownloads; + this.values = values; + } + + static WebViewOptions fromJson(JSONObject input) { + JSONObject source = input != null ? input : new JSONObject(); + + String mode = source.optString("mode", DEFAULT_MODE); + if (!"fullscreen".equals(mode) && !"hidden".equals(mode)) { + throw new IllegalArgumentException( + "Unsupported WebView mode: \"" + mode + "\". Use \"fullscreen\" or \"hidden\"." + ); + } + + String userAgentMode = source.optString("userAgentMode", DEFAULT_USER_AGENT_MODE); + if (!"default".equals(userAgentMode) + && !"mobile".equals(userAgentMode) + && !"desktop".equals(userAgentMode)) { + throw new IllegalArgumentException( + "Unsupported userAgentMode: \"" + userAgentMode + + "\". Use \"default\", \"mobile\" or \"desktop\"." + ); + } + + boolean incognito = source.optBoolean("incognito", false); + + // Profile names are used verbatim; reject non-canonical input instead of + // rewriting it so two different names can never select the same profile. + String profileName = optString(source, "profileName"); + if (profileName != null) { + ProfileManager.requireValidUserName(profileName); + } + + JSONObject values = defaults(incognito); + merge(values, source); + clampSettings(values); + validateEnums(values); + + return new WebViewOptions( + mode, + source.optString("title", ""), + source.optBoolean("visible", true), + incognito, + profileName, + source.optBoolean("allowNavigation", true), + source.optBoolean("allowDownloads", false), + values + ); + } + + /** Full settings snapshot including behavioural keys, for the JS layer. */ + JSONObject toJson() { + JSONObject out = copy(values); + putQuietly(out, "mode", mode); + putQuietly(out, "title", title); + putQuietly(out, "visible", visible); + putQuietly(out, "incognito", incognito); + if (profileName != null) { + putQuietly(out, "profileName", profileName); + } + putQuietly(out, "allowNavigation", allowNavigation); + putQuietly(out, "allowDownloads", allowDownloads); + return out; + } + + private static JSONObject defaults(boolean incognito) { + JSONObject values = new JSONObject(); + putQuietly(values, "userAgent", JSONObject.NULL); + putQuietly(values, "userAgentMode", DEFAULT_USER_AGENT_MODE); + putQuietly(values, "javaScript", true); + putQuietly(values, "domStorage", true); + putQuietly(values, "databaseStorage", false); + putQuietly(values, "cacheMode", incognito ? "no-cache" : DEFAULT_CACHE_MODE); + putQuietly(values, "mediaPlaybackRequiresUserGesture", true); + putQuietly(values, "loadImages", true); + putQuietly(values, "mixedContentMode", DEFAULT_MIXED_CONTENT_MODE); + putQuietly(values, "textZoom", 100); + putQuietly(values, "initialScale", 0); + putQuietly(values, "useWideViewPort", true); + putQuietly(values, "loadWithOverviewMode", true); + putQuietly(values, "supportZoom", true); + putQuietly(values, "builtInZoomControls", false); + putQuietly(values, "displayZoomControls", false); + putQuietly(values, "geolocation", false); + putQuietly(values, "safeBrowsing", true); + putQuietly(values, "algorithmicDarkening", DEFAULT_ALGORITHMIC_DARKENING); + putQuietly(values, "acceptThirdPartyCookies", incognito ? false : JSONObject.NULL); + putQuietly(values, "backgroundColor", JSONObject.NULL); + return values; + } + + private static void validateEnums(JSONObject values) { + String cacheMode = values.optString("cacheMode", DEFAULT_CACHE_MODE); + if (!"default".equals(cacheMode) + && !"no-cache".equals(cacheMode) + && !"cache-only".equals(cacheMode) + && !"cache-else-network".equals(cacheMode)) { + throw new IllegalArgumentException( + "Unsupported cacheMode: \"" + cacheMode + + "\". Use \"default\", \"no-cache\", \"cache-only\" or \"cache-else-network\"." + ); + } + + String mixed = values.optString("mixedContentMode", DEFAULT_MIXED_CONTENT_MODE); + if (!"never-allow".equals(mixed) + && !"compatibility".equals(mixed) + && !"always-allow".equals(mixed)) { + throw new IllegalArgumentException( + "Unsupported mixedContentMode: \"" + mixed + + "\". Use \"never-allow\", \"compatibility\" or \"always-allow\"." + ); + } + + String darkening = values.optString("algorithmicDarkening", DEFAULT_ALGORITHMIC_DARKENING); + if (!"auto".equals(darkening) && !"on".equals(darkening) && !"off".equals(darkening)) { + throw new IllegalArgumentException( + "Unsupported algorithmicDarkening: \"" + darkening + + "\". Use \"auto\", \"on\" or \"off\"." + ); + } + + String userAgentMode = values.optString("userAgentMode", DEFAULT_USER_AGENT_MODE); + if (!"default".equals(userAgentMode) + && !"mobile".equals(userAgentMode) + && !"desktop".equals(userAgentMode)) { + throw new IllegalArgumentException( + "Unsupported userAgentMode: \"" + userAgentMode + + "\". Use \"default\", \"mobile\" or \"desktop\"." + ); + } + } + + private static void clampSettings(JSONObject values) { + if (values.has("textZoom")) { + putQuietly(values, "textZoom", clamp(values.optInt("textZoom", 100), 25, 500)); + } + if (values.has("initialScale")) { + putQuietly(values, "initialScale", clamp(values.optInt("initialScale", 0), 0, 1000)); + } + } + + /** Applies every setting in this snapshot to a freshly created WebView. */ + void applyTo(WebView view, Context context) { + applyPartial(view, context, values); + } + + /** + * Merges (and applies) a partial settings object. Unknown keys are ignored, + * isolation-critical settings are always forced, and the resulting normalized + * settings are returned. + */ + JSONObject update(WebView view, Context context, JSONObject partial) { + JSONObject applied = new JSONObject(); + if (partial != null) { + for (String key : SETTING_KEYS) { + if (partial.has(key)) { + putQuietly(applied, key, partial.opt(key)); + } + } + } + + validateEnums(mergeIntoSnapshot(applied)); + clampSettings(applied); + // A fullscreen instance may not have created its WebView yet; merge now so + // the settings apply when createWebView() runs. + if (view != null) { + applyPartial(view, context, settingsToApply(applied), true); + } + merge(values, applied); + if (applied.has("userAgentMode") && !applied.has("userAgent")) { + // The mode now decides the UA; drop any stale explicit override. + putQuietly(values, "userAgent", JSONObject.NULL); + } + return copy(values); + } + + /** + * A batch that sets or clears the explicit user agent without repeating the + * mode must resolve the preset from the current snapshot. Otherwise clearing + * a custom UA would fall back to "default" and silently undo a saved + * "desktop" (or "mobile") preset. + */ + private JSONObject settingsToApply(JSONObject applied) { + if (!applied.has("userAgent") || applied.has("userAgentMode")) { + return applied; + } + JSONObject effective = copy(applied); + putQuietly( + effective, + "userAgentMode", + values.optString("userAgentMode", DEFAULT_USER_AGENT_MODE) + ); + return effective; + } + + private JSONObject mergeIntoSnapshot(JSONObject partial) { + JSONObject merged = copy(values); + merge(merged, partial); + return merged; + } + + /** Current normalized settings snapshot. */ + JSONObject settings() { + return copy(values); + } + + /** + * Single source of truth for translating options into {@link WebSettings} + * calls. Only keys present in {@code source} are touched, so the same method + * serves both initial creation and runtime updates. + */ + static void applyPartial(WebView view, Context context, JSONObject source) { + applyPartial(view, context, source, false); + } + + private static void applyPartial( + WebView view, + Context context, + JSONObject source, + boolean runtimeUpdate + ) { + WebSettings settings = view.getSettings(); + + // Isolation is not configurable: hosted content must never be able to + // reach app/device data, and navigation below only permits http(s). + settings.setAllowFileAccess(false); + settings.setAllowContentAccess(false); + setFileUrlAccessFlags(settings); + settings.setSaveFormData(false); + settings.setSupportMultipleWindows(false); + settings.setJavaScriptCanOpenWindowsAutomatically(false); + + if (source.has("javaScript")) { + settings.setJavaScriptEnabled(source.optBoolean("javaScript", true)); + } + if (source.has("domStorage")) { + settings.setDomStorageEnabled(source.optBoolean("domStorage", true)); + } + if (source.has("databaseStorage")) { + settings.setDatabaseEnabled(source.optBoolean("databaseStorage", false)); + } + if (source.has("cacheMode")) { + settings.setCacheMode(cacheMode(source.optString("cacheMode", DEFAULT_CACHE_MODE))); + } + if (source.has("mediaPlaybackRequiresUserGesture")) { + settings.setMediaPlaybackRequiresUserGesture( + source.optBoolean("mediaPlaybackRequiresUserGesture", true) + ); + } + if (source.has("loadImages")) { + boolean loadImages = source.optBoolean("loadImages", true); + settings.setLoadsImagesAutomatically(loadImages); + settings.setBlockNetworkImage(!loadImages); + } + if (source.has("mixedContentMode")) { + settings.setMixedContentMode( + mixedContentMode(source.optString("mixedContentMode", DEFAULT_MIXED_CONTENT_MODE)) + ); + } + if (source.has("textZoom")) { + settings.setTextZoom(clamp(source.optInt("textZoom", 100), 25, 500)); + } + if (source.has("useWideViewPort")) { + settings.setUseWideViewPort(source.optBoolean("useWideViewPort", true)); + } + if (source.has("loadWithOverviewMode")) { + settings.setLoadWithOverviewMode(source.optBoolean("loadWithOverviewMode", true)); + } + if (source.has("supportZoom")) { + settings.setSupportZoom(source.optBoolean("supportZoom", true)); + } + if (source.has("builtInZoomControls")) { + settings.setBuiltInZoomControls(source.optBoolean("builtInZoomControls", false)); + } + if (source.has("displayZoomControls")) { + settings.setDisplayZoomControls(source.optBoolean("displayZoomControls", false)); + } + if (source.has("initialScale")) { + view.setInitialScale(clamp(source.optInt("initialScale", 0), 0, 1000)); + } + if (source.has("geolocation")) { + settings.setGeolocationEnabled(source.optBoolean("geolocation", false)); + } + if (source.has("acceptThirdPartyCookies")) { + if (!source.isNull("acceptThirdPartyCookies")) { + CookieManager.getInstance().setAcceptThirdPartyCookies( + view, + source.optBoolean("acceptThirdPartyCookies", false) + ); + } + } + if (source.has("safeBrowsing")) { + applyFeatureSafely("safeBrowsing", () -> { + if (WebViewFeature.isFeatureSupported(WebViewFeature.SAFE_BROWSING_ENABLE)) { + WebSettingsCompat.setSafeBrowsingEnabled( + settings, + source.optBoolean("safeBrowsing", true) + ); + } + }); + } + if (source.has("algorithmicDarkening")) { + String darkening = source.optString("algorithmicDarkening", DEFAULT_ALGORITHMIC_DARKENING); + if (!"auto".equals(darkening)) { + applyFeatureSafely("algorithmicDarkening", () -> { + if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) { + WebSettingsCompat.setAlgorithmicDarkeningAllowed(settings, "on".equals(darkening)); + } + }); + } + } + if (source.has("backgroundColor")) { + applyBackgroundColor(view, source); + } + // User agent is applied last so callers can override preset handling with + // an explicit string in the same batch. + if (source.has("userAgent") || source.has("userAgentMode")) { + resolveUserAgent(context, settings, source); + } + + if (runtimeUpdate) { + Log.d(TAG, "Applied runtime settings update"); + } + } + + private static void applyBackgroundColor(WebView view, JSONObject source) { + if (source.isNull("backgroundColor")) return; + String value = source.optString("backgroundColor", ""); + if (value == null || value.isEmpty()) return; + try { + view.setBackgroundColor(Color.parseColor(value)); + } catch (IllegalArgumentException e) { + Log.w(TAG, "Ignoring invalid backgroundColor: " + value); + } + } + + /** + * Resolves the user agent from either an explicit string or a preset mode. + * "desktop" is the platform default with the Mobile token removed; "mobile" + * restores the platform default; "default" clears any override. + */ + static String resolveUserAgent(Context context, WebSettings settings, JSONObject source) { + String explicit = optString(source, "userAgent"); + String mode = source.optString("userAgentMode", DEFAULT_USER_AGENT_MODE); + String result; + + if (explicit != null && !explicit.trim().isEmpty()) { + result = explicit.trim(); + } else if ("desktop".equals(mode)) { + result = desktopUserAgent(context); + } else if ("mobile".equals(mode)) { + result = WebSettings.getDefaultUserAgent(context); + } else { + result = null; + } + + settings.setUserAgentString(result); + String applied = settings.getUserAgentString(); + return applied != null ? applied : ""; + } + + private static String desktopUserAgent(Context context) { + String ua = WebSettings.getDefaultUserAgent(context); + if (ua == null) return null; + return ua.replace(" Mobile", "").replace("; wv", ""); + } + + static int cacheMode(String value) { + switch (value == null ? DEFAULT_CACHE_MODE : value) { + case "no-cache": + return WebSettings.LOAD_NO_CACHE; + case "cache-only": + return WebSettings.LOAD_CACHE_ONLY; + case "cache-else-network": + return WebSettings.LOAD_CACHE_ELSE_NETWORK; + default: + return WebSettings.LOAD_DEFAULT; + } + } + + static int mixedContentMode(String value) { + switch (value == null ? DEFAULT_MIXED_CONTENT_MODE : value) { + case "always-allow": + return WebSettings.MIXED_CONTENT_ALWAYS_ALLOW; + case "compatibility": + return WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE; + default: + return WebSettings.MIXED_CONTENT_NEVER_ALLOW; + } + } + + interface ThrowingRunnable { + void run() throws Exception; + } + + private static void applyFeatureSafely(String feature, ThrowingRunnable action) { + try { + action.run(); + } catch (Exception e) { + // Feature probes can throw on some WebView providers; a missing optional + // feature must never fail instance creation. + Log.w(TAG, "Could not apply " + feature + ": " + e.getMessage()); + } + } + + @SuppressWarnings("deprecation") + private static void setFileUrlAccessFlags(WebSettings settings) { + settings.setAllowFileAccessFromFileURLs(false); + settings.setAllowUniversalAccessFromFileURLs(false); + } + + private static int clamp(int value, int min, int max) { + return Math.max(min, Math.min(max, value)); + } + + private static String optString(JSONObject object, String key) { + if (object == null || !object.has(key) || object.isNull(key)) return null; + return object.optString(key, null); + } + + private static void putQuietly(JSONObject object, String key, Object value) { + try { + object.put(key, value); + } catch (Exception e) { + Log.w(TAG, "Could not set option " + key, e); + } + } + + private static void merge(JSONObject target, JSONObject source) { + if (source == null) return; + for (String key : SETTING_KEYS) { + if (source.has(key)) { + putQuietly(target, key, source.opt(key)); + } + } + } + + private static JSONObject copy(JSONObject source) { + JSONObject out = new JSONObject(); + if (source == null) return out; + // Android's org.json exposes keys() (Iterator), not keySet(). + java.util.Iterator keys = source.keys(); + while (keys.hasNext()) { + String key = keys.next(); + putQuietly(out, key, source.opt(key)); + } + return out; + } +} diff --git a/src/plugins/webview/src/android/com/foxdebug/webview/WebViewPlugin.java b/src/plugins/webview/src/android/com/foxdebug/webview/WebViewPlugin.java new file mode 100644 index 0000000000..068134d29a --- /dev/null +++ b/src/plugins/webview/src/android/com/foxdebug/webview/WebViewPlugin.java @@ -0,0 +1,528 @@ +package com.foxdebug.webview; + +import android.app.DownloadManager; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.Environment; +import android.util.Log; +import android.webkit.CookieManager; +import android.widget.Toast; +import androidx.webkit.WebViewFeature; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.UUID; +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.PluginResult; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Cordova entry point for the Acode WebView API. + * + *

Owns the instance registry, routes each JS call to the matching + * {@link WebViewInstance}, and forwards page/lifecycle events back over the + * single long-lived "setMessageCallback" channel. + */ +public class WebViewPlugin extends CordovaPlugin { + + private static final String TAG = "AcodeWebView"; + private static final String PLUGIN_VERSION = "2.0.0"; + private static WebViewPlugin instance; + + private final HashMap instances = new HashMap<>(); + private CallbackContext messageCallback; + + @Override + protected void pluginInitialize() { + instance = this; + // Remove incognito profiles left behind if the process was killed before + // their instance could be destroyed. + ProfileManager.cleanupEphemeralProfiles(); + } + + public static WebViewPlugin getInstance() { + return instance; + } + + @Override + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { + try { + switch (action) { + case "setMessageCallback": + setMessageCallback(callbackContext); + return true; + case "capabilities": + callbackContext.success(capabilities()); + return true; + case "create": + create(args.optJSONObject(0), callbackContext); + return true; + case "loadURL": + loadURL(args.getString(0), optionalString(args, 1), args.optJSONObject(2), callbackContext); + return true; + case "loadHTML": + loadHTML(args.getString(0), args.getString(1), args.optJSONObject(2), callbackContext); + return true; + case "evaluate": + evaluate(args.getString(0), args.getString(1), callbackContext); + return true; + case "postMessage": + postMessage(args.getString(0), args.getString(1), callbackContext); + return true; + case "show": + show(args.getString(0), callbackContext); + return true; + case "hide": + hide(args.getString(0), callbackContext); + return true; + case "reload": + reload(args.getString(0), callbackContext); + return true; + case "stopLoading": + stopLoading(args.getString(0), callbackContext); + return true; + case "goBack": + goBack(args.getString(0), callbackContext); + return true; + case "goForward": + goForward(args.getString(0), callbackContext); + return true; + case "canGoBack": + canGoBack(args.getString(0), callbackContext); + return true; + case "canGoForward": + canGoForward(args.getString(0), callbackContext); + return true; + case "clearCache": + clearCache(args.getString(0), args.optBoolean(1, true), callbackContext); + return true; + case "clearHistory": + clearHistory(args.getString(0), callbackContext); + return true; + case "clearFormData": + clearFormData(args.getString(0), callbackContext); + return true; + case "setUserAgent": + setUserAgent( + args.getString(0), + optionalString(args, 1), + optionalString(args, 2), + callbackContext + ); + return true; + case "getUserAgent": + getUserAgent(args.getString(0), callbackContext); + return true; + case "updateSettings": + updateSettings(args.getString(0), args.optJSONObject(1), callbackContext); + return true; + case "getSettings": + getSettings(args.getString(0), callbackContext); + return true; + case "getInfo": + getInfo(args.getString(0), callbackContext); + return true; + case "destroy": + destroy(args.getString(0), callbackContext); + return true; + default: + callbackContext.error("Unknown action: " + action); + return true; + } + } catch (Exception e) { + Log.e(TAG, "Error handling action: " + action, e); + callbackContext.error(e.getMessage()); + } + return true; + } + + private void setMessageCallback(CallbackContext callbackContext) { + this.messageCallback = callbackContext; + PluginResult keepResult = new PluginResult(PluginResult.Status.NO_RESULT); + keepResult.setKeepCallback(true); + callbackContext.sendPluginResult(keepResult); + } + + /** + * Reads an optional string argument, mapping JSON null/missing to Java null. + * Android's {@code JSONArray.optString(index, fallback)} returns the literal + * string "null" for a JSON null value, which would otherwise leak into + * options such as the user agent. + */ + private static String optionalString(JSONArray args, int index) { + if (args == null || args.isNull(index)) return null; + return args.optString(index, null); + } + + private String generateId() { + return "wv_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12); + } + + private void create(final JSONObject rawOptions, final CallbackContext callbackContext) { + final WebViewOptions options; + try { + options = WebViewOptions.fromJson(rawOptions); + } catch (IllegalArgumentException e) { + callbackContext.error(e.getMessage()); + return; + } + + final String id = generateId(); + + cordova.getActivity().runOnUiThread(() -> { + WebViewInstance instance = new WebViewInstance(id, options, WebViewPlugin.this); + instances.put(id, instance); + + try { + if (instance.isFullscreen()) { + // The WebView is created lazily by WebViewActivity. When the caller + // asked for an initially hidden instance, the launch is deferred + // until show() is called. + if (options.visible) { + showFullscreenActivity(id); + } + } else { + // "hidden" mode: a headless WebView that is never displayed. + instance.createWebView(cordova.getActivity()); + } + + JSONObject result = new JSONObject(); + result.put("id", id); + result.put("isolated", instance.isIsolated()); + result.put("ready", instance.isReady()); + if (instance.getProfileName() != null) { + result.put("profileName", instance.getProfileName()); + } + JSONObject resolvedOptions = options.toJson(); + if (!instance.isIsolated()) { + // The requested profile was not acquired (unsupported provider or a + // failed bind); do not report a profile name that is not in use. + resolvedOptions.remove("profileName"); + } + result.put("options", resolvedOptions); + result.put("capabilities", capabilities()); + callbackContext.success(result); + } catch (Exception e) { + instances.remove(id); + try { + instance.destroy(); + } catch (Exception ignored) {} + Log.e(TAG, "Create error: " + e.getMessage(), e); + callbackContext.error(e.getMessage()); + } + }); + } + + /** + * Shows a fullscreen WebView: launches its hosting activity, or brings the + * existing one back to the front if it is still alive (e.g. after hide() + * backgrounded it), preserving the WebView's page state. + */ + void showFullscreenActivity(String id) { + Intent intent = new Intent(cordova.getActivity(), WebViewActivity.class); + intent.putExtra("webviewId", id); + WebViewInstance target = getInstance(id); + WebViewActivity hosting = target != null ? target.getHostingActivity() : null; + if (hosting != null && !hosting.isFinishing() && !hosting.isDestroyed()) { + intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); + } + cordova.getActivity().startActivity(intent); + } + + public WebViewInstance getInstance(String id) { + return instances.get(id); + } + + public void removeInstance(String id) { + instances.remove(id); + } + + /** Context used for options that need a Context even before the WebView exists. */ + public Context getContext() { + return cordova.getContext(); + } + + private WebViewInstance requireInstance(String id, CallbackContext callbackContext) { + WebViewInstance instance = getInstance(id); + if (instance == null) { + callbackContext.error("WebView not found: " + id); + } + return instance; + } + + private void loadURL( + String id, + String url, + JSONObject headers, + CallbackContext callbackContext + ) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.loadURL(url, headers, callbackContext); + } + + private void loadHTML( + String id, + String html, + JSONObject htmlOptions, + CallbackContext callbackContext + ) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.loadHTML(html, htmlOptions, callbackContext); + } + + private void evaluate(String id, String js, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.evaluate(js, callbackContext); + } + + private void postMessage(String id, String message, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.postMessage(message, callbackContext); + } + + private void show(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.show(callbackContext); + } + + private void hide(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.hide(callbackContext); + } + + private void reload(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.reload(callbackContext); + } + + private void stopLoading(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.stopLoading(callbackContext); + } + + private void goBack(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.goBack(callbackContext); + } + + private void goForward(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.goForward(callbackContext); + } + + private void canGoBack(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.canGoBack(callbackContext); + } + + private void canGoForward(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.canGoForward(callbackContext); + } + + private void clearCache(String id, boolean includeDiskFiles, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.clearCache(includeDiskFiles, callbackContext); + } + + private void clearHistory(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.clearHistory(callbackContext); + } + + private void clearFormData(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.clearFormData(callbackContext); + } + + private void setUserAgent( + String id, + String userAgent, + String mode, + CallbackContext callbackContext + ) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.setUserAgent(userAgent, mode, callbackContext); + } + + private void getUserAgent(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.getUserAgent(callbackContext); + } + + private void updateSettings(String id, JSONObject settings, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.updateSettings(settings, callbackContext); + } + + private void getSettings(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.getSettings(callbackContext); + } + + private void getInfo(String id, CallbackContext callbackContext) { + WebViewInstance instance = requireInstance(id, callbackContext); + if (instance == null) return; + instance.getInfo(callbackContext); + } + + private void destroy(String id, final CallbackContext callbackContext) { + final WebViewInstance instance = instances.remove(id); + if (instance == null) { + callbackContext.error("WebView not found: " + id); + return; + } + + cordova.getActivity().runOnUiThread(() -> { + instance.destroy(); + callbackContext.success(); + }); + } + + /** Feature probes for the JS layer. */ + private JSONObject capabilities() { + JSONObject result = new JSONObject(); + try { + result.put("version", PLUGIN_VERSION); + result.put("multiProfile", ProfileManager.isSupported()); + result.put("deleteBrowsingData", ProfileManager.canDeleteBrowsingData()); + result.put("documentStartScript", isSupported(WebViewFeature.DOCUMENT_START_SCRIPT)); + result.put("safeBrowsing", isSupported(WebViewFeature.SAFE_BROWSING_ENABLE)); + result.put("algorithmicDarkening", isSupported(WebViewFeature.ALGORITHMIC_DARKENING)); + } catch (JSONException e) { + Log.e(TAG, "Error building capabilities", e); + } + return result; + } + + private static boolean isSupported(String feature) { + try { + return WebViewFeature.isFeatureSupported(feature); + } catch (Throwable t) { + return false; + } + } + + /** + * Starts a confirmed download via the system DownloadManager into the public + * Downloads directory. Cookies come from the originating instance's profile + * cookie jar, so isolated-profile sessions are neither dropped nor crossed + * with the default profile. Returns whether the download was enqueued. + */ + boolean download( + WebViewInstance instance, + String url, + String userAgent, + String mimeType, + String fileName + ) { + Context context = cordova.getActivity(); + try { + DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); + request.setMimeType(mimeType); + if (userAgent != null && !userAgent.isEmpty()) { + request.addRequestHeader("User-Agent", userAgent); + } + CookieManager cookieManager = instance != null + ? instance.getCookieManager() + : CookieManager.getInstance(); + String cookie = cookieManager != null ? cookieManager.getCookie(url) : null; + if (cookie != null && !cookie.isEmpty()) { + request.addRequestHeader("Cookie", cookie); + } + request.setDescription("Downloading file..."); + request.setTitle(fileName); + request.allowScanningByMediaScanner(); + request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); + request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); + + DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); + if (dm == null) { + throw new IllegalStateException("DownloadManager unavailable"); + } + dm.enqueue(request); + Toast.makeText(context, "Download started...", Toast.LENGTH_SHORT).show(); + return true; + } catch (Exception e) { + Log.e(TAG, "Download failed", e); + Toast.makeText(context, "Download failed", Toast.LENGTH_SHORT).show(); + return false; + } + } + + public void sendMessageToCordova(String id, String message) { + try { + JSONObject payload = new JSONObject(); + payload.put("id", id); + payload.put("message", message); + sendPayload(payload); + } catch (JSONException e) { + Log.e(TAG, "Error building message payload", e); + } + } + + public void sendEventToCordova(String id, String event, JSONObject data) { + try { + JSONObject payload = new JSONObject(); + payload.put("id", id); + payload.put("event", event); + if (data != null) { + payload.put("data", data); + } + sendPayload(payload); + } catch (JSONException e) { + Log.e(TAG, "Error building event payload", e); + } + } + + private void sendPayload(JSONObject payload) { + if (messageCallback == null) return; + PluginResult result = new PluginResult(PluginResult.Status.OK, payload); + result.setKeepCallback(true); + messageCallback.sendPluginResult(result); + } + + @Override + public void onReset() { + super.onReset(); + // The host WebView navigated and rebuilt its JS world, so the previous + // keep-callback is dead. The reloaded page registers a fresh one. + messageCallback = null; + } + + @Override + public void onDestroy() { + super.onDestroy(); + // Copy: destroying a fullscreen instance finishes its activity, whose + // onDestroy() removes it from the map. + for (WebViewInstance instance : new ArrayList<>(instances.values())) { + try { + instance.destroy(); + } catch (Exception ignored) {} + } + instances.clear(); + instance = null; + } +} diff --git a/src/plugins/webview/www/webview.js b/src/plugins/webview/www/webview.js new file mode 100644 index 0000000000..55e06e3126 --- /dev/null +++ b/src/plugins/webview/www/webview.js @@ -0,0 +1,174 @@ +/** + * Thin, promise-based wrapper over the native AcodeWebView Cordova plugin. + * + * Every call maps 1:1 to an action handled by WebViewPlugin.java. Higher-level + * behaviour (instance registry, event fan-out, option validation) lives in + * src/lib/webview.js. + */ + +const SERVICE = "AcodeWebView"; + +let messageHandler = null; +let messageCallbackRegistered = false; + +/** + * Registers the single, long-lived callback used for page messages and + * lifecycle events. Calling it more than once only swaps the handler; the + * native keep-callback channel is registered exactly once. + */ +function setMessageCallback(callback) { + messageHandler = typeof callback === "function" ? callback : null; + + if (messageCallbackRegistered) return; + + messageCallbackRegistered = true; + cordova.exec( + (payload) => { + if (messageHandler) { + messageHandler(payload); + } + }, + (error) => { + console.error("WebView message callback error:", error); + }, + SERVICE, + "setMessageCallback", + [], + ); +} + +function invoke(action, args) { + return new Promise((resolve, reject) => { + cordova.exec(resolve, reject, SERVICE, action, args || []); + }); +} + +/** Feature probes; resolves to a plain object of capability booleans. */ +function capabilities() { + return invoke("capabilities", []); +} + +function create(options) { + return invoke("create", [options || {}]); +} + +function loadURL(id, url, headers) { + const args = [id, url]; + if (headers && Object.keys(headers).length > 0) { + args.push(headers); + } + return invoke("loadURL", args); +} + +function loadHTML(id, html, htmlOptions) { + const args = [id, html]; + if (htmlOptions && Object.keys(htmlOptions).length > 0) { + args.push(htmlOptions); + } + return invoke("loadHTML", args); +} + +function evaluate(id, js) { + return invoke("evaluate", [id, js]); +} + +function postMessage(id, message) { + const payload = + typeof message === "string" ? message : JSON.stringify(message); + return invoke("postMessage", [id, payload]); +} + +function show(id) { + return invoke("show", [id]); +} + +function hide(id) { + return invoke("hide", [id]); +} + +function reload(id) { + return invoke("reload", [id]); +} + +function stopLoading(id) { + return invoke("stopLoading", [id]); +} + +function goBack(id) { + return invoke("goBack", [id]); +} + +function goForward(id) { + return invoke("goForward", [id]); +} + +function canGoBack(id) { + return invoke("canGoBack", [id]); +} + +function canGoForward(id) { + return invoke("canGoForward", [id]); +} + +function clearCache(id, includeDiskFiles) { + return invoke("clearCache", [id, includeDiskFiles !== false]); +} + +function clearHistory(id) { + return invoke("clearHistory", [id]); +} + +function clearFormData(id) { + return invoke("clearFormData", [id]); +} + +function setUserAgent(id, userAgent, mode) { + return invoke("setUserAgent", [id, userAgent == null ? null : userAgent, mode || null]); +} + +function getUserAgent(id) { + return invoke("getUserAgent", [id]); +} + +function updateSettings(id, settings) { + return invoke("updateSettings", [id, settings || {}]); +} + +function getSettings(id) { + return invoke("getSettings", [id]); +} + +function getInfo(id) { + return invoke("getInfo", [id]); +} + +function destroy(id) { + return invoke("destroy", [id]); +} + +export default { + setMessageCallback, + capabilities, + create, + loadURL, + loadHTML, + evaluate, + postMessage, + show, + hide, + reload, + stopLoading, + goBack, + goForward, + canGoBack, + canGoForward, + clearCache, + clearHistory, + clearFormData, + setUserAgent, + getUserAgent, + updateSettings, + getSettings, + getInfo, + destroy, +}; diff --git a/src/res/file-icons/style.css b/src/res/file-icons/style.css index e845690ad5..0b527ec4c1 100644 --- a/src/res/file-icons/style.css +++ b/src/res/file-icons/style.css @@ -886,6 +886,11 @@ color: #2c2d72; } +.file_type_luau:before { + content: "\e949"; + color: #2c2d72; +} + .file_type_lp:before { content: "\e949"; color: #2c2d72; @@ -1560,12 +1565,9 @@ color: #78dc50; } -.file_type_typescript:before { - content: "\e98a"; - color: #007acc; -} - -.file_type_ts:before { +.file_type_typescript:before, +.file_type_ts:before, +.file_type_tsx:before { content: "\e98a"; color: #007acc; } @@ -1768,4 +1770,4 @@ .file_type_zig:before { content: "\e9a5"; color: #f7a41d; -} \ No newline at end of file +} diff --git a/src/res/icons/icons.ttf b/src/res/icons/icons.ttf old mode 100644 new mode 100755 index 751a3c9d4e..8bcc9e37d5 Binary files a/src/res/icons/icons.ttf and b/src/res/icons/icons.ttf differ diff --git a/src/res/icons/li-icons.ttf b/src/res/icons/li-icons.ttf deleted file mode 100644 index 2880af54f2..0000000000 Binary files a/src/res/icons/li-icons.ttf and /dev/null differ diff --git a/src/res/icons/style.css b/src/res/icons/style.css index 1fb38d5fed..f883316e0e 100644 --- a/src/res/icons/style.css +++ b/src/res/icons/style.css @@ -1,38 +1,15 @@ @font-face { font-family: "code-editor-icon"; - src: url("icons.ttf?r1lwvj") format("truetype"); + src: url("icons.ttf?v3") format("truetype"); font-weight: normal; font-style: normal; font-display: block; } - -@font-face { - font-family: "li-icon"; - src: url("li-icons.ttf?6wte0b") format("truetype"); - font-weight: normal; - font-style: normal; - font-display: block; -} - -.icon { - /* use !important to prevent issues with browser extensions that change fonts */ +.icon, +[class^="icon-"], +[class*=" icon-"] { + /* Use !important to prevent extensions from overriding this font. */ font-family: "code-editor-icon" !important; - speak: none; - font-style: normal; - font-weight: normal; - font-variant: normal; - text-transform: none; - line-height: 1; - - /* Better Font Rendering =========== */ - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -.licons { - /* use !important to prevent issues with browser extensions that change fonts */ - font-family: "li-icon" !important; - speak: none; font-style: normal; font-weight: normal; font-variant: normal; @@ -43,1171 +20,915 @@ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } - -.licons.terminal:before { - content: "\e900"; -} -.licons.cart:before { - content: "\e901"; -} -.licons.scale:before { - content: "\e902"; -} -.licons.tag:before { - content: "\e903"; -} -.licons.verified:before { - content: "\e904"; -} - -.icon.acode:before { - content: "\ea0d"; - color: #3499fe; -} - -.icon.shift:before { - content: "\ea06"; -} - -.icon.replace:before { - content: "\ea07"; -} - -.icon.replace_all:before { - content: "\ea08"; -} - -.icon.moveline-up:before { - content: "\ea09"; -} - -.icon.moveline-down:before { - content: "\ea0a"; -} - -.icon.copyline-up:before { - content: "\ea0b"; -} - -.icon.copyline-down:before { - content: "\ea0c"; -} - -.icon.android:before { - content: "\e92e"; - color: #a4c639; -} - -.icon.angular:before { - content: "\e92f"; - color: #dd0031; -} - -.icon.angularuniversal:before { - content: "\e9ff"; - color: #00acc1; -} - -.icon.css3:before { - content: "\e930"; - color: #1572b6; -} - -.icon.dev-dot-to:before { - content: "\e931"; -} - -.icon.facebook:before { - content: "\e932"; - color: #4172b8; -} - -.icon.git:before { - content: "\e933"; - color: #f05032; -} - -.icon.github:before { - content: "\e934"; -} - -.icon.gmail:before { - content: "\e935"; - color: #d14836; -} - -.icon.googlechrome:before { - content: "\e936"; - color: #4285f4; -} - -.icon.googledrive:before { - content: "\e937"; - color: #4285f4; -} - -.icon.googleplay:before { - content: "\e938"; - color: #607d8b; -} - -.icon.html5:before { - content: "\e939"; - color: #e34f26; +.icon.like:before { + content: "\f2df"; } - -.icon.instagram:before { - content: "\e93a"; - color: #e4405f; +.icon.like-solid:before { + content: "\f576"; } - -.icon.ionic:before { - content: "\e93b"; - color: #3880ff; +.icon.text-search:before { + content: "\f02a"; } - -.icon.javascript:before { - content: "\e93c"; - color: #f7df1e; +.icon.wand:before { + content: "\f014"; } - -.icon.jekyll:before { - content: "\e93d"; - color: #c00; +.icon.wand-sparkles:before { + content: "\f013"; } - -.icon.linkedin:before { - content: "\e93e"; - color: #0077b5; +.icon.link:before { + content: "\f012"; } - -.icon.markdown:before { - content: "\e93f"; +.icon.brain:before { + content: "\f011"; } - -.icon.npm:before { - content: "\e940"; - color: #cb3837; +.icon.paperclip:before { + content: "\f010"; } - -.icon.patreon:before { - content: "\ea0f"; - color: #f96854; +.icon.palette:before { + content: "\f00f"; } - -.icon.paypal:before { - content: "\ea10"; - color: #00457c; +.icon.loader:before { + content: "\f00e"; } - -.icon.python:before { - content: "\e941"; - color: #3776ab; +.icon.square-terminal:before { + content: "\f00d"; } - -.icon.react:before { - content: "\e942"; - color: #61dafb; +.icon.house:before { + content: "\f00c"; } - -.icon.ruby:before { - content: "\ea11"; - color: #cc342d; +.icon.message-circle:before { + content: "\f00b"; } - -.icon.stackexchange:before { - content: "\e943"; - color: #1e5397; +.icon.user-round:before { + content: "\f00a"; } - -.icon.stackoverflow:before { - content: "\e944"; - color: #fe7a16; +.icon.funnel:before { + content: "\f009"; } - -.icon.telegram:before { - content: "\e945"; - color: #2ca5e0; +.icon.zap:before { + content: "\f000"; } - -.icon.twitter:before { - content: "\e946"; - color: #1da1f2; +.icon.verified:before { + content: "\f001"; } - -.icon.visualstudiocode:before { - content: "\e947"; - color: #007acc; +.icon.terminal:before { + content: "\f002"; } - -.icon.vue:before { - content: "\e9fe"; - color: #4fc08d; +.icon.tag:before { + content: "\f003"; } - -.icon.webpack:before { - content: "\e948"; - color: #8dd6f9; +.icon.scale:before { + content: "\f004"; } - -.icon.yarn:before { - content: "\e949"; - color: #2c8ebb; +.icon.cart:before { + content: "\f005"; } - -.icon.youtube:before { - content: "\e94a"; - color: #f00; +.icon.lightbulb:before { + content: "\f006"; } - -.icon.zip:before { - content: "\e9f8"; +.icon.pin:before { + content: "\f007"; } - -.icon.zip-outline:before { - content: "\e9f9"; +.icon.pin-off:before { + content: "\f008"; } - .icon.document-information:before { content: "\e900"; } - .icon.document-information-outline:before { content: "\e901"; } - .icon.document-forbidden:before { content: "\e902"; } - .icon.document-forbidden-outline:before { content: "\e903"; } - .icon.document-remove:before { content: "\e904"; } - .icon.document-remove-outline:before { content: "\e905"; } - .icon.document-checked:before { content: "\e906"; } - .icon.document-checked-outline:before { content: "\e907"; } - .icon.document-cancel:before { content: "\e908"; } - .icon.document-cancel-outline:before { content: "\e909"; } - .icon.document-error:before { content: "\e90a"; } - .icon.document-error-outline:before { content: "\e90b"; } - .icon.document-locked:before { content: "\e90c"; } - .icon.document-locked-outline:before { content: "\e90d"; } - .icon.document-unlocked:before { content: "\e90e"; } - .icon.document-unlocked-outline:before { content: "\e90f"; } - .icon.document-search:before { content: "\e910"; } - .icon.document-search-outline:before { content: "\e911"; } - .icon.document-code:before { content: "\e912"; } - .icon.document-code-outline:before { content: "\e913"; } - .icon.document-text:before { content: "\e914"; } - .icon.document-text-outline:before { content: "\e915"; } - -.icon.document-text2:before { - content: "\ea01"; +.icon.text_format:before { + content: "\e916"; } - -.icon.document-text2-outline:before { - content: "\ea02"; +.icon.chat_bubble:before { + content: "\e917"; } - -.icon.document-text4:before { - content: "\ea03"; +.icon.movie:before { + content: "\e918"; } - -.icon.document-text5:before { - content: "\ea04"; +.icon.videocam:before { + content: "\e919"; } - .icon.document-add:before { content: "\e91a"; } - .icon.document-add-outline:before { content: "\e91b"; } - .icon.documents:before { content: "\e91c"; } - .icon.documents-outline:before { content: "\e91d"; } - .icon.folder-information:before { content: "\e91e"; } - .icon.folder-information-outline:before { content: "\e91f"; } - .icon.folder-remove:before { content: "\e920"; } - .icon.folder-remove-outline:before { content: "\e921"; } - .icon.folder-add:before { content: "\e922"; } - .icon.folder-add-outline:before { content: "\e923"; } - .icon.folder-upload:before { content: "\e924"; } - .icon.folder-upload-outline:before { content: "\e925"; } - .icon.folder-download:before { content: "\e926"; } - .icon.folder-download-outline:before { content: "\e927"; } - .icon.folder-search:before { content: "\e928"; } - .icon.folder-search-outline:before { content: "\e929"; } - .icon.folder:before { content: "\e92a"; } - .icon.folder-outline:before { content: "\e92b"; } - .icon.folder2:before { content: "\e92c"; } - .icon.folder2-outline:before { content: "\e92d"; } - +.icon.android:before { + content: "\e92e"; +} +.icon.angular:before { + content: "\e92f"; +} +.icon.css3:before { + content: "\e930"; +} +.icon.dev-dot-to:before { + content: "\e931"; +} +.icon.facebook:before { + content: "\e932"; +} +.icon.git:before { + content: "\e933"; +} +.icon.github:before { + content: "\e934"; +} +.icon.gmail:before { + content: "\e935"; +} +.icon.googlechrome:before { + content: "\e936"; +} +.icon.googledrive:before { + content: "\e937"; +} +.icon.googleplay:before { + content: "\e938"; +} +.icon.html5:before { + content: "\e939"; +} +.icon.instagram:before { + content: "\e93a"; +} +.icon.ionic:before { + content: "\e93b"; +} +.icon.javascript:before { + content: "\e93c"; +} +.icon.jekyll:before { + content: "\e93d"; +} +.icon.linkedin:before { + content: "\e93e"; +} +.icon.markdown:before { + content: "\e93f"; +} +.icon.npm:before { + content: "\e940"; +} +.icon.python:before { + content: "\e941"; +} +.icon.react:before { + content: "\e942"; +} +.icon.stackexchange:before { + content: "\e943"; +} +.icon.stackoverflow:before { + content: "\e944"; +} +.icon.telegram:before { + content: "\e945"; +} +.icon.twitter:before { + content: "\e946"; +} +.icon.visualstudiocode:before { + content: "\e947"; +} +.icon.webpack:before { + content: "\e948"; +} +.icon.yarn:before { + content: "\e949"; +} +.icon.youtube:before { + content: "\e94a"; +} .icon.error:before { content: "\e94b"; } - .icon.error_outline:before { content: "\e94c"; } - .icon.warningreport_problem:before { content: "\e94d"; } - -.icon.movie:before { - content: "\e918"; -} - .icon.library_addqueueadd_to_photos:before { content: "\e94e"; } - .icon.library_music:before { content: "\e94f"; } - .icon.new_releases:before { content: "\e950"; } - .icon.not_interesteddo_not_disturb:before { content: "\e951"; } - .icon.pause:before { content: "\e952"; } - .icon.pause_circle_filled:before { content: "\e953"; } - .icon.pause_circle_outline:before { content: "\e954"; } - .icon.play_arrow:before { content: "\e955"; } - .icon.play_circle_filled:before { content: "\e956"; } - .icon.play_circle_outline:before { content: "\e957"; } - .icon.repeat:before { content: "\e958"; } - .icon.repeat_one:before { content: "\e959"; } - .icon.replay:before { content: "\e95a"; } - .icon.shuffle:before { content: "\e95b"; } - .icon.skip_next:before { content: "\e95c"; } - .icon.skip_previous:before { content: "\e95d"; } - -.icon.videocam:before { - content: "\e919"; -} - -.icon.music_video:before { - content: "\e978"; -} - .icon.emailmailmarkunreadlocal_post_office:before { content: "\e95e"; } - -.icon.chat_bubble:before { - content: "\e917"; -} - .icon.vpn_key:before { content: "\e95f"; } - .icon.add:before { content: "\e960"; } - .icon.add_box:before { content: "\e961"; } - .icon.add_circle:before { content: "\e962"; } - .icon.add_circle_outlinecontrol_point:before { content: "\e963"; } - .icon.block:before { content: "\e964"; } - .icon.clearclose:before { content: "\e965"; } - .icon.copy:before { content: "\e966"; } - .icon.cut:before { content: "\e967"; } - .icon.paste:before { content: "\e968"; } - .icon.edit:before { content: "\e969"; } - .icon.drafts:before { content: "\e96a"; } - .icon.forward:before { content: "\e96b"; } - -.icon.linkinsert_link:before { - content: "\ea00"; -} - -.icon.redo:before { - content: "\e9f6"; -} - .icon.remove:before { content: "\e96c"; } - .icon.remove_circledo_not_disturb_on:before { content: "\e96d"; } - .icon.remove_circle_outline:before { content: "\e96e"; } - -.icon.save:before { - content: "\e9f7"; -} - .icon.send:before { content: "\e96f"; } - -.icon.text_format:before { - content: "\e916"; -} - .icon.undo:before { content: "\e970"; } - -.icon.font_download:before { - content: "\ea12"; -} - .icon.save_alt:before { content: "\e971"; } - .icon.file_copy:before { content: "\e972"; } - .icon.sd_storagesd_card:before { content: "\e973"; } - .icon.attach_file:before { content: "\e974"; } - .icon.attach_money:before { content: "\e975"; } - .icon.format_bold:before { content: "\e976"; } - .icon.format_color_fill:before { content: "\e977"; } - +.icon.music_video:before { + content: "\e978"; +} .icon.format_size:before { content: "\e979"; } - .icon.format_underlined:before { content: "\e97a"; } - .icon.insert_chartpollassessment:before { content: "\e97b"; } - .icon.insert_emoticontag_facesmood:before { content: "\e97c"; } - .icon.insert_invitationevent:before { content: "\e97d"; } - .icon.image:before { content: "\e97e"; } - .icon.publish:before { content: "\e97f"; } - .icon.vertical_align_bottom:before { content: "\e980"; } - .icon.vertical_align_top:before { content: "\e981"; } - .icon.monetization_on:before { content: "\e982"; } - -.icon.notes:before { - content: "\ea13"; -} - .icon.cloud:before { content: "\e983"; } - .icon.cloud_done:before { content: "\e984"; } - .icon.cloud_download:before { content: "\e985"; } - .icon.cloud_uploadbackup:before { content: "\e986"; } - .icon.file_downloadget_app:before { content: "\e987"; } - -.icon.file_upload:before { - content: "\e988"; +.icon.file_upload:before { + content: "\e988"; +} +.icon.audiotrack:before { + content: "\e989"; +} +.icon.music_note:before { + content: "\e98a"; } - -.icon.folder4:before { - content: "\ea05"; +.icon.movie_filter:before { + content: "\e98b"; } - -.icon.folder_open:before { - content: "\e9fb"; +.icon.local_moviestheaters:before { + content: "\e98c"; } - .icon.keyboard_arrow_down:before { content: "\e98d"; } - .icon.keyboard_arrow_left:before { content: "\e98e"; } - .icon.keyboard_arrow_right:before { content: "\e98f"; } - .icon.keyboard_arrow_up:before { content: "\e990"; } - .icon.keyboard_backspace:before { content: "\e991"; } - .icon.keyboard_capslock:before { content: "\e992"; } - .icon.keyboard_hide:before { content: "\e993"; } - .icon.keyboard_tab:before { content: "\e994"; } - .icon.keyboard_voice:before { content: "\e995"; } - .icon.laptop_chromebook:before { content: "\e996"; } - .icon.laptop_mac:before { content: "\e997"; } - .icon.laptop_windows:before { content: "\e998"; } - .icon.phone_android:before { content: "\e999"; } - .icon.phone_iphone:before { content: "\e99a"; } - -.icon.audiotrack:before { - content: "\e989"; -} - .icon.color_lenspalette:before { content: "\e99b"; } - .icon.colorize:before { content: "\e99c"; } - -.icon.music_note:before { - content: "\e98a"; -} - .icon.navigate_beforechevron_left:before { content: "\e99d"; } - .icon.navigate_nextchevron_right:before { content: "\e99e"; } - .icon.remove_red_eyevisibility:before { content: "\e99f"; } - .icon.tune:before { content: "\e9a0"; } - -.icon.movie_filter:before { - content: "\e98b"; -} - .icon.add_photo_alternate:before { content: "\e9a1"; } - .icon.image_search:before { content: "\e9a2"; } - .icon.beenhere:before { content: "\e9a3"; } - -.icon.local_moviestheaters:before { - content: "\e98c"; -} - .icon.apps:before { content: "\e9a4"; } - .icon.arrow_back:before { content: "\e9a5"; } - .icon.arrow_drop_down:before { content: "\e9a6"; } - .icon.arrow_drop_down_circle:before { content: "\e9a7"; } - .icon.arrow_drop_up:before { content: "\e9a8"; } - .icon.arrow_forward:before { content: "\e9a9"; } - .icon.cancel:before { content: "\e9aa"; } - .icon.check:before { content: "\e9ab"; } - .icon.expand_less:before { content: "\e9ac"; } - .icon.expand_more:before { content: "\e9ad"; } - .icon.fullscreen:before { content: "\e9ae"; } - .icon.fullscreen_exit:before { content: "\e9af"; } - .icon.menu:before { content: "\e9b0"; } - .icon.keyboard_control:before { content: "\e9b1"; } - .icon.more_vert:before { content: "\e9b2"; } - .icon.refresh:before { content: "\e9b3"; } - .icon.unfold_less:before { content: "\e9b4"; } - .icon.unfold_more:before { content: "\e9b5"; } - .icon.arrow_upward:before { content: "\e9b6"; } - .icon.subdirectory_arrow_left:before { content: "\e9b7"; } - .icon.subdirectory_arrow_right:before { content: "\e9b8"; } - .icon.arrow_downward:before { content: "\e9b9"; } - .icon.first_page:before { content: "\e9ba"; } - .icon.last_page:before { content: "\e9bb"; } - .icon.arrow_left:before { content: "\e9bc"; } - .icon.arrow_right:before { content: "\e9bd"; } - .icon.arrow_back_ios:before { content: "\e9be"; } - .icon.arrow_forward_ios:before { content: "\e9bf"; } - .icon.folder_special:before { content: "\e9c0"; } - .icon.priority_high:before { content: "\e9c1"; } - .icon.notifications:before { content: "\e9c2"; } - .icon.notifications_none:before { content: "\e9c3"; } - .icon.person:before { content: "\e9c4"; } - .icon.public:before { content: "\e9c5"; } - .icon.share:before { content: "\e9c6"; } - .icon.sentiment_dissatisfied:before { content: "\e9c7"; } - .icon.sentiment_neutral:before { content: "\e9c8"; } - .icon.sentiment_satisfied:before { content: "\e9c9"; } - .icon.sentiment_very_dissatisfied:before { content: "\e9ca"; } - .icon.sentiment_very_satisfied:before { content: "\e9cb"; } - .icon.stargrade:before { content: "\e9cc"; } - .icon.star_half:before { content: "\e9cd"; } - .icon.star_outline:before { content: "\e9ce"; } - .icon.account_box:before { content: "\e9cf"; } - .icon.account_circle:before { content: "\e9d0"; } - .icon.android-full:before { content: "\e9d1"; } - .icon.autorenew:before { content: "\e9d2"; } - .icon.cached:before { content: "\e9d3"; } - .icon.check_circle:before { content: "\e9d4"; } - .icon.code:before { content: "\e9d5"; } - .icon.delete:before { content: "\e9d6"; } - .icon.exit_to_app:before { content: "\e9d7"; } - .icon.extension:before { content: "\e9d8"; } - .icon.favorite:before { content: "\e9d9"; } - .icon.favorite_outline:before { content: "\e9da"; } - .icon.help:before { content: "\e9db"; } - .icon.highlight_remove:before { content: "\e9dc"; } - .icon.historyrestore:before { content: "\e9dd"; } - .icon.home:before { content: "\e9de"; } - .icon.httpslock:before { content: "\e9df"; } - .icon.info:before { content: "\e9e0"; } - .icon.info_outline:before { content: "\e9e1"; } - .icon.input:before { content: "\e9e2"; } - .icon.label:before { content: "\e9e3"; } - .icon.label_outline:before { content: "\e9e4"; } - -.icon.launchopen_in_new:before { - content: "\e9fc"; -} - -.icon.open_in_browser:before { - content: "\e9fd"; -} - .icon.perm_media:before { content: "\e9e5"; } - .icon.power_settings_new:before { content: "\e9e6"; } - .icon.search:before { content: "\e9e7"; } - .icon.settings:before { content: "\e9e8"; } - .icon.settings_applications:before { content: "\e9e9"; } - .icon.shop:before { content: "\e9ea"; } - .icon.spellcheck:before { content: "\e9eb"; } - .icon.stars:before { content: "\e9ec"; } - .icon.translate:before { content: "\e9ed"; } - .icon.visibility_off:before { content: "\e9ee"; } - -.icon.http:before { - content: "\ea14"; -} - -.icon.compare_arrows:before { - content: "\ea15"; -} - .icon.update:before { content: "\e9ef"; } - .icon.g_translate:before { content: "\e9f0"; } - .icon.check_circle_outline:before { content: "\e9f1"; } - .icon.delete_outline:before { content: "\e9f2"; } - .icon.drive_folder_upload:before { content: "\e9f3"; } - -.icon.home_filled:before { - content: "\ea16"; -} - .icon.library_add_check:before { content: "\e9f4"; } - +.icon.replay_circle_filled:before { + content: "\e9f5"; +} +.icon.redo:before { + content: "\e9f6"; +} +.icon.save:before { + content: "\e9f7"; +} +.icon.zip:before { + content: "\e9f8"; +} +.icon.zip-outline:before { + content: "\e9f9"; +} .icon.logout:before { content: "\e9fa"; } - -.icon.replay_circle_filled:before { - content: "\e9f5"; +.icon.folder_open:before { + content: "\e9fb"; +} +.icon.launchopen_in_new:before { + content: "\e9fc"; +} +.icon.open_in_browser:before { + content: "\e9fd"; +} +.icon.vue:before { + content: "\e9fe"; +} +.icon.angularuniversal:before { + content: "\e9ff"; +} +.icon.linkinsert_link:before { + content: "\ea00"; +} +.icon.document-text2:before { + content: "\ea01"; +} +.icon.document-text2-outline:before { + content: "\ea02"; +} +.icon.document-text4:before { + content: "\ea03"; +} +.icon.document-text5:before { + content: "\ea04"; +} +.icon.folder4:before { + content: "\ea05"; +} +.icon.shift:before { + content: "\ea06"; +} +.icon.replace:before { + content: "\ea07"; +} +.icon.replace_all:before { + content: "\ea08"; +} +.icon.moveline-up:before { + content: "\ea09"; +} +.icon.moveline-down:before { + content: "\ea0a"; +} +.icon.copyline-up:before { + content: "\ea0b"; +} +.icon.copyline-down:before { + content: "\ea0c"; +} +.icon.acode:before { + content: "\ea0d"; +} +.icon.patreon:before { + content: "\ea0f"; +} +.icon.paypal:before { + content: "\ea10"; +} +.icon.ruby:before { + content: "\ea11"; +} +.icon.font_download:before { + content: "\ea12"; +} +.icon.notes:before { + content: "\ea13"; +} +.icon.http:before { + content: "\ea14"; +} +.icon.compare_arrows:before { + content: "\ea15"; +} +.icon.home_filled:before { + content: "\ea16"; } - .icon.height:before { content: "\ea17"; } - .icon.all_inclusive:before { content: "\ea18"; } diff --git a/src/res/tail-spin.svg b/src/res/tail-spin.svg index a12f0f4b9f..b72bb60882 100644 --- a/src/res/tail-spin.svg +++ b/src/res/tail-spin.svg @@ -1,15 +1,15 @@ - + - - - - + + + + - + - + lang.getName(value), + info: strings["settings-info-app-language"], + category: categories.interface, }, { key: "animation", @@ -34,42 +55,34 @@ export default function otherSettings() { ["yes", strings.yes], ["system", strings.system], ], + info: strings["settings-info-app-animation"], + category: categories.interface, }, { key: "fullscreen", text: strings.fullscreen.capitalize(), checkbox: values.fullscreen, + info: strings["settings-info-app-fullscreen"], + category: categories.interface, }, { - key: "lang", - text: strings["change language"], - value: values.lang, - select: lang.list, - valueText: (value) => lang.getName(value), - }, - { - key: "keybindings", - text: strings["key bindings"], - select: [ - ["edit", strings.edit], - ["reset", strings.reset], - ], - }, - { - key: "confirmOnExit", - text: strings["confirm on exit"], - checkbox: values.confirmOnExit, - }, - { - key: "checkFiles", - text: strings["check file changes"], - checkbox: values.checkFiles, - }, - { - key: "console", - text: strings.console, - value: values.console, - select: [appSettings.CONSOLE_LEGACY, appSettings.CONSOLE_ERUDA], + key: "uiZoom", + text: strings["ui zoom"] || "UI zoom", + value: values.uiZoom, + valueText: (value) => `${value}%`, + prompt: strings["ui zoom"] || "UI zoom", + promptType: "number", + promptOptions: { + test(value) { + if (!/^\d+$/.test(String(value).trim())) return false; + const zoom = Number(value); + return zoom >= 70 && zoom <= 160; + }, + }, + info: + strings["settings-info-app-ui-zoom"] || + "Scale text across the Acode interface.", + category: categories.interface, }, { key: "keyboardMode", @@ -86,26 +99,29 @@ export default function otherSettings() { strings["no suggestions aggressive"], ], ], + info: strings["settings-info-app-keyboard-mode"], + category: categories.interface, }, { key: "vibrateOnTap", text: strings["vibrate on tap"], checkbox: values.vibrateOnTap, + info: strings["settings-info-app-vibrate-on-tap"], + category: categories.interface, }, { - key: "rememberFiles", - text: strings["remember opened files"], - checkbox: values.rememberFiles, - }, - { - key: "rememberFolders", - text: strings["remember opened folders"], - checkbox: values.rememberFolders, + key: "showSideButtons", + text: strings["show side buttons"], + checkbox: values.showSideButtons, + info: strings["settings-info-app-side-buttons"], + category: categories.interface, }, { - key: "floatingButton", - text: strings["floating button"], - checkbox: values.floatingButton, + key: "showSponsorSidebarApp", + text: `${strings.sponsor} (${strings.sidebar})`, + checkbox: values.showSponsorSidebarApp, + info: strings["settings-info-app-sponsor-sidebar"], + category: categories.interface, }, { key: "openFileListPos", @@ -117,21 +133,8 @@ export default function otherSettings() { [appSettings.OPEN_FILE_LIST_POS_HEADER, strings.header], [appSettings.OPEN_FILE_LIST_POS_BOTTOM, strings.bottom], ], - }, - { - key: "quickTools", - text: strings["quick tools"], - checkbox: !!values.quickTools, - info: "Show or hide quick tools.", - }, - { - key: "quickToolsTriggerMode", - text: strings["quicktools trigger mode"], - value: values.quickToolsTriggerMode, - select: [ - [appSettings.QUICKTOOLS_TRIGGER_MODE_CLICK, "click"], - [appSettings.QUICKTOOLS_TRIGGER_MODE_TOUCH, "touch"], - ], + info: strings["settings-info-app-open-file-list-position"], + category: categories.interface, }, { key: "touchMoveThreshold", @@ -144,21 +147,127 @@ export default function otherSettings() { return value >= 0; }, }, + info: strings["settings-info-app-touch-move-threshold"], + category: categories.interface, + }, + { + key: "floatingButton", + text: strings["quick tools toggler"], + checkbox: values.floatingButton, + info: strings["settings-info-app-floating-button"], + category: categories.quickTools, + }, + { + key: "quickTools", + text: strings["quick tools height"], + value: values.quickTools, + valueText: (value) => { + const height = Number(value) || 0; + if (height === 0) return strings.off; + if (height === 1) return strings.compact; + return strings.full; + }, + select: [ + [0, strings.off], + [1, strings.compact], + [2, strings.full], + ], + info: strings["info-quickTools"], + category: categories.quickTools, + }, + { + key: "quickToolsTriggerMode", + text: strings["quicktools trigger mode"], + value: values.quickToolsTriggerMode, + valueText: (value) => { + const options = { + [appSettings.QUICKTOOLS_TRIGGER_MODE_CLICK]: + strings["quicktools-trigger:click"], + [appSettings.QUICKTOOLS_TRIGGER_MODE_TOUCH]: + strings["quicktools-trigger:touch"], + }; + + return options[value] ?? (value != null ? value.capitalize() : value); + }, + select: [ + [ + appSettings.QUICKTOOLS_TRIGGER_MODE_CLICK, + strings["quicktools-trigger:click"], + ], + [ + appSettings.QUICKTOOLS_TRIGGER_MODE_TOUCH, + strings["quicktools-trigger:touch"], + ], + ], + info: strings["settings-info-app-quick-tools-trigger-mode"], + category: categories.quickTools, }, { key: "quickToolsSettings", text: strings["shortcut buttons"], - index: 0, + info: strings["settings-info-app-quick-tools-settings"], + category: categories.quickTools, + chevron: true, + }, + { + key: "appFont", + text: appFontText, + value: values.appFont || "", + valueText: (value) => value || defaultFontLabel, + get select() { + return [["", defaultFontLabel], ...fonts.getNames()]; + }, + info: appFontInfo, + category: categories.fonts, }, { key: "fontManager", text: strings["fonts"], - index: 1, + info: strings["settings-info-app-font-manager"], + category: categories.fonts, + chevron: true, }, { - key: "showSideButtons", - text: strings["show side buttons"], - checkbox: values.showSideButtons, + key: "iconTheme", + text: strings["icon pack"], + value: values.iconTheme || "builtin", + get select() { + return fileIcons + .list() + .map((theme) => [ + theme.id, + theme.available === false + ? `${theme.name} (${strings.unavailable || "unavailable"})` + : theme.name, + ]); + }, + valueText: (value) => { + const theme = fileIcons.list().find((entry) => entry.id === value); + return theme?.name || value || "Builtin"; + }, + info: strings["settings-info-icon-pack"], + category: categories.interface, + }, + { + key: "rememberFiles", + text: strings["remember opened files"], + checkbox: values.rememberFiles, + info: strings["settings-info-app-remember-files"], + category: categories.filesSessions, + }, + { + key: "rememberFolders", + text: strings["remember opened folders"], + checkbox: values.rememberFolders, + info: strings["settings-info-app-remember-folders"], + category: categories.filesSessions, + }, + { + key: "retryRemoteFsAfterFail", + text: strings["retry ftp/sftp when fail"], + checkbox: values.retryRemoteFsAfterFail, + info: strings["settings-info-app-retry-remote-fs"], + category: categories.filesSessions, }, { key: "excludeFolders", @@ -168,11 +277,25 @@ export default function otherSettings() { promptType: "textarea", promptOptions: { test(value) { + if (!value.trim()) return true; return value.split("\n").every((item) => { return item.trim().length > 0; }); }, }, + info: strings["settings-info-app-exclude-folders"], + category: categories.filesSessions, + }, + { + key: "useFileOperationExclusions", + text: + strings["apply exclusions when copying"] || + "Apply exclusions when copying", + checkbox: values.useFileOperationExclusions, + info: + strings["settings-info-app-use-file-operation-exclusions"] || + "Skip files and folders matching the exclusion patterns during copy and paste operations.", + category: categories.filesSessions, }, { key: "defaultFileEncoding", @@ -187,14 +310,92 @@ export default function otherSettings() { return [id, encoding.label]; }), ], + info: strings["settings-info-app-default-file-encoding"], + category: categories.filesSessions, + }, + { + key: "keybindings", + text: strings["key bindings"], + info: strings["settings-info-app-keybindings"], + category: categories.advanced, + chevron: true, + }, + { + key: "confirmOnExit", + text: strings["confirm on exit"], + checkbox: values.confirmOnExit, + info: strings["settings-info-app-confirm-on-exit"], + category: categories.advanced, + }, + { + key: "checkFiles", + text: strings["check file changes"], + checkbox: values.checkFiles, + info: strings["settings-info-app-check-files"], + category: categories.advanced, + }, + ...(!installedFromPlayStore + ? [ + { + key: "checkForAppUpdates", + text: strings["check for app updates"], + checkbox: values.checkForAppUpdates, + info: strings["info-checkForAppUpdates"], + category: categories.advanced, + }, + ] + : []), + { + key: "console", + text: strings.console, + value: values.console, + valueText: (value) => { + const options = { + [appSettings.CONSOLE_LEGACY]: "Legacy", + [appSettings.CONSOLE_ERUDA]: "Eruda", + }; + return options[value] ?? (value != null ? value.capitalize() : value); + }, + select: [ + [appSettings.CONSOLE_LEGACY, "Legacy"], + [appSettings.CONSOLE_ERUDA, "Eruda"], + ], + info: strings["settings-info-app-console"], + category: categories.advanced, + }, + { + key: "developerMode", + text: strings["developer mode"], + checkbox: values.developerMode, + info: strings["info-developermode"], + category: categories.advanced, + }, + { + key: "cleanInstallState", + text: strings["clean install state"], + info: strings["settings-info-app-clean-install-state"], + category: categories.advanced, + chevron: true, }, ]; - return settingsPage(title, items, callback); + return settingsPage(title, items, callback, undefined, { + preserveOrder: true, + pageClassName: "detail-settings-page", + listClassName: "detail-settings-list", + infoAsDescription: true, + valueInTail: true, + }); async function callback(key, value) { switch (key) { case "keybindings": { + value = await select(strings["key bindings"], [ + ["edit", strings.edit], + ["reset", strings.reset], + ]); + if (!value) return; + if (value === "edit") { actionStack.pop(2); openFile(KEYBINDING_FILE); @@ -212,6 +413,10 @@ export default function otherSettings() { FontManager(); return; + case "appFont": + await fonts.setAppFont(value); + break; + case "console": { if (value !== "eruda") { break; @@ -227,16 +432,60 @@ export default function otherSettings() { strings["downloading..."], ); try { - const erudaScript = await ajax({ - url: constants.ERUDA_CDN, - responseType: "text", - contentType: "application/x-www-form-urlencoded", - }); + const erudaScript = await fsOperation(config.ERUDA_CDN).readFile( + "utf-8", + ); await fsOperation(DATA_STORAGE).createFile("eruda.js", erudaScript); loader.destroy(); } catch (error) { helpers.error(error); } + break; + } + + case "developerMode": { + if (value) { + const devTools = (await import("lib/devTools")).default; + try { + await devTools.init(true); + toast( + strings["developer mode enabled"] || + "Developer mode enabled. Use command palette to toggle inspector.", + ); + } catch (error) { + helpers.error(error); + value = false; + } + } else { + const devTools = (await import("lib/devTools")).default; + devTools.destroy(); + toast( + strings["developer mode disabled"] || "Developer mode disabled", + ); + } + break; + } + + case "cleanInstallState": { + const INSTALL_STATE_STORAGE = Url.join(DATA_STORAGE, ".install-state"); + + const fs = fsOperation(INSTALL_STATE_STORAGE); + + if (!(await fs.exists())) { + toast(strings["no such file or directory"]); + break; + } + + loader.create("loading..."); + + try { + await fs.delete(); + loader.destroy(); + toast(strings["success"]); + } catch (error) { + helpers.error(error); + loader.destroy(); + } } case "rememberFiles": @@ -252,26 +501,41 @@ export default function otherSettings() { break; case "floatingButton": - root.classList.toggle("hide-floating-button"); + if (value && !editorManager.activeFile?.hideQuickTools) { + clearTimeout(quickTools.$toggler._hideTimeout); + quickTools.$toggler._hideTimeout = null; + quickTools.$toggler.classList.remove("hide"); + if (!quickTools.$toggler.isConnected) { + root.appendOuter(quickTools.$toggler); + } + } else { + clearTimeout(quickTools.$toggler._hideTimeout); + quickTools.$toggler.classList.add("hide"); + quickTools.$toggler._hideTimeout = setTimeout(() => { + quickTools.$toggler.remove(); + quickTools.$toggler._hideTimeout = null; + }, 300); + } break; case "keyboardMode": system.setInputType(value); break; + case "uiZoom": + value = Number(value); + if (!Number.isInteger(value)) return; + value = Math.min(160, Math.max(70, value)); + break; + case "fullscreen": if (value) acode.exec("enable-fullscreen"); else acode.exec("disable-fullscreen"); break; case "quickTools": - if (value) { - value = 1; - actions("set-height", 1); - } else { - value = 0; - actions("set-height", 0); - } + value = Number(value) || 0; + actions("set-height", { height: value, save: false }); break; case "excludeFolders": @@ -285,7 +549,7 @@ export default function otherSettings() { break; } - appSettings.update({ + await appSettings.update({ [key]: value, }); } diff --git a/src/settings/backupRestore.js b/src/settings/backupRestore.js index 522d572c89..d23a576e8c 100644 --- a/src/settings/backupRestore.js +++ b/src/settings/backupRestore.js @@ -2,13 +2,138 @@ import fsOperation from "fileSystem"; import settingsPage from "components/settingsPage"; import toast from "components/toast"; import alert from "dialogs/alert"; -import constants from "lib/constants"; +import confirm from "dialogs/confirm"; +import loader from "dialogs/loader"; +import config from "lib/config"; import appSettings from "lib/settings"; import FileBrowser from "pages/fileBrowser"; import helpers from "utils/helpers"; import Uri from "utils/Uri"; import Url from "utils/Url"; +// Backup format version for future compatibility +const BACKUP_VERSION = 2; + +/** + * CRC32 lookup table for checksum calculation + */ +const CRC32_TABLE = (() => { + const table = new Uint32Array(256); + for (let i = 0; i < 256; i++) { + let crc = i; + for (let j = 0; j < 8; j++) { + crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1; + } + table[i] = crc >>> 0; + } + return table; +})(); + +/** + * Generates a CRC32 checksum for data integrity verification + * More robust than simple hash for detecting corrupted data + * @param {string} data + * @returns {string} + */ +function generateChecksum(data) { + let crc = 0xffffffff; + for (let i = 0; i < data.length; i++) { + const byte = data.charCodeAt(i) & 0xff; + crc = CRC32_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8); + } + return ((crc ^ 0xffffffff) >>> 0).toString(16).padStart(8, "0"); +} + +/** + * Validates the structure of a backup object + * Supports both v1 (legacy) and v2 (new) backup formats + * @param {object} backup + * @returns {{valid: boolean, errors: string[], warnings: string[], isLegacy: boolean}} + */ +function validateBackupStructure(backup) { + const errors = []; + const warnings = []; + + if (!backup || typeof backup !== "object") { + errors.push(strings["backup not valid object"]); + return { valid: false, errors, warnings, isLegacy: false }; + } + + // Determine if this is a legacy (v1) backup + const isLegacy = !backup.version; + + if (isLegacy) { + // Legacy backup (v1) - just needs settings or installedPlugins to be valid + const hasData = + backup.settings || backup.keyBindings || backup.installedPlugins; + if (!hasData) { + errors.push(strings["backup no data"]); + } + warnings.push(strings["backup legacy warning"]); + } else { + // Version 2+ backup + if (backup.version >= 2) { + if (!backup.metadata) { + warnings.push(strings["backup missing metadata"]); + } + + // Verify checksum if present + if (backup.checksum) { + try { + const dataToCheck = JSON.stringify({ + settings: backup.settings, + keyBindings: backup.keyBindings, + installedPlugins: backup.installedPlugins, + }); + const expectedChecksum = generateChecksum(dataToCheck); + if (backup.checksum !== expectedChecksum) { + warnings.push(strings["backup checksum mismatch"]); + } + } catch (e) { + warnings.push(strings["backup checksum verify failed"]); + } + } + } + } + + // Validate settings (both versions) + if (backup.settings !== undefined && typeof backup.settings !== "object") { + errors.push(strings["backup invalid settings"]); + } + + // Validate keyBindings (both versions) + if ( + backup.keyBindings !== undefined && + typeof backup.keyBindings !== "object" + ) { + errors.push(strings["backup invalid keybindings"]); + } + + // Validate installedPlugins (both versions) + if ( + backup.installedPlugins !== undefined && + !Array.isArray(backup.installedPlugins) + ) { + errors.push(strings["backup invalid plugins"]); + } + + return { valid: errors.length === 0, errors, warnings, isLegacy }; +} + +/** + * Formats a date for backup filename + * @param {Date} date + * @returns {string} + */ +function formatDateForFilename(date) { + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, "0"); + const day = String(date.getDate()).padStart(2, "0"); + const hours = String(date.getHours()).padStart(2, "0"); + const minutes = String(date.getMinutes()).padStart(2, "0"); + return `${year}${month}${day}_${hours}${minutes}`; +} + function backupRestore() { const title = strings.backup.capitalize() + "/" + strings.restore.capitalize(); @@ -17,18 +142,25 @@ function backupRestore() { key: "backup", text: strings.backup.capitalize(), icon: "file_downloadget_app", + chevron: true, }, { key: "restore", text: strings.restore.capitalize(), icon: "historyrestore", + chevron: true, }, { note: strings["backup/restore note"], }, ]; - return settingsPage(title, items, callback); + return settingsPage(title, items, callback, undefined, { + preserveOrder: true, + pageClassName: "detail-settings-page", + listClassName: "detail-settings-list", + groupByDefault: true, + }); function callback(key) { switch (key) { @@ -46,35 +178,91 @@ function backupRestore() { } async function backup() { + const loaderDialog = loader.create( + strings.backup.capitalize(), + strings["preparing backup"], + ); + try { + loaderDialog.show(); + loaderDialog.setMessage(strings["collecting settings"]); + const settings = appSettings.value; - const keyBindings = await fsOperation(KEYBINDING_FILE).readFile("json"); - const plugins = await fsOperation(window.PLUGIN_DIR).lsDir(); + + // Read keybindings with fallback + loaderDialog.setMessage(strings["collecting key bindings"]); + let keyBindings = null; + try { + const keybindingsFS = fsOperation(KEYBINDING_FILE); + if (await keybindingsFS.exists()) { + keyBindings = await keybindingsFS.readFile("json"); + } + } catch (error) { + console.warn("Could not read keybindings:", error); + } + + // Collect plugin information + loaderDialog.setMessage(strings["collecting plugins"]); const installedPlugins = []; - const installedPluginsWithSource = []; + const pluginDetails = []; - for (const plugin of plugins) { - try { - const pluginJsonPath = Url.join( - window.PLUGIN_DIR, - plugin.name, - "plugin.json", - ); - const pluginJson = await fsOperation(pluginJsonPath).readFile("json"); + try { + const pluginsDir = fsOperation(window.PLUGIN_DIR); + if (await pluginsDir.exists()) { + const plugins = await pluginsDir.lsDir(); - if (pluginJson.source) { - installedPluginsWithSource.push(pluginJson.source); - } else { - installedPlugins.push(plugin.name); + for (const plugin of plugins) { + try { + const pluginJsonPath = Url.join( + window.PLUGIN_DIR, + plugin.name, + "plugin.json", + ); + const pluginJson = + await fsOperation(pluginJsonPath).readFile("json"); + + // Store detailed plugin info for better restore + const pluginInfo = { + id: pluginJson.id || plugin.name, + name: pluginJson.name || plugin.name, + version: pluginJson.version || "unknown", + source: pluginJson.source || null, + }; + pluginDetails.push(pluginInfo); + + if (pluginJson.source) { + installedPlugins.push(pluginJson.source); + } else { + installedPlugins.push(pluginJson.id || plugin.name); + } + } catch (error) { + // Fallback to just plugin name + installedPlugins.push(plugin.name); + pluginDetails.push({ + id: plugin.name, + name: plugin.name, + version: "unknown", + source: null, + }); + } } - } catch (error) { - installedPlugins.push(plugin.name); } + } catch (error) { + console.warn("Could not read plugins directory:", error); } + loaderDialog.hide(); + + // Get destination folder const { url } = await FileBrowser("folder", strings["select folder"]); - const backupFilename = "Acode.backup"; + loaderDialog.show(); + loaderDialog.setMessage( + strings["creating backup"] || "Creating backup file...", + ); + + const timestamp = formatDateForFilename(new Date()); + const backupFilename = `Acode_backup_${timestamp}.backup`; const backupDirname = "Backup"; const backupDir = Url.join(url, backupDirname); const backupFile = Url.join(backupDir, backupFilename); @@ -82,31 +270,62 @@ function backupRestore() { const backupDirFS = fsOperation(backupDir); const backupFileFS = fsOperation(backupFile); + // Create backup directory if needed if (!(await backupDirFS.exists())) { await backupStorageFS.createDirectory(backupDirname); } + // Create backup file if (!(await backupFileFS.exists())) { await backupDirFS.createFile(backupFilename); } - const backupString = JSON.stringify({ + // Prepare backup data with checksum + const backupData = { + settings, + keyBindings, + installedPlugins, + }; + + const checksum = generateChecksum(JSON.stringify(backupData)); + + const backupObject = { + version: BACKUP_VERSION, + metadata: { + createdAt: new Date().toISOString(), + appVersion: BuildInfo?.version || "unknown", + pluginCount: installedPlugins.length, + hasSettings: !!settings, + hasKeyBindings: !!keyBindings, + }, + checksum, settings, keyBindings, - installedPlugins: [...installedPlugins, ...installedPluginsWithSource], - }); + installedPlugins, + pluginDetails, // Extra detail for better restoration info + }; + const backupString = JSON.stringify(backupObject, null, 2); await backupFileFS.writeFile(backupString); + loaderDialog.destroy(); + + const message = [ + strings["backup successful"], + `
${Uri.getVirtualAddress(backupFile)}
`, + `${strings.settings || "Settings"}: ✓`, + `${strings["key bindings"] || "Key Bindings"}: ${keyBindings ? "✓" : "-"}`, + `${strings.plugins || "Plugins"}: ${installedPlugins.length}`, + ].join("
"); + + alert(strings.success, message); + } catch (error) { + loaderDialog.destroy(); + console.error("Backup error:", error); alert( - strings.success.toUpperCase(), - `${strings["backup successful"]}\n${Uri.getVirtualAddress( - backupFile, - )}.`, + strings.error, + `${strings["error details"] || "Error"}: ${error.message || error}`, ); - } catch (error) { - console.error(error); - toast(error); } } @@ -115,93 +334,362 @@ function backupRestore() { (data) => { backupRestore.restore(data.uri); }, - toast, + (error) => { + console.error("File picker error:", error); + toast(strings.error || "Error selecting file"); + }, "application/octet-stream", ); } } backupRestore.restore = async function (url) { + const loaderDialog = loader.create( + strings.restore.capitalize(), + strings["please wait..."], + ); + + const restoreResults = { + settings: { attempted: false, success: false, error: null }, + keyBindings: { attempted: false, success: false, error: null }, + plugins: { attempted: false, success: [], failed: [], skipped: [] }, + }; + try { - let fs = fsOperation(url); - let backup = await fs.readFile("utf8"); + loaderDialog.show(); + + // Read and parse backup file + const fs = fsOperation(url); + let backupContent; try { - backup = JSON.parse(backup); + backupContent = await fs.readFile("utf8"); } catch (error) { - alert(strings.error.toUpperCase(), strings["invalid backup file"]); - return; + throw new Error(`Could not read backup file: ${error.message}`); } + let backup; try { - const text = JSON.stringify(backup.keyBindings, undefined, 2); - await fsOperation(window.KEYBINDING_FILE).writeFile(text); + backup = JSON.parse(backupContent); } catch (error) { - console.error("Error restoring key bindings:", error); + loaderDialog.destroy(); + alert(strings.error, strings["invalid backup file"]); + return; + } + + // Validate backup structure + loaderDialog.setMessage(strings["validating backup"]); + const validation = validateBackupStructure(backup); + + if (!validation.valid) { + loaderDialog.destroy(); + const errorMessage = [ + strings["invalid backup file"], + "", + `${strings["issues found"]}:`, + ...validation.errors.map((e) => `• ${e}`), + ].join("\n"); + alert(strings.error, errorMessage); + return; } - const { settings, installedPlugins } = backup; + loaderDialog.hide(); - const { default: installPlugin } = await import("lib/installPlugin"); + // Show backup info and ask for confirmation + const backupInfo = backup.metadata || {}; + const confirmParts = [ + `${strings["restore will include"]}

`, + `${strings.settings}: ${backup.settings ? strings.yes : strings.no}
`, + `${strings["key bindings"]}: ${backup.keyBindings ? strings.yes : strings.no}
`, + `${strings.plugins}: ${backup.installedPlugins?.length || 0}
`, + ]; + + if (backupInfo.createdAt) { + confirmParts.push( + `
${strings["last modified"]}: ${new Date(backupInfo.createdAt).toLocaleString()}
`, + ); + } + + // Show warnings if any (legacy backup, checksum issues, etc.) + if (validation.warnings && validation.warnings.length > 0) { + confirmParts.push(`
${strings.warning}:
`); + for (const warning of validation.warnings) { + confirmParts.push(`- ${warning}
`); + } + } + + confirmParts.push(`
${strings["restore warning"]}`); + + const shouldContinue = await confirm( + strings.restore.capitalize(), + confirmParts.join(""), + true, + ); + + if (!shouldContinue) { + return; + } + + // What to restore - restore everything available + const selectedOptions = []; + if (backup.settings) selectedOptions.push("settings"); + if (backup.keyBindings) selectedOptions.push("keyBindings"); + if (backup.installedPlugins?.length) selectedOptions.push("plugins"); + + loaderDialog.show(); + + // Restore key bindings first (before settings, in case of reload) + if (selectedOptions.includes("keyBindings") && backup.keyBindings) { + restoreResults.keyBindings.attempted = true; + loaderDialog.setMessage(strings["restoring key bindings"]); + + try { + const keybindingsFS = fsOperation(window.KEYBINDING_FILE); + + // Ensure file exists + if (!(await keybindingsFS.exists())) { + const parentDir = fsOperation(DATA_STORAGE); + await parentDir.createFile(".key-bindings.json"); + } + + const text = JSON.stringify(backup.keyBindings, undefined, 2); + await keybindingsFS.writeFile(text); + restoreResults.keyBindings.success = true; + } catch (error) { + console.error("Error restoring key bindings:", error); + restoreResults.keyBindings.error = error.message; + } + } // Restore plugins - if (Array.isArray(installedPlugins)) { - for (const id of installedPlugins) { + if ( + selectedOptions.includes("plugins") && + Array.isArray(backup.installedPlugins) && + backup.installedPlugins.length > 0 + ) { + restoreResults.plugins.attempted = true; + const { default: installPlugin } = await import("lib/installPlugin"); + + const totalPlugins = backup.installedPlugins.length; + let currentPlugin = 0; + + for (const id of backup.installedPlugins) { + currentPlugin++; + + if (!id) { + restoreResults.plugins.skipped.push({ + id: "(empty)", + reason: "Empty plugin ID", + }); + continue; + } + + const pluginName = + backup.pluginDetails?.find((p) => p.id === id || p.source === id) + ?.name || id; + + loaderDialog.setMessage( + `${strings["restoring plugins"]} (${currentPlugin}/${totalPlugins}): ${pluginName}`, + ); + try { - if (!id) continue; if ( id.startsWith("content://") || id.startsWith("file://") || id.includes("/") ) { - // Local plugin case - pass URI directly - toast("Restoring plugins"); - await installPlugin(id); + // Local plugin case + try { + // Check if the source file still exists + const sourceFS = fsOperation(id); + if (!(await sourceFS.exists())) { + restoreResults.plugins.skipped.push({ + id: pluginName, + reason: strings["source not found"], + }); + continue; + } + await installPlugin(id); + restoreResults.plugins.success.push(pluginName); + } catch (error) { + restoreResults.plugins.failed.push({ + id: pluginName, + reason: error.message, + }); + } } else { // Remote plugin case - fetch from API - const pluginUrl = Url.join(constants.API_BASE, `plugin/${id}`); - const remotePlugin = await fsOperation(pluginUrl) - .readFile("json") - .catch(() => null); + const pluginUrl = Url.join(config.API_BASE, `plugin/${id}`); + let remotePlugin = null; + + try { + remotePlugin = await fsOperation(pluginUrl).readFile("json"); + } catch (error) { + restoreResults.plugins.failed.push({ + id: pluginName, + reason: strings["plugin not found"], + }); + continue; + } if (remotePlugin) { let purchaseToken = null; - if (Number.parseFloat(remotePlugin.price) > 0) { + const isPaid = Number.parseFloat(remotePlugin.price) > 0; + + if (isPaid) { try { const [product] = await helpers.promisify(iap.getProducts, [ remotePlugin.sku, ]); if (product) { - async function getPurchase(sku) { - const purchases = await helpers.promisify( - iap.getPurchases, - ); - const purchase = purchases.find((p) => - p.productIds.includes(sku), - ); - return purchase; - } - const purchase = await getPurchase(product.productId); + const purchases = await helpers.promisify(iap.getPurchases); + const purchase = purchases.find((p) => + p.productIds.includes(product.productId), + ); purchaseToken = purchase?.purchaseToken; } + + if (!purchaseToken) { + restoreResults.plugins.skipped.push({ + id: pluginName, + reason: strings["paid plugin skipped"], + }); + continue; + } } catch (error) { - helpers.error(error); + restoreResults.plugins.skipped.push({ + id: pluginName, + reason: `Paid plugin - ${error.message}`, + }); + continue; } } - toast("Restoring plugins", 3000); - await installPlugin(id, remotePlugin.name, purchaseToken); + + try { + await installPlugin(id, remotePlugin.name, purchaseToken); + restoreResults.plugins.success.push(pluginName); + } catch (error) { + restoreResults.plugins.failed.push({ + id: pluginName, + reason: error.message, + }); + } } } } catch (error) { console.error(`Error restoring plugin ${id}:`, error); + restoreResults.plugins.failed.push({ + id: pluginName, + reason: error.message, + }); + } + } + } + + // Restore settings last (may trigger reload) + if (selectedOptions.includes("settings") && backup.settings) { + restoreResults.settings.attempted = true; + loaderDialog.setMessage(strings["restoring settings"]); + + try { + // Validate and merge settings carefully + const currentSettings = appSettings.value; + const restoredSettings = backup.settings; + + // Only restore known settings keys to prevent issues with outdated backups + const validSettings = {}; + for (const key of Object.keys(currentSettings)) { + if (key in restoredSettings) { + // Type check before applying + if (typeof restoredSettings[key] === typeof currentSettings[key]) { + validSettings[key] = restoredSettings[key]; + } + } + } + + await appSettings.update(validSettings, false); + restoreResults.settings.success = true; + } catch (error) { + console.error("Error restoring settings:", error); + restoreResults.settings.error = error.message; + } + } + + loaderDialog.destroy(); + + // Build restore summary + const summaryParts = [ + `${strings["restore completed"]}

`, + ]; + + if (restoreResults.settings.attempted) { + const status = restoreResults.settings.success + ? `✓ ${strings.restored}` + : `✗ ${strings.failed}`; + summaryParts.push(`${strings.settings}: ${status}
`); + } + + if (restoreResults.keyBindings.attempted) { + const status = restoreResults.keyBindings.success + ? `✓ ${strings.restored}` + : `✗ ${strings.failed}`; + summaryParts.push(`${strings["key bindings"]}: ${status}
`); + } + + if (restoreResults.plugins.attempted) { + summaryParts.push(`
${strings.plugins}
`); + + if (restoreResults.plugins.success.length > 0) { + summaryParts.push( + `✓ ${strings.restored}: ${restoreResults.plugins.success.length}
`, + ); + } + + if (restoreResults.plugins.failed.length > 0) { + summaryParts.push( + `✗ ${strings.failed}: ${restoreResults.plugins.failed.length}
`, + ); + for (const f of restoreResults.plugins.failed.slice(0, 3)) { + summaryParts.push(`- ${f.id}: ${f.reason}
`); + } + if (restoreResults.plugins.failed.length > 3) { + summaryParts.push( + `...${strings.more || "and"} ${restoreResults.plugins.failed.length - 3} ${strings.more || "more"}
`, + ); + } + } + + if (restoreResults.plugins.skipped.length > 0) { + summaryParts.push( + `${strings.skipped}: ${restoreResults.plugins.skipped.length}
`, + ); + for (const s of restoreResults.plugins.skipped.slice(0, 3)) { + summaryParts.push(`- ${s.id}: ${s.reason}
`); + } + if (restoreResults.plugins.skipped.length > 3) { + summaryParts.push( + `...${strings.more} ${restoreResults.plugins.skipped.length - 3} ${strings.more}
`, + ); } } } - await appSettings.update(settings); - location.reload(); + summaryParts.push(`
${strings["reload to apply"]}`); + + const shouldReload = await confirm( + strings["restore completed"], + summaryParts.join(""), + true, + ); + + // Reload only if user confirms + if (shouldReload) { + location.reload(); + } } catch (err) { - toast(err); + loaderDialog.destroy(); + console.error("Restore error:", err); + alert(strings.error, `${strings["error details"]}: ${err.message || err}`); } }; diff --git a/src/settings/editorSettings.js b/src/settings/editorSettings.js index 0f07feae85..0ba895e3ec 100644 --- a/src/settings/editorSettings.js +++ b/src/settings/editorSettings.js @@ -1,26 +1,111 @@ import settingsPage from "components/settingsPage"; -import constants from "lib/constants"; +import confirm from "dialogs/confirm"; +import config from "lib/config"; import fonts from "lib/fonts"; import appSettings from "lib/settings"; import scrollSettings from "./scrollSettings"; +/** Settings only canvas editors use; shown with the canvas renderer. */ +const CANVAS_ONLY_SETTINGS = [ + "canvasBackend", + "stickyScroll", + "stickyScrollMaxLines", + "canvasGutterMarkers", + "cursorBlinkRate", +]; + export default function editorSettings() { const title = strings["editor settings"]; const values = appSettings.value; + const rendererOptions = [ + ["dom", strings["editor renderer dom"]], + ["canvas", strings["editor renderer canvas"]], + ]; + const canvasBackendOptions = [ + ["auto", strings["canvas backend auto"]], + ["webgl2", "WebGL2"], + ["webgpu", "WebGPU"], + ]; + const gutterMarkerOptions = [ + ["shared", strings["gutter markers shared"]], + ["columns", strings["gutter markers columns"]], + ["overlay", strings["gutter markers overlay"]], + ]; + const wrappingIndentOptions = [ + ["none", strings.none], + ["same", strings["wrap-indent-same"]], + ["indent", strings["wrap-indent-indent"]], + ["deepIndent", strings["wrap-indent-deep"]], + ]; + const categories = { + scrolling: strings["settings-category-scrolling"], + textLayout: strings["settings-category-text-layout"], + editing: strings["settings-category-editing"], + assistance: strings["settings-category-assistance"], + guidesIndicators: strings["settings-category-guides-indicators"], + cursorSelection: strings["settings-category-cursor-selection"], + }; const items = [ { - key: "autosave", - text: strings.autosave.capitalize(), - value: values.autosave, - valueText: (value) => (value ? value : strings.no), - prompt: strings.delay + " (>=1000 || 0)", + key: "scroll-settings", + text: strings["scroll settings"], + info: strings["settings-info-editor-scroll-settings"], + category: categories.scrolling, + chevron: true, + }, + { + key: "editorRenderer", + text: strings["editor renderer"], + value: values.editorRenderer ?? "dom", + valueText: (value) => + rendererOptions.find(([key]) => key === value)?.[1] ?? + rendererOptions[0][1], + select: rendererOptions, + info: strings["settings-info-editor-renderer"], + category: categories.textLayout, + }, + { + key: "canvasBackend", + text: strings["canvas backend"], + value: values.canvasBackend ?? "auto", + valueText: (value) => + canvasBackendOptions.find(([key]) => key === value)?.[1] ?? + canvasBackendOptions[0][1], + select: canvasBackendOptions, + info: strings["settings-info-canvas-backend"], + category: categories.textLayout, + }, + { + key: "stickyScroll", + text: strings["sticky scroll"], + checkbox: values.stickyScroll ?? false, + info: strings["settings-info-sticky-scroll"], + category: categories.textLayout, + }, + { + key: "stickyScrollMaxLines", + text: strings["sticky scroll max lines"], + value: values.stickyScrollMaxLines ?? 5, + prompt: strings["sticky scroll max lines"], promptType: "number", promptOptions: { test(value) { value = Number.parseInt(value); - return value >= 1000 || value === 0; + return value >= 1 && value <= 10; }, }, + info: strings["settings-info-sticky-scroll-max-lines"], + category: categories.textLayout, + }, + { + key: "editorFont", + text: strings["editor font"], + value: values.editorFont, + get select() { + return fonts.getNames(); + }, + info: strings["settings-info-editor-font-family"], + category: categories.textLayout, }, { key: "fontSize", @@ -29,153 +114,303 @@ export default function editorSettings() { prompt: strings["font size"], promptOptions: { required: true, - match: constants.FONT_SIZE, + match: config.FONT_SIZE, }, + info: strings["settings-info-editor-font-size"], + category: categories.textLayout, }, { - key: "softTab", - text: strings["soft tab"], - checkbox: values.softTab, + key: "lineHeight", + text: strings["line height"], + value: values.lineHeight, + prompt: strings["line height"], + promptType: "number", + promptOptions: { + test(value) { + value = Number.parseFloat(value); + return value >= 1 && value <= 2; + }, + }, + info: strings["settings-info-editor-line-height"], + category: categories.textLayout, }, { - key: "tabSize", - text: strings["tab size"], - value: values.tabSize, - prompt: strings["tab size"], + key: "textWrap", + text: strings["text wrap"], + checkbox: values.textWrap, + info: strings["settings-info-editor-text-wrap"], + category: categories.textLayout, + }, + { + key: "wrappingIndent", + text: strings["wrapped line indent"], + value: values.wrappingIndent ?? "same", + valueText: (value) => + wrappingIndentOptions.find(([key]) => key === value)?.[1] ?? + wrappingIndentOptions[1][1], + select: wrappingIndentOptions, + info: strings["settings-info-editor-wrapping-indent"], + category: categories.textLayout, + }, + { + key: "autosave", + text: strings.autosave, + value: values.autosave, + valueText: (value) => (value ? value : strings.no), + prompt: strings.delay + " (>=1000 || 0)", promptType: "number", promptOptions: { test(value) { value = Number.parseInt(value); - return value >= 1 && value <= 8; + return value >= 1000 || value === 0; }, }, + info: strings["settings-info-editor-autosave"], + category: categories.editing, }, { - key: "linenumbers", - text: strings["show line numbers"], - checkbox: values.linenumbers, + key: "softTab", + text: strings["soft tab"], + checkbox: values.softTab, + info: strings["settings-info-editor-soft-tab"], + category: categories.editing, }, { - key: "lineHeight", - text: strings["line height"], - value: values.lineHeight, - prompt: strings["line height"], + key: "tabSize", + text: strings["tab size"], + value: values.tabSize, + prompt: strings["tab size"], promptType: "number", promptOptions: { test(value) { - value = Number.parseFloat(value); - return value >= 1 && value <= 2; + value = Number.parseInt(value); + return value >= 1 && value <= 8; }, }, + info: strings["settings-info-editor-tab-size"], + category: categories.editing, }, { key: "formatOnSave", text: strings["format on save"], checkbox: values.formatOnSave, + info: strings["settings-info-editor-format-on-save"], + category: categories.editing, }, { - key: "showSpaces", - text: strings["show spaces"], - checkbox: values.showSpaces, + key: "liveAutoCompletion", + text: strings["live autocompletion"], + checkbox: values.liveAutoCompletion, + info: strings["settings-info-editor-live-autocomplete"], + category: categories.assistance, }, { - key: "editorFont", - text: strings["editor font"], - value: values.editorFont, - get select() { - return fonts.getNames(); - }, + key: "localWordCompletion", + text: strings["local word completion"], + checkbox: values.localWordCompletion, + info: strings["settings-info-editor-local-word-completion"], + category: categories.assistance, }, { - key: "liveAutoCompletion", - text: strings["live autocompletion"].capitalize(), - checkbox: values.liveAutoCompletion, + key: "languageCompletion", + text: strings["language package completion"], + checkbox: values.languageCompletion ?? true, + info: strings["settings-info-editor-language-completion"], + category: categories.assistance, }, { - key: "showPrintMargin", - text: strings["show print margin"].capitalize(), - checkbox: values.showPrintMargin, + key: "recommendExtensions", + text: strings["recommend extensions"], + checkbox: values.recommendExtensions ?? true, + info: strings["settings-info-editor-recommend-extensions"], + category: categories.assistance, }, { - key: "printMargin", - text: strings["print margin"], - value: values.printMargin, - prompt: strings["print margin"], - promptType: "number", - promptOptions: { - test(value) { - value = Number.parseInt(value); - return value >= 10 && value <= 200; - }, - }, + key: "useEmmet", + text: strings["use emmet"], + checkbox: values.useEmmet ?? true, + category: categories.assistance, }, { - key: "teardropSize", - text: strings["cursor controller size"], - value: values.teardropSize, - valueText(value) { - return this.select.find(([v]) => v === value)[1]; - }, - select: [ - [0, strings.none], - [20, strings.small], - [30, strings.medium], - [60, strings.large], - ], + key: "autoCloseTags", + text: strings["auto close tags"], + checkbox: values.autoCloseTags, + info: strings["settings-info-editor-auto-close-tags"], + category: categories.assistance, + }, + { + key: "autoRenameTags", + text: strings["auto rename tags"], + checkbox: values.autoRenameTags ?? true, + info: strings["settings-info-editor-auto-rename-tags"], + category: categories.assistance, + }, + { + key: "colorPreview", + text: strings["color preview"], + checkbox: values.colorPreview, + info: strings["settings-info-editor-color-preview"], + category: categories.assistance, + }, + { + key: "linenumbers", + text: strings["show line numbers"], + checkbox: values.linenumbers, + info: strings["settings-info-editor-line-numbers"], + category: categories.guidesIndicators, }, { key: "relativeLineNumbers", text: strings["relative line numbers"], checkbox: values.relativeLineNumbers, + info: strings["settings-info-editor-relative-line-numbers"], + category: categories.guidesIndicators, }, { - key: "elasticTabstops", - text: strings["elastic tabstops"], - checkbox: values.elasticTabstops, + key: "lintGutter", + text: strings["lint gutter"] || "Show lint gutter", + checkbox: values.lintGutter ?? true, + info: strings["settings-info-editor-lint-gutter"], + category: categories.guidesIndicators, }, { - key: "rtlText", - text: strings["line based rtl switching"], - checkbox: values.rtlText, + key: "canvasGutterMarkers", + text: strings["gutter markers"], + value: values.canvasGutterMarkers ?? "shared", + valueText: (value) => + gutterMarkerOptions.find(([key]) => key === value)?.[1] ?? + gutterMarkerOptions[0][1], + select: gutterMarkerOptions, + info: strings["settings-info-gutter-markers"], + category: categories.guidesIndicators, }, { - key: "hardWrap", - text: strings["hard wrap"], - checkbox: values.hardWrap, + key: "showSpaces", + text: strings["show spaces"], + checkbox: values.showSpaces, + info: strings["settings-info-editor-show-spaces"], + category: categories.guidesIndicators, }, { - key: "useTextareaForIME", - text: strings["use textarea for ime"], - checkbox: values.useTextareaForIME, + key: "indentGuides", + text: strings["indent guides"] || "Indent guides", + checkbox: values.indentGuides ?? false, + info: strings["settings-info-editor-indent-guides"], + category: categories.guidesIndicators, + }, + { + key: "rainbowBrackets", + text: strings["rainbow brackets"] || "Rainbow brackets", + checkbox: values.rainbowBrackets ?? true, + info: strings["settings-info-editor-rainbow-brackets"], + category: categories.guidesIndicators, }, { key: "fadeFoldWidgets", text: strings["fade fold widgets"], checkbox: values.fadeFoldWidgets, + info: strings["settings-info-editor-fade-fold-widgets"], + category: categories.guidesIndicators, }, { - index: 0, - key: "scroll-settings", - text: strings["scroll settings"], + key: "showShareButton", + text: strings["show share button"], + checkbox: values.showShareButton ?? true, + info: strings["settings-info-editor-show-share-button"], + category: categories.cursorSelection, }, { - key: "colorPreview", - text: strings["color preview"], - checkbox: values.colorPreview, + key: "shiftClickSelection", + text: strings["shift click selection"], + checkbox: values.shiftClickSelection !== false, + info: strings["settings-info-editor-shift-click-selection"], + category: categories.cursorSelection, + }, + { + key: "cursorBlinkRate", + text: strings["cursor blink rate"], + value: values.cursorBlinkRate ?? 1200, + prompt: strings["cursor blink rate"] + " (ms)", + promptType: "number", + promptOptions: { + test(value) { + value = Number.parseInt(value); + return value >= 0 && value <= 10000; + }, + }, + info: strings["settings-info-cursor-blink-rate"], + category: categories.cursorSelection, + }, + { + key: "rtlText", + text: strings["line based rtl switching"], + checkbox: values.rtlText, + info: strings["settings-info-editor-rtl-text"], + category: categories.cursorSelection, }, ]; - return settingsPage(title, items, callback); + for (const item of items) { + if (CANVAS_ONLY_SETTINGS.includes(item.key)) { + item.hidden = !isCanvasSettingVisible(item.key); + } + } + + const page = settingsPage(title, items, callback, undefined, { + preserveOrder: true, + pageClassName: "detail-settings-page", + listClassName: "detail-settings-list", + infoAsDescription: true, + valueInTail: true, + }); + + // The page is created once and kept, so follow the renderer from here. + appSettings.on("update:editorRenderer", updateCanvasSettings); + appSettings.on("update:stickyScroll", updateCanvasSettings); + + return page; + + function isCanvasSettingVisible(key) { + const { editorRenderer, stickyScroll } = appSettings.value; + if (editorRenderer !== "canvas") return false; + return key !== "stickyScrollMaxLines" || !!stickyScroll; + } + + function updateCanvasSettings() { + for (const key of CANVAS_ONLY_SETTINGS) { + page.setItemVisibility(key, isCanvasSettingVisible(key)); + } + } /** * Callback for settings page when an item is clicked * @param {string} key * @param {string} value */ - function callback(key, value) { + async function callback(key, value) { switch (key) { case "scroll-settings": appSettings.uiSettings[key].show(); + return; + + case "editorRenderer": + case "canvasBackend": + // Editors are created with their renderer and backend: reload + // to switch (a backend change only matters to canvas editors). + if (value === appSettings.value[key]) return; + await appSettings.update({ [key]: value }); + if ( + (key === "editorRenderer" || + appSettings.value.editorRenderer === "canvas") && + (await confirm(strings.info, strings["reload to apply"])) + ) { + await reloadApp(); + } + return; + + case "stickyScrollMaxLines": + case "cursorBlinkRate": + appSettings.update({ [key]: Number.parseInt(value) }); break; case "editorFont": @@ -188,4 +423,11 @@ export default function editorSettings() { break; } } + + /** Reload once open files' edits are cached and the session is saved. */ + async function reloadApp() { + await window.editorManager?.flushCacheWrites?.(); + window.acode?.exec("save-state"); + location.reload(); + } } diff --git a/src/settings/filesSettings.js b/src/settings/filesSettings.js index cc23546199..d3ff121205 100644 --- a/src/settings/filesSettings.js +++ b/src/settings/filesSettings.js @@ -15,11 +15,24 @@ export default function filesSettings() { key: "showHiddenFiles", text: strings["show hidden files"], checkbox: values.showHiddenFiles, - info: "Show hidden files and folders. (Start with .)", + info: strings["info-showHiddenFiles"], + }, + { + key: "listFiles", + text: strings["title-listfiles"], + checkbox: values.listFiles !== false, + info: + strings["info-listFiles"] || + "List all files in opened folders for quick search", }, ]; - return settingsPage(title, items, callback); + return settingsPage(title, items, callback, undefined, { + preserveOrder: true, + pageClassName: "detail-settings-page", + listClassName: "detail-settings-list", + groupByDefault: true, + }); function callback(key, value) { appSettings.value.fileBrowser[key] = value; diff --git a/src/settings/formatterSettings.js b/src/settings/formatterSettings.js index 25dae39111..b7d97aed44 100644 --- a/src/settings/formatterSettings.js +++ b/src/settings/formatterSettings.js @@ -1,3 +1,4 @@ +import { getFormatAsMode, getMode, getModes } from "cm/modelist"; import settingsPage from "components/settingsPage"; import appSettings from "lib/settings"; @@ -5,31 +6,68 @@ export default function formatterSettings(languageName) { const title = strings.formatter; const values = appSettings.value; const { formatters } = acode; - const { modes } = ace.require("ace/ext/modelist"); + const languagesLabel = strings.languages || "Languages"; - const items = modes.map((mode) => { - const { name, caption } = mode; - const formatterID = values.formatter[name] || null; - const extensions = mode.extensions.split("|"); - const options = acode.getFormatterFor(extensions); + // Build items from CodeMirror modelist + const items = getModes() + .slice() + .sort((a, b) => + String(a.caption || a.name).localeCompare(String(b.caption || b.name)), + ) + .map((mode) => { + const { name, caption, extensions } = mode; + const formatterID = values.formatter[name] || null; + // Only pass real extensions (skip anchored filename patterns like ^Dockerfile) + const extList = String(extensions) + .split("|") + .filter((e) => e && !e.startsWith("^")); + // Also offer formatters of the mode this one formats as + const baseMode = getMode(getFormatAsMode(name) || ""); + const baseExts = String(baseMode?.extensions || "") + .split("|") + .filter((e) => e && !e.startsWith("^")); + const options = acode.getFormatterFor([...extList, ...baseExts]); + const sampleExt = extList[0] || name; + // Unset falls back to the base mode's formatter, so say which one + const inheritedText = () => { + const inherited = formatters.find( + ({ id }) => id === values.formatter[baseMode.name], + ); + return inherited ? `${inherited.name} (${baseMode.caption})` : null; + }; - return { - key: name, - text: caption, - icon: `file file_type_default file_type_${name}`, - value: formatterID, - valueText: (value) => { - const formatter = formatters.find(({ id }) => id === value); - if (formatter) { - return formatter.name; - } - return strings.none; - }, - select: options, - }; + return { + key: name, + text: caption, + fileIcon: { name: `sample.${sampleExt}` }, + value: formatterID, + valueText: (value) => { + const formatter = formatters.find(({ id }) => id === value); + if (formatter) { + return formatter.name; + } + return (baseMode && inheritedText()) || strings.none; + }, + // Read when the picker opens, so the inherited label stays current + get select() { + if (baseMode) options[0] = [null, inheritedText() || strings.none]; + return options; + }, + chevron: true, + category: languagesLabel, + }; + }); + + items.unshift({ + note: strings["settings-note-formatter-settings"], }); - const page = settingsPage(title, items, callback, "separate"); + const page = settingsPage(title, items, callback, "separate", { + preserveOrder: true, + pageClassName: "detail-settings-page formatter-settings-page", + listClassName: "detail-settings-list formatter-settings-list", + notePosition: "top", + }); page.show(languageName); function callback(key, value) { diff --git a/src/settings/helpSettings.js b/src/settings/helpSettings.js index 56b009bb73..5088e902ca 100644 --- a/src/settings/helpSettings.js +++ b/src/settings/helpSettings.js @@ -1,25 +1,40 @@ import settingsPage from "components/settingsPage"; +import config from "lib/config"; export default function help() { const title = strings.help; const items = [ + { + key: "docs", + text: strings.documentation, + link: config.DOCS_URL, + chevron: true, + }, { key: "help", text: strings.help, - link: "https://telegram.me/foxdebug_acode", + link: config.TELEGRAM_URL, + chevron: true, }, { key: "faqs", text: strings.faqs, - link: "https://acode.app/faqs", + link: `${config.BASE_URL}/faqs`, + chevron: true, }, { key: "bug_report", text: strings.bug_report, - link: "https://github.com/deadlyjack/Acode/issues", + link: `${config.GITHUB_URL}/issues`, + chevron: true, }, ]; - const page = settingsPage(title, items, () => {}, "separate"); + const page = settingsPage(title, items, () => {}, "separate", { + preserveOrder: true, + pageClassName: "detail-settings-page", + listClassName: "detail-settings-list", + groupByDefault: true, + }); page.show(); } diff --git a/src/settings/lspConfigUtils.js b/src/settings/lspConfigUtils.js new file mode 100644 index 0000000000..a7a5bc86d4 --- /dev/null +++ b/src/settings/lspConfigUtils.js @@ -0,0 +1,145 @@ +import lspApi from "cm/lsp/api"; +import appSettings from "lib/settings"; + +function cloneLspSettings() { + return JSON.parse(JSON.stringify(appSettings.value?.lsp || {})); +} + +export function normalizeServerId(id) { + return String(id || "") + .trim() + .toLowerCase(); +} + +export function normalizeLanguages(value) { + if (Array.isArray(value)) { + return value + .map((lang) => + String(lang || "") + .trim() + .toLowerCase(), + ) + .filter(Boolean); + } + + return String(value || "") + .split(",") + .map((lang) => lang.trim().toLowerCase()) + .filter(Boolean); +} + +export function getServerOverride(id) { + return appSettings.value?.lsp?.servers?.[normalizeServerId(id)] || {}; +} + +export function isCustomServer(id) { + return getServerOverride(id).custom === true; +} + +export async function updateServerConfig(serverId, partial) { + const key = normalizeServerId(serverId); + if (!key) { + throw new Error("Server id is required"); + } + + const current = cloneLspSettings(); + current.servers = current.servers || {}; + const nextServer = { + ...(current.servers[key] || {}), + }; + + Object.entries(partial || {}).forEach(([entryKey, value]) => { + if (value === undefined) { + delete nextServer[entryKey]; + return; + } + nextServer[entryKey] = value; + }); + + if (Object.keys(nextServer).length) { + current.servers[key] = nextServer; + } else { + delete current.servers[key]; + } + + await appSettings.update({ lsp: current }, false); +} + +export async function upsertCustomServer(serverId, config) { + const key = normalizeServerId(serverId); + if (!key) { + throw new Error("Server id is required"); + } + + const existingServer = lspApi.servers.get(key); + if (existingServer && getServerOverride(key).custom !== true) { + throw new Error("A built-in server already uses this id"); + } + + const languages = normalizeLanguages(config.languages); + if (!languages.length) { + throw new Error("At least one language id is required"); + } + + const current = cloneLspSettings(); + current.servers = current.servers || {}; + const existing = current.servers[key] || {}; + const hasTransport = Object.prototype.hasOwnProperty.call( + config, + "transport", + ); + const hasLauncher = Object.prototype.hasOwnProperty.call(config, "launcher"); + const nextConfig = { + ...existing, + ...config, + custom: true, + label: config.label || existing.label || key, + languages, + transport: hasTransport + ? config.transport + : existing.transport || { kind: "websocket" }, + launcher: hasLauncher ? config.launcher : existing.launcher, + runtimes: config.runtimes || existing.runtimes, + enabled: config.enabled !== false, + }; + + const installKind = nextConfig.launcher?.install?.kind; + if (installKind && installKind !== "shell") { + const providedExecutable = + nextConfig.launcher.install.binaryPath || + nextConfig.launcher.install.executable; + if (!providedExecutable) { + throw new Error( + "Managed installers must declare the executable path or command they provide", + ); + } + } + + current.servers[key] = nextConfig; + await appSettings.update({ lsp: current }, false); + + const definition = { + id: key, + label: nextConfig.label, + languages, + transport: nextConfig.transport, + launcher: nextConfig.launcher, + runtimes: nextConfig.runtimes, + clientConfig: nextConfig.clientConfig, + initializationOptions: nextConfig.initializationOptions, + startupTimeout: nextConfig.startupTimeout, + enabled: nextConfig.enabled !== false, + }; + + lspApi.upsert(definition); + return key; +} + +export async function removeCustomServer(serverId) { + const key = normalizeServerId(serverId); + const current = cloneLspSettings(); + current.servers = current.servers || {}; + delete current.servers[key]; + await appSettings.update({ lsp: current }, false); + lspApi.servers.unregister(key); +} diff --git a/src/settings/lspServerDetail.js b/src/settings/lspServerDetail.js new file mode 100644 index 0000000000..c84a2a2c7b --- /dev/null +++ b/src/settings/lspServerDetail.js @@ -0,0 +1,807 @@ +import lspApi from "cm/lsp/api"; +import lspClientManager from "cm/lsp/clientManager"; +import { + checkRuntimeServerInstallation, + getRuntimeInstallCommand, + getRuntimeUninstallCommand, + installRuntimeServer, + uninstallRuntimeServer, +} from "cm/lsp/runtimeActions"; +import { stopManagedServer } from "cm/lsp/serverLauncher"; +import settingsPage from "components/settingsPage"; +import toast from "components/toast"; +import alert from "dialogs/alert"; +import confirm from "dialogs/confirm"; +import loader from "dialogs/loader"; +import prompt from "dialogs/prompt"; +import appSettings from "lib/settings"; +import { + getServerOverride, + isCustomServer, + removeCustomServer, + updateServerConfig, +} from "./lspConfigUtils"; + +function getFeatureItems() { + return [ + [ + "ext_hover", + "hover", + strings["lsp-feature-hover"], + strings["lsp-feature-hover-info"], + ], + [ + "ext_completion", + "completion", + strings["lsp-feature-completion"], + strings["lsp-feature-completion-info"], + ], + [ + "ext_signature", + "signature", + strings["lsp-feature-signature"], + strings["lsp-feature-signature-info"], + ], + [ + "ext_diagnostics", + "diagnostics", + strings["lsp-feature-diagnostics"], + strings["lsp-feature-diagnostics-info"], + ], + [ + "ext_inlayHints", + "inlayHints", + strings["lsp-feature-inlay-hints"], + strings["lsp-feature-inlay-hints-info"], + ], + [ + "ext_formatting", + "formatting", + strings["lsp-feature-formatting"], + strings["lsp-feature-formatting-info"], + ], + ]; +} + +function fillTemplate(template, replacements) { + return Object.entries(replacements).reduce( + (result, [key, value]) => result.replaceAll(`{${key}}`, String(value)), + String(template || ""), + ); +} + +function clone(value) { + if (!value || typeof value !== "object") return value; + return JSON.parse(JSON.stringify(value)); +} + +function mergeLauncher(base, patch) { + if (!base && !patch) return undefined; + return { + ...(base || {}), + ...(patch || {}), + bridge: { + ...(base?.bridge || {}), + ...(patch?.bridge || {}), + }, + install: { + ...(base?.install || {}), + ...(patch?.install || {}), + }, + }; +} + +function isDirectWebSocketServer(server) { + return server?.transport?.kind === "websocket" && !server?.launcher?.bridge; +} + +function getMergedConfig(server) { + const override = getServerOverride(server.id); + return { + ...server, + enabled: override.enabled ?? server.enabled, + startupTimeout: override.startupTimeout ?? server.startupTimeout, + initializationOptions: { + ...(server.initializationOptions || {}), + ...(override.initializationOptions || {}), + }, + clientConfig: { + ...(server.clientConfig || {}), + ...(override.clientConfig || {}), + builtinExtensions: { + ...(server.clientConfig?.builtinExtensions || {}), + ...(override.clientConfig?.builtinExtensions || {}), + }, + }, + launcher: mergeLauncher(server.launcher, override.launcher), + runtimes: override.runtimes || server.runtimes, + }; +} + +function formatInstallStatus(result) { + switch (result?.status) { + case "present": + return result.version + ? fillTemplate(strings["lsp-status-installed-version"], { + version: result.version, + }) + : strings["lsp-status-installed"]; + case "missing": + return strings["lsp-status-not-installed"]; + case "failed": + return strings["lsp-status-check-failed"]; + default: + return strings["lsp-status-unknown"]; + } +} + +function formatStatusLabel(result) { + switch (result?.status) { + case "present": + return strings["lsp-status-installed"]; + case "missing": + return strings["lsp-status-not-installed"]; + case "failed": + return strings["lsp-status-check-failed"]; + default: + return strings["lsp-status-unknown"]; + } +} + +function formatStartupTimeoutValue(timeout) { + return typeof timeout === "number" + ? fillTemplate(strings["lsp-timeout-ms"], { timeout }) + : strings["lsp-default"]; +} + +// PRoot prints `can't sanitize binding "/proc/self/fd/N"` when one of the +// session's stdio descriptors is a pipe/socket and therefore cannot be +// canonicalized (see init-sandbox.sh). Drop only that known, harmless message +// so genuine proot warnings still reach the UI. +const PROOT_FD_BINDING_WARNING = + /can'?t sanitize binding "\/proc\/self\/fd(?:\/[012])?"/i; + +function sanitizeInstallMessage(message) { + const lines = String(message || "") + .split("\n") + .map((line) => line.trim()) + .filter(Boolean) + .filter((line) => !PROOT_FD_BINDING_WARNING.test(line)); + + return lines.join(" "); +} + +function formatInstallInfo(result) { + const cleanedMessage = sanitizeInstallMessage(result?.message); + + switch (result?.status) { + case "present": + return result.version + ? fillTemplate(strings["lsp-install-info-version-available"], { + version: result.version, + }) + : strings["lsp-install-info-ready"]; + case "missing": + return strings["lsp-install-info-missing"]; + case "failed": + return cleanedMessage || strings["lsp-install-info-check-failed"]; + default: + return cleanedMessage || strings["lsp-install-info-unknown"]; + } +} + +function formatValue(value) { + if (value === undefined || value === null || value === "") return ""; + let text = String(value); + if (text.includes("\n")) { + [text] = text.split("\n"); + } + if (text.length > 47) { + text = `${text.slice(0, 47)}...`; + } + return text; +} + +function escapeHtml(text) { + const div = document.createElement("div"); + div.textContent = String(text || ""); + return div.innerHTML; +} + +function updateItemDisplay($list, itemsByKey, key, value, extras = {}) { + const item = itemsByKey.get(key); + if (!item) return; + + if ("value" in extras) { + item.value = extras.value; + } else if (value !== undefined) { + item.value = value; + } + + if ("info" in extras) { + item.info = extras.info; + } + + if ("checkbox" in extras) { + item.checkbox = extras.checkbox; + } + + if ("text" in extras) { + item.text = extras.text; + } + + const $item = $list?.querySelector?.(`[data-key="${key}"]`); + if (!$item) return; + + if (extras.text !== undefined) { + const $text = $item.querySelector(".text"); + if ($text) $text.textContent = extras.text; + } + + const $subtitle = $item.querySelector(".value"); + if ($subtitle) { + $subtitle.textContent = $subtitle.classList.contains("setting-info") + ? String(item.info || "") + : formatValue(item.value); + } + + const $trailingValue = $item.querySelector(".setting-trailing-value"); + if ($trailingValue) { + $trailingValue.textContent = formatValue(item.value); + } + + const $checkbox = $item.querySelector(".input-checkbox"); + if ($checkbox && typeof item.checkbox === "boolean") { + $checkbox.checked = item.checkbox; + } +} + +function getConnectedServerList(serverId, preferredList) { + if (preferredList?.isConnected) return preferredList; + + return Array.from( + document.querySelectorAll(".detail-settings-list[data-lsp-server-id]"), + ).find( + ($list) => + $list.isConnected && $list.dataset.lspServerId === String(serverId), + ); +} + +async function buildSnapshot(serverId) { + const liveServer = lspApi.servers.get(serverId); + if (!liveServer) return null; + + const merged = getMergedConfig(liveServer); + const override = getServerOverride(serverId); + const directWebSocket = isDirectWebSocketServer(merged); + const installResult = await checkRuntimeServerInstallation(merged).catch( + (error) => ({ + status: "failed", + version: null, + canInstall: true, + canUpdate: true, + message: error instanceof Error ? error.message : String(error), + }), + ); + + return { + liveServer, + merged, + override, + directWebSocket, + isCustom: isCustomServer(serverId), + installResult, + builtinExts: merged.clientConfig?.builtinExtensions || {}, + installCommand: await getRuntimeInstallCommand(merged, "install"), + updateCommand: await getRuntimeInstallCommand(merged, "update"), + uninstallCommand: await getRuntimeUninstallCommand(merged), + }; +} + +function createItems(snapshot) { + const featureItems = getFeatureItems(); + const categories = { + general: strings["settings-category-general"], + installation: strings["settings-category-installation"], + advanced: strings["settings-category-advanced"], + features: strings["settings-category-features"], + }; + const items = [ + { + key: "enabled", + text: strings["lsp-enabled"], + checkbox: snapshot.merged.enabled !== false, + info: strings["settings-info-lsp-server-enabled"], + category: categories.general, + }, + ...(snapshot.isCustom + ? [ + { + key: "remove_custom_server", + text: strings["lsp-remove-custom-server"], + info: strings["settings-info-lsp-remove-custom-server"], + category: categories.general, + chevron: true, + }, + ] + : []), + { + key: "startup_timeout", + text: strings["lsp-startup-timeout"], + value: formatStartupTimeoutValue(snapshot.merged.startupTimeout), + info: strings["settings-info-lsp-startup-timeout"], + category: categories.advanced, + chevron: true, + }, + { + key: "edit_init_options", + text: strings["lsp-edit-initialization-options"], + value: Object.keys(snapshot.override.initializationOptions || {}).length + ? strings["lsp-configured"] + : strings["lsp-empty"], + info: strings["settings-info-lsp-edit-init-options"], + category: categories.advanced, + chevron: true, + }, + { + key: "view_init_options", + text: strings["lsp-view-initialization-options"], + info: strings["settings-info-lsp-view-init-options"], + category: categories.advanced, + chevron: true, + }, + ]; + + const installationItems = [ + { + key: "install_status", + text: formatStatusLabel(snapshot.installResult), + info: formatInstallInfo(snapshot.installResult), + category: categories.installation, + chevron: true, + }, + ]; + if ( + snapshot.installCommand || + snapshot.installResult?.canInstall || + !snapshot.directWebSocket + ) { + installationItems.push({ + key: "install_server", + text: strings["lsp-install-repair"], + info: strings["settings-info-lsp-install-server"], + category: categories.installation, + chevron: true, + }); + } + if ( + snapshot.updateCommand || + snapshot.installResult?.canUpdate || + !snapshot.directWebSocket + ) { + installationItems.push({ + key: "update_server", + text: strings["lsp-update-server"], + info: strings["settings-info-lsp-update-server"], + category: categories.installation, + chevron: true, + }); + } + if (snapshot.uninstallCommand || !snapshot.directWebSocket) { + installationItems.push({ + key: "uninstall_server", + text: strings["lsp-uninstall-server"], + info: strings["settings-info-lsp-uninstall-server"], + category: categories.installation, + chevron: true, + }); + } + + items.splice(2, 0, ...installationItems); + + featureItems.forEach(([key, extKey, text, info]) => { + items.push({ + key, + text, + checkbox: isBuiltinFeatureEnabled(snapshot.builtinExts, extKey), + info, + category: categories.features, + }); + }); + + return items; +} + +async function refreshVisibleState($list, itemsByKey, serverId) { + if (!$list) return; + + const snapshot = await buildSnapshot(serverId); + if (!snapshot) return; + + updateItemDisplay($list, itemsByKey, "enabled", undefined, { + checkbox: snapshot.merged.enabled !== false, + }); + updateItemDisplay($list, itemsByKey, "install_status", undefined, { + info: formatInstallInfo(snapshot.installResult), + text: formatStatusLabel(snapshot.installResult), + }); + updateItemDisplay($list, itemsByKey, "install_server", ""); + updateItemDisplay($list, itemsByKey, "update_server", ""); + updateItemDisplay($list, itemsByKey, "uninstall_server", ""); + + const $installItem = $list.querySelector('[data-key="install_server"]'); + if ($installItem) { + $installItem.style.display = + snapshot.installCommand || snapshot.installResult?.canInstall + ? "" + : "none"; + } + const $updateItem = $list.querySelector('[data-key="update_server"]'); + if ($updateItem) { + $updateItem.style.display = + snapshot.updateCommand || snapshot.installResult?.canUpdate ? "" : "none"; + } + const $uninstallItem = $list.querySelector('[data-key="uninstall_server"]'); + if ($uninstallItem) { + $uninstallItem.style.display = snapshot.uninstallCommand ? "" : "none"; + } + + updateItemDisplay( + $list, + itemsByKey, + "startup_timeout", + formatStartupTimeoutValue(snapshot.merged.startupTimeout), + ); + updateItemDisplay( + $list, + itemsByKey, + "edit_init_options", + Object.keys(snapshot.override.initializationOptions || {}).length + ? strings["lsp-configured"] + : strings["lsp-empty"], + ); + + getFeatureItems().forEach(([key, extKey]) => { + updateItemDisplay($list, itemsByKey, key, undefined, { + checkbox: isBuiltinFeatureEnabled(snapshot.builtinExts, extKey), + }); + }); +} + +function isBuiltinFeatureEnabled(builtinExts, extKey) { + if (extKey === "inlayHints") { + return builtinExts?.[extKey] === true; + } + return builtinExts?.[extKey] !== false; +} + +async function persistEnabled(serverId, value) { + await updateServerConfig(serverId, { enabled: value }); + lspApi.servers.update(serverId, (current) => ({ + ...current, + enabled: value, + })); +} + +async function persistClientConfig(serverId, clientConfig) { + await updateServerConfig(serverId, { clientConfig }); + lspApi.servers.update(serverId, (current) => ({ + ...current, + clientConfig: { + ...(current.clientConfig || {}), + ...clientConfig, + builtinExtensions: { + ...(current.clientConfig?.builtinExtensions || {}), + ...(clientConfig.builtinExtensions || {}), + }, + }, + })); +} + +async function persistStartupTimeout(serverId, timeout) { + await updateServerConfig(serverId, { startupTimeout: timeout }); + lspApi.servers.update(serverId, (current) => ({ + ...current, + startupTimeout: timeout, + })); +} + +async function persistInitOptions(serverId, value) { + await updateServerConfig(serverId, { initializationOptions: value }); + lspApi.servers.update(serverId, (current) => ({ + ...current, + initializationOptions: value, + })); +} + +export default function lspServerDetail(serverId) { + const initialServer = lspApi.servers.get(serverId); + if (!initialServer) { + toast(strings["lsp-server-not-found"]); + return null; + } + + const directWebSocket = isDirectWebSocketServer( + getMergedConfig(initialServer), + ); + const initialSnapshot = { + liveServer: initialServer, + merged: getMergedConfig(initialServer), + override: getServerOverride(serverId), + directWebSocket, + isCustom: isCustomServer(serverId), + installResult: { + status: "unknown", + version: null, + canInstall: !directWebSocket, + canUpdate: !directWebSocket, + message: strings["lsp-checking-installation-status"], + }, + builtinExts: + getMergedConfig(initialServer).clientConfig?.builtinExtensions || {}, + installCommand: null, + updateCommand: null, + uninstallCommand: null, + }; + + const items = createItems(initialSnapshot); + const itemsByKey = new Map(items.map((item) => [item.key, item])); + const page = settingsPage( + initialServer.label || initialServer.id, + items, + callback, + undefined, + { + preserveOrder: true, + pageClassName: "detail-settings-page", + listClassName: "detail-settings-list", + valueInTail: true, + }, + ); + const $pageList = page.getListElement(); + $pageList.dataset.lspServerId = String(serverId); + + const baseShow = page.show.bind(page); + + return { + ...page, + show(goTo) { + baseShow(goTo); + refreshVisibleState($pageList, itemsByKey, serverId).catch(console.error); + }, + }; + + async function callback(key, value) { + const isSwitch = + key === "enabled" || + [ + "ext_hover", + "ext_completion", + "ext_signature", + "ext_diagnostics", + "ext_inlayHints", + "ext_formatting", + ].includes(key); + const $loader = isSwitch + ? null + : loader.create("LSP", strings["loading..."]); + + try { + const snapshot = await buildSnapshot(serverId); + if (!snapshot) { + toast(strings["lsp-server-not-found"]); + return; + } + + switch (key) { + case "enabled": + await persistEnabled(serverId, value); + if (!value) { + await lspClientManager.disposeServer(serverId); + stopManagedServer(serverId); + } + toast( + value + ? strings["lsp-server-enabled-toast"] + : strings["lsp-server-disabled-toast"], + ); + break; + + case "remove_custom_server": + $loader?.hide(); + if ( + !(await confirm( + strings["lsp-remove-custom-server"], + fillTemplate(strings["lsp-remove-custom-server-confirm"], { + server: snapshot.liveServer.label || serverId, + }), + )) + ) { + break; + } + $loader?.show(); + await lspClientManager.disposeServer(serverId); + stopManagedServer(serverId); + await removeCustomServer(serverId); + toast(strings["lsp-custom-server-removed"]); + page.hide(); + appSettings.uiSettings["lsp-settings"]?.show(); + return; + + case "install_status": { + const result = await checkRuntimeServerInstallation(snapshot.merged); + $loader?.hide(); + const lines = [ + fillTemplate(strings["lsp-status-line"], { + status: formatInstallStatus(result), + }), + result.version + ? fillTemplate(strings["lsp-version-line"], { + version: result.version, + }) + : null, + fillTemplate(strings["lsp-details-line"], { + details: formatInstallInfo(result), + }), + ].filter(Boolean); + alert(strings["lsp-installation-status"], lines.join("
")); + break; + } + + case "install_server": + if (!snapshot.installCommand) { + toast(strings["lsp-install-command-unavailable"]); + break; + } + await installRuntimeServer(snapshot.merged, "install"); + break; + + case "update_server": + if (!snapshot.updateCommand) { + toast(strings["lsp-update-command-unavailable"]); + break; + } + await installRuntimeServer(snapshot.merged, "update"); + break; + + case "uninstall_server": + if (!snapshot.uninstallCommand) { + toast(strings["lsp-uninstall-command-unavailable"]); + break; + } + $loader?.hide(); + if ( + !(await confirm( + strings["lsp-uninstall-server"], + fillTemplate(strings["lsp-remove-installed-files"], { + server: snapshot.liveServer.label || serverId, + }), + )) + ) { + break; + } + $loader?.show(); + await uninstallRuntimeServer(snapshot.merged); + toast(strings["lsp-server-uninstalled"]); + break; + + case "startup_timeout": { + const currentTimeout = + snapshot.override.startupTimeout ?? + snapshot.liveServer.startupTimeout ?? + 5000; + $loader?.hide(); + const result = await prompt( + strings["lsp-startup-timeout-ms"], + String(currentTimeout), + "number", + { + test: (val) => { + const timeout = Number.parseInt(String(val), 10); + return Number.isFinite(timeout) && timeout >= 1000; + }, + }, + ); + + if (result === null) { + break; + } + + const timeout = Number.parseInt(String(result), 10); + if (!Number.isFinite(timeout) || timeout < 1000) { + toast(strings["lsp-invalid-timeout"]); + break; + } + + $loader?.show(); + await persistStartupTimeout(serverId, timeout); + toast( + fillTemplate(strings["lsp-startup-timeout-set"], { + timeout, + }), + ); + break; + } + + case "edit_init_options": { + const currentJson = JSON.stringify( + snapshot.override.initializationOptions || {}, + null, + 2, + ); + $loader?.hide(); + const result = await prompt( + strings["lsp-initialization-options-json"], + currentJson || "{}", + "textarea", + { + test: (val) => { + try { + JSON.parse(val); + return true; + } catch { + return false; + } + }, + }, + ); + + if (result === null) { + break; + } + + $loader?.show(); + await persistInitOptions(serverId, JSON.parse(result)); + toast(strings["lsp-initialization-options-updated"]); + break; + } + + case "view_init_options": { + const json = JSON.stringify( + snapshot.merged.initializationOptions || {}, + null, + 2, + ); + $loader?.hide(); + alert( + strings["lsp-initialization-options"], + `

${escapeHtml(json)}
`, + ); + break; + } + + case "ext_hover": + case "ext_completion": + case "ext_signature": + case "ext_diagnostics": + case "ext_inlayHints": + case "ext_formatting": { + const extKey = key.replace("ext_", ""); + const currentClientConfig = clone( + snapshot.override.clientConfig || {}, + ); + const currentBuiltins = currentClientConfig.builtinExtensions || {}; + + await persistClientConfig(serverId, { + ...currentClientConfig, + builtinExtensions: { + ...currentBuiltins, + [extKey]: value, + }, + }); + break; + } + + default: + break; + } + + const $connectedList = getConnectedServerList(serverId, $pageList); + if ($connectedList) { + await refreshVisibleState($connectedList, itemsByKey, serverId); + } + } finally { + $loader?.destroy(); + } + } +} diff --git a/src/settings/lspSettings.js b/src/settings/lspSettings.js new file mode 100644 index 0000000000..6a9b418034 --- /dev/null +++ b/src/settings/lspSettings.js @@ -0,0 +1,452 @@ +import { quoteArg } from "cm/lsp/installRuntime"; +import serverRegistry from "cm/lsp/serverRegistry"; +import { builtinServers } from "cm/lsp/servers"; +import settingsPage from "components/settingsPage"; +import toast from "components/toast"; +import prompt from "dialogs/prompt"; +import select from "dialogs/select"; +import appSettings from "lib/settings"; +import { + getServerOverride, + isCustomServer, + normalizeLanguages, + normalizeServerId, + upsertCustomServer, +} from "./lspConfigUtils"; +import lspServerDetail from "./lspServerDetail"; + +function parseArgsInput(value) { + const normalized = String(value || "").trim(); + if (!normalized) return []; + + const parsed = JSON.parse(normalized); + if (!Array.isArray(parsed)) { + throw new Error(strings["lsp-error-args-must-be-array"]); + } + return parsed.map((entry) => String(entry)); +} + +function normalizePackages(value) { + return String(value || "") + .split(",") + .map((entry) => entry.trim()) + .filter(Boolean); +} + +function getInstallMethods() { + return [ + { value: "manual", text: strings["lsp-install-method-manual"] }, + { value: "apk", text: strings["lsp-install-method-apk"] }, + { value: "npm", text: strings["lsp-install-method-npm"] }, + { value: "pip", text: strings["lsp-install-method-pip"] }, + { value: "cargo", text: strings["lsp-install-method-cargo"] }, + { value: "shell", text: strings["lsp-install-method-shell"] }, + ]; +} + +function getTransportMethods() { + return [ + { + value: "stdio", + text: + strings["lsp-transport-method-stdio"] || + "STDIO (launch a binary command)", + }, + { + value: "websocket", + text: + strings["lsp-transport-method-websocket"] || + "WebSocket (connect to a ws/wss URL)", + }, + ]; +} + +function parseWebSocketUrl(value) { + const normalized = String(value || "").trim(); + if (!normalized) { + throw new Error( + strings["lsp-error-websocket-url-required"] || + "WebSocket URL is required", + ); + } + if (!/^wss?:\/\//i.test(normalized)) { + throw new Error( + strings["lsp-error-websocket-url-invalid"] || + "WebSocket URL must start with ws:// or wss://", + ); + } + return normalized; +} + +function buildDefaultCheckCommand(binaryCommand, installer) { + const executable = String( + installer?.binaryPath || installer?.executable || binaryCommand || "", + ).trim(); + if (!executable) return ""; + if (installer?.kind === "manual" && installer?.binaryPath) { + return `test -x ${quoteArg(installer.binaryPath)}`; + } + if (executable.includes("/")) { + return `test -x ${quoteArg(executable)}`; + } + return `which ${quoteArg(executable)}`; +} + +async function promptInstaller(binaryCommand) { + const method = await select( + strings["lsp-install-method-title"], + getInstallMethods(), + ); + if (!method) return null; + + switch (method) { + case "manual": { + const binaryPath = await prompt( + strings["lsp-binary-path-optional"], + String(binaryCommand || "").includes("/") ? String(binaryCommand) : "", + "text", + ); + if (binaryPath === null) return null; + return { + kind: "manual", + source: "manual", + executable: String(binaryCommand || "").trim() || undefined, + binaryPath: String(binaryPath || "").trim() || undefined, + }; + } + case "apk": + case "npm": + case "pip": + case "cargo": { + const packagesInput = await prompt( + strings["lsp-packages-prompt"].replace( + "{method}", + method.toUpperCase(), + ), + "", + "text", + ); + if (packagesInput === null) return null; + const packages = normalizePackages(packagesInput); + if (!packages.length) { + throw new Error(strings["lsp-error-package-required"]); + } + return { + kind: method, + source: method, + executable: String(binaryCommand || "").trim() || undefined, + packages, + }; + } + case "shell": { + const installCommand = await prompt( + strings["lsp-install-command"], + "", + "textarea", + ); + if (installCommand === null) return null; + const updateCommand = await prompt( + strings["lsp-update-command-optional"], + String(installCommand || ""), + "textarea", + ); + if (updateCommand === null) return null; + return { + kind: "shell", + source: "custom", + executable: String(binaryCommand || "").trim() || undefined, + command: String(installCommand || "").trim() || undefined, + updateCommand: String(updateCommand || "").trim() || undefined, + }; + } + default: + return null; + } +} + +/** + * LSP Settings page - shows list of all language servers + * @returns {object} Settings page interface + */ +export default function lspSettings() { + const title = + strings?.lsp_settings || strings["language servers"] || "Language Servers"; + const categories = { + customServers: strings["settings-category-custom-servers"], + behavior: strings["settings-category-behavior"] || "Behavior", + builtinServers: + strings["settings-category-builtin-servers"] || "Built-in servers", + pluginServers: + strings["settings-category-plugin-servers"] || "Plugin servers", + }; + let page = createPage(); + + return { + show(goTo) { + page = createPage(); + page.show(goTo); + }, + hide() { + page.hide(); + }, + search(key) { + page = createPage(); + return page.search(key); + }, + restoreList() { + page.restoreList(); + }, + setTitle(nextTitle) { + page.setTitle(nextTitle); + }, + }; + + function createPage() { + const servers = serverRegistry.listServers(); + + const sortedServers = servers.sort((a, b) => { + const aEnabled = getServerOverride(a.id).enabled ?? a.enabled; + const bEnabled = getServerOverride(b.id).enabled ?? b.enabled; + + if (aEnabled !== bEnabled) { + return bEnabled ? 1 : -1; + } + return a.label.localeCompare(b.label); + }); + + const builtinServersList = []; + const pluginServersList = []; + const customServersList = []; + + for (const server of sortedServers) { + const source = server.launcher?.install?.source + ? ` • ${server.launcher.install.source}` + : ""; + const languagesList = + Array.isArray(server.languages) && server.languages.length + ? `${server.languages.join(", ")}${source}` + : source.slice(3); + + const serverItem = { + key: `server:${server.id}`, + text: server.label, + info: languagesList || undefined, + chevron: true, + }; + + if (builtinServers.some((s) => s.id === server.id)) { + serverItem.category = categories.builtinServers; + builtinServersList.push(serverItem); + } else if (isCustomServer(server.id)) { + serverItem.category = categories.customServers; + customServersList.push(serverItem); + } else { + serverItem.category = categories.pluginServers; + pluginServersList.push(serverItem); + } + } + + const items = [ + { + key: "allow_non_terminal_workspace", + text: strings["lsp-allow-non-terminal-workspace"], + checkbox: appSettings.value.lsp?.allowNonTerminalWorkspace === true, + info: strings["settings-info-lsp-allow-non-terminal-workspace"], + category: categories.behavior, + }, + ...builtinServersList, + ...pluginServersList, + { + key: "add_custom_server", + text: strings["lsp-add-custom-server"], + info: strings["settings-info-lsp-add-custom-server"], + category: categories.customServers, + chevron: true, + }, + ...customServersList, + ]; + + items.push({ + note: strings["settings-note-lsp-settings"], + }); + + return settingsPage(title, items, callback, undefined, { + preserveOrder: true, + pageClassName: "detail-settings-page", + listClassName: "detail-settings-list", + groupByDefault: true, + }); + } + + function refreshVisiblePage() { + page.hide(); + page = createPage(); + page.show(); + } + + async function callback(key, value) { + if (key === "allow_non_terminal_workspace") { + await appSettings.update({ + lsp: { + ...(appSettings.value.lsp || {}), + allowNonTerminalWorkspace: value === true, + }, + }); + return; + } + + if (key === "add_custom_server") { + try { + const idInput = await prompt(strings["lsp-server-id"], "", "text"); + if (idInput === null) return; + + const serverId = normalizeServerId(idInput); + if (!serverId) { + toast(strings["lsp-error-server-id-required"]); + return; + } + + const label = await prompt( + strings["lsp-server-label"], + serverId, + "text", + ); + if (label === null) return; + + const languageInput = await prompt( + strings["lsp-language-ids"], + "", + "text", + ); + if (languageInput === null) return; + const languages = normalizeLanguages(languageInput); + if (!languages.length) { + toast(strings["lsp-error-language-id-required"]); + return; + } + + const transportKind = await select( + strings.type || "Type", + getTransportMethods(), + ); + if (!transportKind) return; + + let transport; + let launcher; + + if (transportKind === "websocket") { + const websocketUrlInput = await prompt( + strings["lsp-websocket-url"] || "WebSocket URL", + "ws://127.0.0.1:3000/", + "text", + { + test: (value) => { + try { + parseWebSocketUrl(value); + return true; + } catch { + return false; + } + }, + }, + ); + if (websocketUrlInput === null) return; + + transport = { + kind: "websocket", + url: parseWebSocketUrl(websocketUrlInput), + }; + } else { + const binaryCommand = await prompt( + strings["lsp-binary-command"], + "", + "text", + ); + if (binaryCommand === null) return; + if (!String(binaryCommand).trim()) { + toast(strings["lsp-error-binary-command-required"]); + return; + } + + const argsInput = await prompt( + strings["lsp-binary-args"], + "[]", + "textarea", + { + test: (value) => { + try { + parseArgsInput(value); + return true; + } catch { + return false; + } + }, + }, + ); + if (argsInput === null) return; + + const parsedArgs = parseArgsInput(argsInput); + const installer = await promptInstaller(binaryCommand); + if (installer === null) return; + const defaultCheckCommand = buildDefaultCheckCommand( + binaryCommand, + installer, + ); + + const checkCommand = await prompt( + strings["lsp-check-command-optional"], + defaultCheckCommand, + "text", + { + placeholder: defaultCheckCommand || "which my-language-server", + }, + ); + if (checkCommand === null) return; + + transport = { + kind: "stdio", + command: String(binaryCommand).trim(), + args: parsedArgs, + }; + launcher = { + bridge: { + kind: "axs", + command: String(binaryCommand).trim(), + args: parsedArgs, + }, + checkCommand: String(checkCommand || "").trim() || undefined, + install: installer, + }; + } + + await upsertCustomServer(serverId, { + label: String(label || "").trim() || serverId, + languages, + transport, + launcher, + enabled: true, + }); + + toast(strings["lsp-custom-server-added"]); + refreshVisiblePage(); + const detailPage = lspServerDetail(serverId); + detailPage?.show(); + } catch (error) { + toast( + error instanceof Error + ? error.message + : strings["lsp-error-add-server-failed"], + ); + } + return; + } + + if (key.startsWith("server:")) { + const id = key.split(":")[1]; + const detailPage = lspServerDetail(id); + if (detailPage) { + detailPage.show(); + } + } + } +} diff --git a/src/settings/mainSettings.js b/src/settings/mainSettings.js index 3df4c3dfc2..f65f4c8132 100644 --- a/src/settings/mainSettings.js +++ b/src/settings/mainSettings.js @@ -2,10 +2,16 @@ import settingsPage from "components/settingsPage"; import confirm from "dialogs/confirm"; import rateBox from "dialogs/rateBox"; import actionStack from "lib/actionStack"; +import { APP_ICONS } from "lib/appIcons"; +import config from "lib/config"; import openFile from "lib/openFile"; -import removeAds from "lib/removeAds"; +import { bindPrivacyChoices } from "lib/privacyChoicesController.mjs"; +import { requestProPurchase } from "lib/removeAds"; import appSettings from "lib/settings"; import settings from "lib/settings"; +import { showPrivacyOptions, subscribePrivacyState } from "lib/startAd"; +import openAdRewardsPage from "pages/adRewards"; +import appIconSetting, { preloadAppIconSetting } from "pages/appIconSetting"; import Changelog from "pages/changelog/changelog"; import plugins from "pages/plugins"; import Sponsors from "pages/sponsors"; @@ -17,99 +23,210 @@ import backupRestore from "./backupRestore"; import editorSettings from "./editorSettings"; import filesSettings from "./filesSettings"; import formatterSettings from "./formatterSettings"; +import lspSettings from "./lspSettings"; import previewSettings from "./previewSettings"; import scrollSettings from "./scrollSettings"; import searchSettings from "./searchSettings"; import terminalSettings from "./terminalSettings"; export default function mainSettings() { + preloadAppIconSetting(); const title = strings.settings.capitalize(); + const categories = { + core: strings["settings-category-core"], + customization: + strings["settings-category-customization"] || "Customization", + tools: strings["settings-category-tools"] || "Tools", + maintenance: strings["settings-category-maintenance"], + aboutAcode: strings["settings-category-about-acode"], + supportAcode: strings["settings-category-support-acode"], + }; const items = [ { - key: "about", - text: strings.about, - icon: "acode", - index: 0, - }, - { - key: "sponsors", - text: strings.sponsor, - icon: "favorite", - iconColor: "orangered", - index: 1, + key: "app-settings", + text: strings["app settings"], + icon: "tune", + info: strings["settings-info-main-app-settings"], + category: categories.core, + chevron: true, }, { key: "editor-settings", text: strings["editor settings"], icon: "text_format", - index: 3, + info: strings["settings-info-main-editor-settings"], + category: categories.core, + chevron: true, }, { - key: "app-settings", - text: strings["app settings"], - icon: "tune", - index: 2, + key: "terminal-settings", + text: `${strings["terminal settings"]}`, + icon: "terminal", + info: strings["settings-info-main-terminal-settings"], + category: categories.core, + chevron: true, }, { - key: "formatter", - text: strings.formatter, - icon: "stars", + key: "preview-settings", + text: strings["preview settings"], + icon: "public", + info: strings["settings-info-main-preview-settings"], + category: categories.core, + chevron: true, }, { key: "theme", text: strings.theme, icon: "color_lenspalette", + info: strings["settings-info-main-theme"], + category: categories.customization, + chevron: true, }, { - key: "backup-restore", - text: strings.backup.capitalize() + "/" + strings.restore.capitalize(), - icon: "cached", + key: "appIcon", + text: strings["app icon"] || "App icon", + image: getAppIconImage(), + info: + strings["settings-info-app-icon"] || + "Choose the app icon displayed on your device.", + category: categories.customization, + chevron: true, }, { - key: "rateapp", - text: strings["rate acode"], - icon: "googleplay", + key: "formatter", + text: strings.formatter, + icon: "spellcheck", + info: strings["settings-info-main-formatter"], + category: categories.tools, + chevron: true, }, { key: "plugins", text: strings["plugins"], icon: "extension", + info: strings["settings-info-main-plugins"], + category: categories.tools, + chevron: true, }, { - key: "reset", - text: strings["restore default settings"], - icon: "historyrestore", - index: 6, + key: "lsp-settings", + text: + strings?.lsp_settings || + strings["language servers"] || + "Language servers", + icon: "zap", + info: strings["settings-info-main-lsp-settings"], + category: categories.tools, + chevron: true, }, { - key: "preview-settings", - text: strings["preview settings"], - icon: "play_arrow", - index: 4, - }, - { - key: "terminal-settings", - text: `${strings["terminal settings"]}`, - icon: "licons terminal", - index: 5, + key: "backup-restore", + text: `${strings.backup.capitalize()} & ${strings.restore.capitalize()}`, + icon: "cached", + info: strings["settings-info-main-backup-restore"], + category: categories.maintenance, + chevron: true, }, { key: "editSettings", text: `${strings["edit"]} settings.json`, icon: "edit", + info: strings["settings-info-main-edit-settings"], + category: categories.maintenance, + chevron: true, + }, + { + key: "reset", + text: strings["restore default settings"], + icon: "historyrestore", + info: strings["settings-info-main-reset"], + category: categories.maintenance, + chevron: true, + }, + { + key: "about", + text: strings.about, + icon: "info", + info: `Version ${BuildInfo.version}`, + category: categories.aboutAcode, + chevron: true, + }, + { + key: "sponsors", + text: strings.sponsor, + icon: "favorite", + info: strings["settings-info-main-sponsors"], + category: categories.aboutAcode, + chevron: true, }, { key: "changeLog", text: `${strings["changelog"]}`, icon: "update", + info: strings["settings-info-main-changelog"], + category: categories.aboutAcode, + chevron: true, + }, + { + key: "rateapp", + text: strings["rate acode"], + icon: "star_outline", + info: strings["settings-info-main-rateapp"], + category: categories.aboutAcode, + chevron: true, }, ]; - if (IS_FREE_VERSION) { + if (!config.HAS_PRO) { + const aboutIndex = items.findIndex((item) => item.key === "about"); + items.splice(aboutIndex, 0, { + key: "privacyChoices", + text: strings["privacy choices"] || "Privacy choices", + icon: "tune", + info: + strings["settings-info-main-privacy-choices"] || + "Manage your advertising privacy choices.", + category: categories.aboutAcode, + chevron: true, + hidden: true, + }); + } + + if (!config.HAS_PRO) { + items.push({ + key: "adRewards", + text: strings["earn ad-free time"], + icon: "play_arrow", + info: strings["settings-info-main-ad-rewards"], + category: categories.supportAcode, + chevron: true, + }); items.push({ key: "removeads", text: strings["remove ads"], - icon: "cancel", + icon: "block", + info: `${strings["settings-info-main-remove-ads"]}${!helpers.shouldAllowExternalPurchase() ? ` ${strings["iap-pro-purchase-warning"]}` : ""}`, + category: categories.supportAcode, + chevron: true, + }); + } + + // Add promotion items from cached data + const cachedPromotions = helpers.parseJSON( + localStorage.getItem("cached_promotions"), + ); + if (Array.isArray(cachedPromotions) && cachedPromotions.length) { + categories.promotions = strings["settings-category-discover-apps"]; + cachedPromotions.forEach((promo) => { + if (!promo.url || !promo.label || !/^https?:\/\//.test(promo.url)) return; + items.push({ + key: `promo-${encodeURIComponent(promo.url)}`, + text: promo.label, + image: typeof promo.icon === "string" ? promo.icon : null, + info: typeof promo.link_text === "string" ? promo.link_text : "", + link: promo.url, + category: categories.promotions, + }); }); } @@ -125,6 +242,7 @@ export default function mainSettings() { case "editor-settings": case "preview-settings": case "terminal-settings": + case "lsp-settings": appSettings.uiSettings[key].show(); break; @@ -132,6 +250,9 @@ export default function mainSettings() { themeSetting(); break; + case "appIcon": + return appIconSetting(); + case "about": About(); break; @@ -144,10 +265,31 @@ export default function mainSettings() { rateBox(); break; + case "privacyChoices": + loader.create( + strings["privacy choices"] || "Privacy Choices", + strings["loading..."] || "Loading...", + ); + try { + await showPrivacyOptions(); + } catch (error) { + console.warn("Unable to open AdMob Privacy Choices:", error); + helpers.error( + "Unable to open Privacy Choices. Check your connection and try again.", + ); + } finally { + loader.destroy(); + } + break; + case "plugins": plugins(); break; + case "adRewards": + openAdRewardsPage(); + break; + case "formatter": formatterSettings(); break; @@ -171,8 +313,7 @@ export default function mainSettings() { case "removeads": try { - await removeAds(); - this.remove(); + if (await requestProPurchase()) this.remove(); } catch (error) { helpers.error(error); } @@ -187,16 +328,75 @@ export default function mainSettings() { } } - const page = settingsPage(title, items, callback); + const page = settingsPage(title, items, callback, undefined, { + preserveOrder: true, + pageClassName: "main-settings-page", + listClassName: "main-settings-list", + }); + const $appIcon = page + .getListElement() + .querySelector('[data-key="appIcon"] > .icon img'); + const updateAppIcon = () => { + $appIcon.src = getAppIconImage(); + }; + appSettings.on("update:appIcon", updateAppIcon); + page.onClose(() => appSettings.off("update:appIcon", updateAppIcon)); + if (!config.HAS_PRO) { + bindPrivacyChoices({ + page, + subscribe: subscribePrivacyState, + }); + } page.show(); appSettings.uiSettings["main-settings"] = page; - appSettings.uiSettings["app-settings"] = otherSettings(); - appSettings.uiSettings["file-settings"] = filesSettings(); - appSettings.uiSettings["backup-restore"] = backupRestore(); - appSettings.uiSettings["editor-settings"] = editorSettings(); - appSettings.uiSettings["scroll-settings"] = scrollSettings(); - appSettings.uiSettings["search-settings"] = searchSettings(); - appSettings.uiSettings["preview-settings"] = previewSettings(); - appSettings.uiSettings["terminal-settings"] = terminalSettings(); + + const lazyPages = { + "app-settings": otherSettings, + "file-settings": filesSettings, + "backup-restore": backupRestore, + "editor-settings": editorSettings, + "scroll-settings": scrollSettings, + "search-settings": searchSettings, + "preview-settings": previewSettings, + "terminal-settings": terminalSettings, + "lsp-settings": lspSettings, + }; + + const instantiated = {}; + + for (const [key, initializer] of Object.entries(lazyPages)) { + delete appSettings.uiSettings[key]; + Object.defineProperty(appSettings.uiSettings, key, { + get() { + if (!(key in instantiated)) { + instantiated[key] = initializer(); + Object.defineProperty(appSettings.uiSettings, key, { + value: instantiated[key], + writable: true, + configurable: true, + enumerable: true, + }); + } + return instantiated[key]; + }, + set(val) { + instantiated[key] = val; + Object.defineProperty(appSettings.uiSettings, key, { + value: val, + writable: true, + configurable: true, + enumerable: true, + }); + }, + configurable: true, + enumerable: false, + }); + } +} + +function getAppIconImage() { + return ( + APP_ICONS.find(({ id }) => id === appSettings.value.appIcon) || APP_ICONS[0] + ).image; } diff --git a/src/settings/previewSettings.js b/src/settings/previewSettings.js index d9529f92e5..5fe49c7b1c 100644 --- a/src/settings/previewSettings.js +++ b/src/settings/previewSettings.js @@ -1,10 +1,13 @@ -import Checkbox from "components/checkbox"; import settingsPage from "components/settingsPage"; import appSettings from "lib/settings"; export default function previewSettings() { const values = appSettings.value; const title = strings["preview settings"]; + const categories = { + server: strings["settings-category-server"], + preview: strings["settings-category-preview"], + }; const PORT_REGEX = /^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/; const items = [ @@ -19,6 +22,8 @@ export default function previewSettings() { return PORT_REGEX.test(value); }, }, + info: strings["settings-info-preview-preview-port"], + category: categories.server, }, { key: "serverPort", @@ -31,15 +36,26 @@ export default function previewSettings() { return PORT_REGEX.test(value); }, }, + info: strings["settings-info-preview-server-port"], + category: categories.server, }, { key: "previewMode", text: strings["preview mode"], value: values.previewMode, + valueText: (value) => { + const options = { + [appSettings.PREVIEW_MODE_BROWSER]: strings.browser, + [appSettings.PREVIEW_MODE_INAPP]: strings.inapp, + }; + return options[value] ?? (value != null ? value.capitalize() : value); + }, select: [ [appSettings.PREVIEW_MODE_BROWSER, strings.browser], [appSettings.PREVIEW_MODE_INAPP, strings.inapp], ], + info: strings["settings-info-preview-mode"], + category: categories.server, }, { key: "host", @@ -57,28 +73,42 @@ export default function previewSettings() { } }, }, + info: strings["settings-info-preview-host"], + category: categories.server, }, { key: "disableCache", text: strings["disable in-app-browser caching"], checkbox: values.disableCache, + info: strings["settings-info-preview-disable-cache"], + category: categories.preview, }, { key: "useCurrentFileForPreview", text: strings["should_use_current_file_for_preview"], checkbox: !!values.useCurrentFileForPreview, + info: strings["settings-info-preview-use-current-file"], + category: categories.preview, }, { key: "showConsoleToggler", text: strings["show console toggler"], checkbox: values.showConsoleToggler, + info: strings["settings-info-preview-show-console-toggler"], + category: categories.preview, }, { note: strings["preview settings note"], }, ]; - return settingsPage(title, items, callback); + return settingsPage(title, items, callback, undefined, { + preserveOrder: true, + pageClassName: "detail-settings-page", + listClassName: "detail-settings-list", + infoAsDescription: true, + valueInTail: true, + }); function callback(key, value) { appSettings.update({ diff --git a/src/settings/scrollSettings.js b/src/settings/scrollSettings.js index 0e3e693355..cb5eb49f7f 100644 --- a/src/settings/scrollSettings.js +++ b/src/settings/scrollSettings.js @@ -1,5 +1,5 @@ import settingsPage from "components/settingsPage"; -import constants from "lib/constants"; +import config from "lib/config"; import appSettings from "lib/settings"; export default function scrollSettings() { @@ -13,22 +13,25 @@ export default function scrollSettings() { value: values.scrollSpeed, valueText: getScrollSpeedString, select: [ - [constants.SCROLL_SPEED_FAST_X2, `${strings.fast} x2`], - [constants.SCROLL_SPEED_FAST, strings.fast], - [constants.SCROLL_SPEED_NORMAL, strings.normal], - [constants.SCROLL_SPEED_SLOW, strings.slow], + [config.SCROLL_SPEED_FAST_X2, `${strings.fast} x2`], + [config.SCROLL_SPEED_FAST, strings.fast], + [config.SCROLL_SPEED_NORMAL, strings.normal], + [config.SCROLL_SPEED_SLOW, strings.slow], ], + info: strings["settings-info-scroll-speed"], + // Only canvas editors use it. + hidden: values.editorRenderer !== "canvas", }, - { + /*{ key: "reverseScrolling", text: strings["reverse scrolling"], checkbox: values.reverseScrolling, - }, - { + },*/ + /*{ key: "diagonalScrolling", text: strings["diagonal scrolling"], checkbox: values.diagonalScrolling, - }, + },*/ { key: "scrollbarSize", text: strings["scrollbar size"], @@ -37,30 +40,87 @@ export default function scrollSettings() { select: [5, 10, 15, 20], }, { - key: "textWrap", - text: strings["text wrap"], - checkbox: values.textWrap, + key: "scrollbarHeight", + text: strings["scrollbar height"] || "Scrollbar height", + value: values.scrollbarHeight, + valueText: (size) => `${size}px`, + select: [20, 30, 40, 50, 60], + }, + { + key: "scrollPastEnd", + text: strings["scroll past end"], + value: values.scrollPastEnd ?? "medium", + info: strings["settings-info-scroll-past-end"], + valueText: (val) => { + switch (val) { + case "none": + return strings.none; + case "small": + return strings.small; + case "medium": + return strings.medium; + default: + return strings.full; + } + }, + select: [ + ["none", strings.none], + ["small", strings.small], + ["medium", strings.medium], + ["full", strings.full], + ], + }, + { + key: "leftMargin", + text: strings["horizontal scroll margin"], + value: values.leftMargin ?? 50, + valueText: (size) => `${size}px`, + prompt: strings["horizontal scroll margin"], + promptType: "number", + promptOptions: { + required: true, + test(value) { + if (!/^\d+$/.test(String(value).trim())) return false; + const size = Number(value); + return Number.isSafeInteger(size) && size >= 0; + }, + }, + info: strings["settings-info-horizontal-scroll-margin"], }, ]; - return settingsPage(title, items, callback); + const page = settingsPage(title, items, callback, undefined, { + preserveOrder: true, + pageClassName: "detail-settings-page", + listClassName: "detail-settings-list", + infoAsDescription: true, + valueInTail: true, + groupByDefault: true, + }); + + // The page is created once and kept, so follow the renderer from here. + appSettings.on("update:editorRenderer", (renderer) => { + page.setItemVisibility("scrollSpeed", renderer === "canvas"); + }); + + return page; function callback(key, value) { appSettings.update({ - [key]: value, + [key]: key === "leftMargin" ? Number(value) : value, }); } } function getScrollSpeedString(speed) { switch (speed) { - case constants.SCROLL_SPEED_FAST: + case config.SCROLL_SPEED_FAST: return strings.fast; - case constants.SCROLL_SPEED_SLOW: + case config.SCROLL_SPEED_SLOW: return strings.slow; - case constants.SCROLL_SPEED_FAST_X2: + case config.SCROLL_SPEED_FAST_X2: return `${strings.fast} x2`; - case constants.SCROLL_SPEED_NORMAL: + case config.SCROLL_SPEED_NORMAL: return strings.normal; default: return strings.normal; diff --git a/src/settings/searchSettings.js b/src/settings/searchSettings.js index 485b9b9075..21ff656029 100644 --- a/src/settings/searchSettings.js +++ b/src/settings/searchSettings.js @@ -22,7 +22,12 @@ export default function searchSettings() { }, ]; - return settingsPage(title, items, callback); + return settingsPage(title, items, callback, undefined, { + preserveOrder: true, + pageClassName: "detail-settings-page", + listClassName: "detail-settings-list", + groupByDefault: true, + }); function callback(key, value) { values[key] = value; diff --git a/src/settings/terminalSettings.js b/src/settings/terminalSettings.js index ff1d7fac0c..408ed204cd 100644 --- a/src/settings/terminalSettings.js +++ b/src/settings/terminalSettings.js @@ -16,6 +16,13 @@ import helpers from "utils/helpers"; export default function terminalSettings() { const title = strings["terminal settings"]; const values = appSettings.value; + const categories = { + permissions: strings["settings-category-permissions"], + display: strings["settings-category-display"], + cursor: strings["settings-category-cursor"], + session: strings["settings-category-session"], + maintenance: strings["settings-category-maintenance"], + }; // Initialize terminal settings with defaults if not present if (!values.terminalSettings) { @@ -28,11 +35,16 @@ export default function terminalSettings() { const terminalValues = values.terminalSettings; + Executor.setProotDebug(terminalValues.prootDebug); + Executor.BackgroundExecutor.setProotDebug(terminalValues.prootDebug); + const items = [ { key: "all_file_access", - text: strings.allFileAccess?.capitalize(), - info: "Enable access of /sdcard and /storage in terminal", + text: strings["allFileAccess"], + info: strings["info-all_file_access"], + category: categories.permissions, + chevron: true, }, { key: "fontSize", @@ -46,7 +58,8 @@ export default function terminalSettings() { return value >= 8 && value <= 32; }, }, - info: "The font size used to render text.", + info: strings["info-fontSize"], + category: categories.display, }, { key: "fontFamily", @@ -55,45 +68,24 @@ export default function terminalSettings() { get select() { return fonts.getNames(); }, - info: "The font family used to render text.", - }, - { - key: "theme", - text: strings["theme"], - value: terminalValues.theme, - info: "The color theme of the terminal.", - get select() { - return TerminalThemeManager.getThemeNames().map((name) => [ - name, - name.charAt(0).toUpperCase() + name.slice(1), - ]); - }, - valueText(value) { - const option = this.select.find(([v]) => v === value); - return option ? option[1] : value; - }, - }, - { - key: "cursorStyle", - text: strings["terminal:cursor style"], - value: terminalValues.cursorStyle, - select: ["block", "underline", "bar"], - info: "The style of the cursor when the terminal is focused.", - }, - { - key: "cursorInactiveStyle", - text: strings["terminal:cursor inactive style"], - value: terminalValues.cursorInactiveStyle, - select: ["outline", "block", "bar", "underline", "none"], - info: "The style of the cursor when the terminal is not focused.", + info: strings["info-fontFamily"], + category: categories.display, }, { key: "fontWeight", text: strings["terminal:font weight"], value: terminalValues.fontWeight, + valueText: (value) => { + const tuple = [ + ["normal", strings["terminal:normal"]], + ["bold", strings["terminal:bold"]], + ].find((item) => item[0] === value); + + return tuple ? tuple[1] : value; + }, select: [ - "normal", - "bold", + ["normal", strings["terminal:normal"]], + ["bold", strings["terminal:bold"]], "100", "200", "300", @@ -104,13 +96,86 @@ export default function terminalSettings() { "800", "900", ], - info: "The font weight used to render non-bold text.", + info: strings["info-fontWeight"], + category: categories.display, + }, + + { + key: "letterSpacing", + text: strings["letter spacing"], + value: terminalValues.letterSpacing, + prompt: strings["letter spacing"], + promptType: "number", + info: strings["info-letterSpacing"], + category: categories.display, + }, + { + key: "fontLigatures", + text: strings["font ligatures"], + checkbox: terminalValues.fontLigatures, + info: strings["info-fontLigatures"], + category: categories.display, + }, + { + key: "showScrollbar", + text: strings["terminal:show scrollbar"] || "Show Scrollbar", + checkbox: terminalValues.showScrollbar !== false, + info: + strings["info-terminal-show-scrollbar"] || + "Show the xterm scrollbar beside the terminal.", + category: categories.display, + }, + { + key: "cursorStyle", + text: strings["terminal:cursor style"], + value: terminalValues.cursorStyle, + valueText: (value) => { + const option = [ + ["block", strings["terminal:block"]], + ["underline", strings["terminal:underline"]], + ["bar", strings["terminal:bar"]], + ].find((item) => item[0] === value); + return option ? option[1] : value; + }, + select: [ + ["block", strings["terminal:block"]], + ["underline", strings["terminal:underline"]], + ["bar", strings["terminal:bar"]], + ], + info: strings["info-cursorStyle"], + category: categories.cursor, + }, + { + key: "cursorInactiveStyle", + text: strings["terminal:cursor inactive style"], + value: terminalValues.cursorInactiveStyle, + valueText: (value) => { + const options = [ + ["outline", strings["terminal:inactive outline"]], + ["block", strings["terminal:inactive block"]], + ["underline", strings["terminal:inactive underline"]], + ["bar", strings["terminal:inactive bar"]], + ["none", strings["terminal:inactive none"]], + ]; + const option = options.find((item) => item[0] === value); + return option ? option[1] : value; + }, + select: [ + ["outline", strings["terminal:inactive outline"]], + ["block", strings["terminal:inactive block"]], + ["underline", strings["terminal:inactive underline"]], + ["bar", strings["terminal:inactive bar"]], + ["none", strings["terminal:inactive none"]], + ], + info: strings["info-cursorInactiveStyle"], + category: categories.cursor, }, { key: "cursorBlink", text: strings["terminal:cursor blink"], checkbox: terminalValues.cursorBlink, - info: "Whether the cursor blinks.", + info: strings["info-cursorBlink"], + category: categories.cursor, }, { key: "scrollback", @@ -124,7 +189,8 @@ export default function terminalSettings() { return value >= 100 && value <= 10000; }, }, - info: "The amount of scrollback in the terminal. Scrollback is the amount of rows that are retained when lines are scrolled beyond the initial viewport.", + info: strings["info-scrollback"], + category: categories.session, }, { key: "tabStopWidth", @@ -138,51 +204,74 @@ export default function terminalSettings() { return value >= 1 && value <= 8; }, }, - info: "The size of tab stops in the terminal.", - }, - { - key: "letterSpacing", - text: strings["letter spacing"], - value: terminalValues.letterSpacing, - prompt: strings["letter spacing"], - promptType: "number", - info: "The spacing in whole pixels between characters.", + info: strings["info-tabStopWidth"], + category: categories.session, }, { key: "convertEol", text: strings["terminal:convert eol"], checkbox: terminalValues.convertEol, + info: strings["settings-info-terminal-convert-eol"], + category: categories.session, }, { key: "imageSupport", - text: `${strings["image"]} Support`, + text: strings["terminal:image support"], checkbox: terminalValues.imageSupport, - info: "Whether images are supported in the terminal.", + info: strings["info-imageSupport"], + category: categories.session, }, { - key: "fontLigatures", - text: strings["font ligatures"], - checkbox: terminalValues.fontLigatures, - info: "Whether font ligatures are enabled in the terminal.", + key: "confirmTabClose", + text: strings["terminal:confirm tab close"], + checkbox: terminalValues.confirmTabClose !== false, + info: strings["info-confirmTabClose"], + category: categories.session, + }, + { + key: "failsafeMode", + text: strings["terminal:failsafe"], + checkbox: terminalValues.failsafeMode, + info: strings["terminal:failsafe-info"], + category: categories.maintenance, + }, + { + key: "prootDebug", + text: "PRoot Debug", + checkbox: terminalValues.prootDebug, + info: "Enable verbose PRoot logging (PROOT_VERBOSE=2). Useful for debugging sandbox issues.", + category: categories.maintenance, }, { key: "backup", - text: strings.backup.capitalize(), - info: "Creates a backup of the terminal installation", + text: strings.backup, + info: strings["info-backup"], + category: categories.maintenance, + chevron: true, }, { key: "restore", - text: strings.restore.capitalize(), - info: "Restores a backup of the terminal installation", + text: strings.restore, + info: strings["info-restore"], + category: categories.maintenance, + chevron: true, }, { key: "uninstall", - text: strings.uninstall.capitalize(), - info: "Uninstalls the terminal installation", + text: strings.uninstall, + info: strings["info-uninstall"], + category: categories.maintenance, + chevron: true, }, ]; - return settingsPage(title, items, callback); + return settingsPage(title, items, callback, undefined, { + preserveOrder: true, + pageClassName: "detail-settings-page", + listClassName: "detail-settings-list", + infoAsDescription: true, + valueInTail: true, + }); /** * Callback for settings page when an item is clicked @@ -197,11 +286,11 @@ export default function terminalSettings() { if (boolStr === "true") { system.requestStorageManager(console.log, console.error); } else { - alert("This feature is not available."); + alert(strings["feature not available"]); } }, alert); } else { - alert("This feature is not available."); + alert(strings["feature not available"]); } return; @@ -216,17 +305,14 @@ export default function terminalSettings() { case "uninstall": const confirmation = await confirm( strings.confirm, - "Are you sure you want to uninstall the terminal?", + strings["settings-info-terminal-uninstall"], ); if (confirmation) { loader.showTitleLoader(); Terminal.uninstall() .then(() => { loader.removeTitleLoader(); - alert( - strings.success.toUpperCase(), - "Terminal uninstalled successfully.", - ); + alert(strings.success, `${strings["uninstalled successfully"]}.`); }) .catch((error) => { loader.removeTitleLoader(); @@ -236,6 +322,17 @@ export default function terminalSettings() { } return; + case "prootDebug": + appSettings.update({ + terminalSettings: { + ...values.terminalSettings, + [key]: value, + }, + }); + Executor.setProotDebug(value); + Executor.BackgroundExecutor.setProotDebug(value); + break; + default: appSettings.update({ terminalSettings: { @@ -270,7 +367,7 @@ export default function terminalSettings() { console.error, ); loader.removeTitleLoader(); - alert(strings.success.toUpperCase(), `${strings["backup successful"]}.`); + alert(strings.success, `${strings["backup successful"]}.`); } catch (error) { loader.removeTitleLoader(); console.error("Terminal backup failed:", error); @@ -283,14 +380,16 @@ export default function terminalSettings() { */ async function terminalRestore() { try { + await Executor.execute("rm -rf $PREFIX/aterm_backup.*"); + sdcard.openDocumentFile( async (data) => { loader.showTitleLoader(); - //this will create a file at $PREFIX/atem_backup.bin + //this will create a file at $PREFIX/atem_backup.tar.tar await system.copyToUri( data.uri, cordova.file.dataDirectory, - "aterm_backup", + "aterm_backup.tar", console.log, console.error, ); @@ -298,16 +397,11 @@ export default function terminalSettings() { // Restore await Terminal.restore(); - // Clean up - const backupFilename = "aterm_backup.bin"; - const tempBackupPath = cordova.file.dataDirectory + backupFilename; - const tempFS = fsOperation(tempBackupPath); - await tempFS.delete(); + //Cleanup restore file + await Executor.execute("rm -rf $PREFIX/aterm_backup.*"); + loader.removeTitleLoader(); - alert( - strings.success.toUpperCase(), - "Terminal restored successfully", - ); + alert(strings.success, `${strings["restored successfully"]}.`); }, toast, "application/x-tar", @@ -325,7 +419,7 @@ export default function terminalSettings() { * @param {string} key * @param {any} value */ -async function updateActiveTerminals(key, value) { +export async function updateActiveTerminals(key, value) { // Find all terminal tabs and update their settings const terminalTabs = editorManager.files.filter( (file) => file.type === "terminal", @@ -342,6 +436,7 @@ async function updateActiveTerminals(key, value) { case "fontFamily": // Load font if it's not already loaded try { + fonts.injectFontFace(value); await fonts.loadFont(value); } catch (error) { console.warn(`Failed to load font ${value}:`, error); @@ -367,6 +462,9 @@ async function updateActiveTerminals(key, value) { case "scrollback": tab.terminalComponent.terminal.options.scrollback = value; break; + case "showScrollbar": + tab.terminalComponent.updateScrollbarVisibility(value); + break; case "tabStopWidth": tab.terminalComponent.terminal.options.tabStopWidth = value; break; @@ -379,11 +477,7 @@ async function updateActiveTerminals(key, value) { case "theme": tab.terminalComponent.terminal.options.theme = TerminalThemeManager.getTheme(value); - // Update container background to match new theme - if (tab.terminalComponent.container) { - tab.terminalComponent.container.style.background = - tab.terminalComponent.terminal.options.theme.background; - } + tab.terminalComponent.updateBackgroundColor(); break; case "imageSupport": tab.terminalComponent.updateImageSupport(value); diff --git a/src/sidebarApps/extensions/index.js b/src/sidebarApps/extensions/index.js index 9ba78b8cda..72ed4378e7 100644 --- a/src/sidebarApps/extensions/index.js +++ b/src/sidebarApps/extensions/index.js @@ -1,17 +1,17 @@ import "./style.scss"; - import fsOperation from "fileSystem"; -import ajax from "@deadlyjack/ajax"; import collapsableList from "components/collapsableList"; import Sidebar from "components/sidebar"; import alert from "dialogs/alert"; import prompt from "dialogs/prompt"; import select from "dialogs/select"; import purchaseListener from "handlers/purchase"; -import constants from "lib/constants"; +import auth from "lib/auth"; +import config from "lib/config"; import InstallState from "lib/installState"; import loadPlugin from "lib/loadPlugin"; import settings from "lib/settings"; +import { interstitialAd } from "lib/startAd"; import FileBrowser from "pages/fileBrowser"; import plugin from "pages/plugin"; import helpers from "utils/helpers"; @@ -27,14 +27,19 @@ let container = null; let $searchResult = null; const LIMIT = 50; +const SEARCH_INPUT_WAIT_TIMEOUT = 1000; let currentPage = 1; let hasMore = true; let isLoading = false; let currentFilter = null; -let filterCurrentPage = 1; let filterHasMore = true; let isFilterLoading = false; +function withSupportedEditor(url) { + const separator = url.includes("?") ? "&" : "?"; + return `${url}${separator}supported_editor=${config.SUPPORTED_EDITOR}`; +} + const $header = (
@@ -43,7 +48,11 @@ const $header = ( -
@@ -141,7 +150,9 @@ async function loadMorePlugins() { startLoading($explore); const response = await fetch( - `${constants.API_BASE}/plugins?page=${currentPage}&limit=${LIMIT}`, + withSupportedEditor( + `${config.API_BASE}/plugins?page=${currentPage}&limit=${LIMIT}`, + ), ); const newPlugins = await response.json(); @@ -163,28 +174,35 @@ async function loadMorePlugins() { } } -async function loadFilteredPlugins(filterName, isInitial = false) { - if (isFilterLoading || !filterHasMore) return; +async function loadFilteredPlugins(filterState, isInitial = false) { + if (isFilterLoading || !filterHasMore || !filterState) return; try { isFilterLoading = true; - const plugins = await getFilteredPlugins(filterName, filterCurrentPage); + const { items, hasMore } = await getFilteredPlugins(filterState); - if (plugins.length < LIMIT) { - filterHasMore = false; + if (currentFilter !== filterState) { + return; } installedPlugins = await listInstalledPlugins(); - const pluginElements = plugins.map(ListItem); - - if (isInitial) { - $searchResult.append(...pluginElements); - } else { + const pluginElements = items.map(ListItem); + if (pluginElements.length) { $searchResult.append(...pluginElements); + } else if (isInitial) { + $searchResult.append( + + {strings["no plugins found"] || strings.empty || "No plugins found"} + , + ); + } + + filterHasMore = hasMore; + if (!filterHasMore) { + $searchResult.onscroll = null; } - filterCurrentPage++; updateHeight($searchResult); } catch (error) { window.log("error", "Error loading filtered plugins:"); @@ -197,66 +215,175 @@ async function loadFilteredPlugins(filterName, isInitial = false) { async function searchPlugin() { clearTimeout(searchTimeout); searchTimeout = setTimeout(async () => { - // Clear filter when searching - currentFilter = null; - filterCurrentPage = 1; - filterHasMore = true; - isFilterLoading = false; - $searchResult.onscroll = null; + await runSearch(this.value); + }, 500); +} - $searchResult.content = ""; - const status = helpers.checkAPIStatus(); - if (!status) { - $searchResult.content = ( - {strings.api_error} - ); - return; - } +async function runSearch(query) { + // Clear filter when searching + currentFilter = null; + filterHasMore = true; + isFilterLoading = false; + $searchResult.onscroll = null; - const query = this.value; - if (!query) return; + $searchResult.content = ""; + const status = await helpers.checkAPIStatus(); + if (!status) { + $searchResult.content = {strings.api_error}; + return; + } - try { - $searchResult.classList.add("loading"); - const plugins = await fsOperation( - Url.join(constants.API_BASE, `plugins?name=${query}`), - ).readFile("json"); + query = String(query || "").trim(); + if (!query) return; - installedPlugins = await listInstalledPlugins(); - $searchResult.content = plugins.map(ListItem); - updateHeight($searchResult); - } catch (error) { - window.log("error", error); - $searchResult.content = {strings.error}; - } finally { - $searchResult.classList.remove("loading"); - } - }, 500); + try { + $searchResult.classList.add("loading"); + const plugins = await fsOperation( + withSupportedEditor( + Url.join(config.API_BASE, `plugins?name=${encodeURIComponent(query)}`), + ), + ).readFile("json"); + + installedPlugins = await listInstalledPlugins(); + $searchResult.content = plugins.length ? ( + plugins.map(ListItem) + ) : ( + + {strings["no plugins found"] || strings.empty || "No plugins found"} + + ); + updateHeight($searchResult); + } catch (error) { + window.log("error", error); + $searchResult.content = {strings.error}; + } finally { + $searchResult.classList.remove("loading"); + } +} + +function getSearchInput() { + return container?.querySelector('input[name="search-ext"]'); +} + +function waitForSearchInput() { + const startTime = Date.now(); + + return new Promise((resolve) => { + const check = () => { + const searchInput = getSearchInput(); + if (searchInput || Date.now() - startTime >= SEARCH_INPUT_WAIT_TIMEOUT) { + resolve(searchInput); + return; + } + + requestAnimationFrame(check); + }; + + check(); + }); +} + +export async function openWithSearch(query) { + Sidebar.show(); + document + .querySelector('[data-action="sidebar-app"][data-id="extensions"]') + ?.click(); + + const searchInput = await waitForSearchInput(); + if (!searchInput) return; + + searchInput.value = query; + clearTimeout(searchTimeout); + void runSearch(query); } async function filterPlugins() { - const filterOptions = { - [strings.top_rated]: "top_rated", - [strings.newly_added]: "newest", - [strings.most_downloaded]: "downloads", + const verifiedLabel = strings["verified publisher"]; + const authorLabel = strings.author || strings.name; + const keywordsLabel = strings.keywords; + + const filterItems = [ + { value: "orderBy:top_rated", text: strings.top_rated }, + { value: "orderBy:newest", text: strings.newly_added }, + { value: "orderBy:downloads", text: strings.most_downloaded }, + { value: "attribute:verified", text: verifiedLabel }, + { value: "attribute:author", text: authorLabel }, + { value: "attribute:keywords", text: keywordsLabel }, + ]; + + const filterConfig = { + "orderBy:top_rated": { + type: "orderBy", + value: "top_rated", + baseLabel: strings.top_rated, + }, + "orderBy:newest": { + type: "orderBy", + value: "newest", + baseLabel: strings.newly_added, + }, + "orderBy:downloads": { + type: "orderBy", + value: "downloads", + baseLabel: strings.most_downloaded, + }, + "attribute:verified": { + type: "verified", + baseLabel: verifiedLabel, + value: true, + }, + "attribute:author": { type: "author", baseLabel: authorLabel }, + "attribute:keywords": { type: "keywords", baseLabel: keywordsLabel }, }; - const filterName = await select("Filter", Object.keys(filterOptions)); - if (!filterName) return; + const selection = await select("Filter", filterItems); + if (!selection) return; - $searchResult.content = ""; - const filterParam = filterOptions[filterName]; - currentFilter = filterParam; - filterCurrentPage = 1; + const option = filterConfig[selection]; + if (!option) return; + + const filterState = { + ...option, + nextPage: 1, + buffer: [], + hasMoreSource: true, + displayLabel: option.baseLabel, + }; + + if (option.type === "author") { + const authorName = ( + await prompt(strings["enter author name"], "", "text") + )?.trim(); + if (!authorName) return; + filterState.value = authorName.toLowerCase(); + filterState.originalValue = authorName; + filterState.displayLabel = `${option.baseLabel}: ${authorName}`; + } else if (option.type === "keywords") { + const rawKeywords = ( + await prompt(strings["enter keywords"], "", "text") + )?.trim(); + if (!rawKeywords) return; + const keywordList = rawKeywords + .split(",") + .map((item) => item.trim()) + .filter(Boolean); + if (!keywordList.length) return; + filterState.value = keywordList.map((item) => item.toLowerCase()); + filterState.originalValue = keywordList.join(", "); + filterState.displayLabel = `${option.baseLabel}: ${filterState.originalValue}`; + } + + currentFilter = filterState; filterHasMore = true; isFilterLoading = false; + $searchResult.content = ""; try { $searchResult.classList.add("loading"); const filterMessage = (
- Filtered by {filterName} + {strings["filtered by"]} {filterState.displayLabel} {strings.api_error}; return; @@ -347,7 +475,9 @@ async function loadExplore() { hasMore = true; const response = await fetch( - `${constants.API_BASE}/plugins?page=${currentPage}&limit=${LIMIT}`, + withSupportedEditor( + `${config.API_BASE}/plugins?page=${currentPage}&limit=${LIMIT}`, + ), ); const plugins = await response.json(); @@ -360,6 +490,7 @@ async function loadExplore() { currentPage++; updateHeight($explore); } catch (error) { + console.error("Failed to load plugins in sidebar explore:", error); $explore.$ul.content = {strings.error}; } finally { stopLoading($explore); @@ -370,36 +501,186 @@ async function listInstalledPlugins() { const plugins = await Promise.all( (await fsOperation(PLUGIN_DIR).lsDir()).map(async (item) => { const id = Url.basename(item.url); - const url = Url.join(item.url, "plugin.json"); - const plugin = await fsOperation(url).readFile("json"); - const iconUrl = getLocalRes(id, plugin.icon); - plugin.icon = await helpers.toInternalUri(iconUrl); - plugin.installed = true; - return plugin; + + try { + const url = Url.join(item.url, "plugin.json"); + const plugin = await fsOperation(url).readFile("json"); + + if (plugin.icon) { + const iconUrl = getLocalRes(id, plugin.icon); + try { + plugin.icon = await helpers.toInternalUri(iconUrl); + } catch (error) { + console.warn( + `Failed to resolve plugin icon for "${id}" in sidebar.`, + error, + ); + } + } + + plugin.installed = true; + return plugin; + } catch (error) { + console.warn( + `Skipping unreadable installed plugin "${id}" in sidebar.`, + error, + ); + return null; + } }), ); - return plugins; + + return plugins.filter(Boolean); } -async function getFilteredPlugins(filterName, page = 1) { - try { - let response; - if (filterName === "top_rated") { - response = await fetch( - `${constants.API_BASE}/plugins?explore=random&page=${page}&limit=${LIMIT}`, +async function getFilteredPlugins(filterState) { + if (!filterState) return { items: [], hasMore: false }; + + if (filterState.type === "orderBy") { + const page = filterState.nextPage || 1; + try { + let response; + if (filterState.value === "top_rated") { + response = await fetch( + withSupportedEditor( + `${config.API_BASE}/plugins?explore=random&page=${page}&limit=${LIMIT}`, + ), + ); + } else { + response = await fetch( + withSupportedEditor( + `${config.API_BASE}/plugin?orderBy=${filterState.value}&page=${page}&limit=${LIMIT}`, + ), + ); + } + const items = await response.json(); + if (!Array.isArray(items)) { + return { items: [], hasMore: false }; + } + filterState.nextPage = page + 1; + const hasMore = items.length === LIMIT; + return { items, hasMore }; + } catch (error) { + console.error(`Failed to get Filtered Plugins: `, error); + return { items: [], hasMore: false }; + } + } + + if (!Array.isArray(filterState.buffer)) { + filterState.buffer = []; + } + if (filterState.hasMoreSource === undefined) { + filterState.hasMoreSource = true; + } + if (!filterState.nextPage) { + filterState.nextPage = 1; + } + + const items = []; + + while (items.length < LIMIT) { + if (filterState.buffer.length) { + items.push(filterState.buffer.shift()); + continue; + } + + if (filterState.hasMoreSource === false) break; + + try { + const page = filterState.nextPage; + const response = await fetch( + withSupportedEditor( + `${config.API_BASE}/plugins?page=${page}&limit=${LIMIT}`, + ), ); - } else { - response = await fetch( - `${constants.API_BASE}/plugin?orderBy=${filterName}&page=${page}&limit=${LIMIT}`, + const data = await response.json(); + filterState.nextPage = page + 1; + + if (!Array.isArray(data) || !data.length) { + filterState.hasMoreSource = false; + break; + } + + if (data.length < LIMIT) { + filterState.hasMoreSource = false; + } + + const matched = data.filter((plugin) => + doesPluginMatchFilter(plugin, filterState), + ); + filterState.buffer.push(...matched); + } catch (error) { + window.log("error", "Failed to fetch filtered plugins:"); + window.log("error", error); + filterState.hasMoreSource = false; + break; + } + } + + while (items.length < LIMIT && filterState.buffer.length) { + items.push(filterState.buffer.shift()); + } + + const hasMore = + (filterState.hasMoreSource !== false && filterState.nextPage) || + filterState.buffer.length > 0; + + return { items, hasMore: Boolean(hasMore) }; +} + +function doesPluginMatchFilter(plugin, filterState) { + if (!plugin) return false; + + switch (filterState.type) { + case "verified": + return Boolean(plugin.author_verified); + case "author": { + const authorName = getPluginAuthorName(plugin); + if (!authorName) return false; + return authorName.toLowerCase().includes(filterState.value); + } + case "keywords": { + const pluginKeywords = getPluginKeywords(plugin) + .map((keyword) => keyword.toLowerCase()) + .filter(Boolean); + if (!pluginKeywords.length) return false; + return filterState.value.some((keyword) => + pluginKeywords.some((pluginKeyword) => pluginKeyword.includes(keyword)), ); } - return await response.json(); - } catch (error) { - window.log("error", error); - return []; + default: + return true; } } +function getPluginAuthorName(plugin) { + const { author } = plugin || {}; + if (!author) return ""; + if (typeof author === "string") return author; + if (typeof author === "object") { + return author.name || author.username || author.github || ""; + } + return ""; +} + +function getPluginKeywords(plugin) { + const { keywords } = plugin || {}; + if (!keywords) return []; + if (Array.isArray(keywords)) return keywords; + if (typeof keywords === "string") { + try { + const parsed = JSON.parse(keywords); + if (Array.isArray(parsed)) return parsed; + } catch (error) { + return keywords + .split(",") + .map((item) => item.trim()) + .filter(Boolean); + } + } + return []; +} + function startLoading($list) { $list.$title.classList.add("loading"); } @@ -479,7 +760,16 @@ function getLocalRes(id, name) { return Url.join(PLUGIN_DIR, id, name); } -function ListItem({ icon, name, id, version, downloads, installed, source }) { +function ListItem({ + icon, + name, + id, + version, + downloads, + installed, + source, + price, +}) { if (installed === undefined) { installed = !!installedPlugins.find(({ id: _id }) => _id === id); } @@ -499,20 +789,24 @@ function ListItem({ icon, name, id, version, downloads, installed, source }) { > {name} - {installed - ? <> - {source - ? - : null} - - - : } + + ) + )}
); @@ -534,61 +828,22 @@ function ListItem({ icon, name, id, version, downloads, installed, source }) { try { let purchaseToken; let product; - const pluginUrl = Url.join(constants.API_BASE, `plugin/${id}`); + const pluginUrl = Url.join(config.API_BASE, `plugin/${id}`); const remotePlugin = await fsOperation(pluginUrl) .readFile("json") .catch(() => { throw new Error("Failed to fetch plugin details"); }); - const isPaid = remotePlugin.price > 0; - if (isPaid) { - [product] = await helpers.promisify(iap.getProducts, [ - remotePlugin.sku, - ]); - if (product) { - const purchase = await getPurchase(product.productId); - purchaseToken = purchase?.purchaseToken; - } - } - - if (isPaid && !purchaseToken) { - if (!product) throw new Error("Product not found"); - const apiStatus = await helpers.checkAPIStatus(); - - if (!apiStatus) { - alert(strings.error, strings.api_error); - return; - } - - iap.setPurchaseUpdatedListener( - ...purchaseListener(onpurchase, onerror), - ); - await helpers.promisify(iap.purchase, product.productId); - - async function onpurchase(e) { - const purchase = await getPurchase(product.productId); - await ajax.post(Url.join(constants.API_BASE, "plugin/order"), { - data: { - id: remotePlugin.id, - token: purchase?.purchaseToken, - package: BuildInfo.packageName, - }, - }); - purchaseToken = purchase?.purchaseToken; - } - - async function onerror(error) { - throw error; - } - } - const { default: installPlugin } = await import("lib/installPlugin"); - await installPlugin( - id, - remotePlugin.name, - purchaseToken ? purchaseToken : undefined, - ); + await Promise.all([ + loadAd(), + installPlugin( + id, + remotePlugin.name, + purchaseToken ? purchaseToken : undefined, + ), + ]); const searchInput = container.querySelector('input[name="search-ext"]'); if (searchInput) { @@ -596,7 +851,6 @@ function ListItem({ icon, name, id, version, downloads, installed, source }) { $searchResult.content = ""; // Reset filter state when clearing search results currentFilter = null; - filterCurrentPage = 1; filterHasMore = true; isFilterLoading = false; $searchResult.onscroll = null; @@ -611,6 +865,7 @@ function ListItem({ icon, name, id, version, downloads, installed, source }) { if (!$installed.collapsed) { $installed.ontoggle(); } + await helpers.showInterstitialIfReady(); async function getPurchase(sku) { const purchases = await helpers.promisify(iap.getPurchases); @@ -636,7 +891,7 @@ function ListItem({ icon, name, id, version, downloads, installed, source }) { } plugin( - { id, installed }, + { id }, () => { if (!$explore.collapsed) { $explore.ontoggle(); @@ -659,14 +914,11 @@ function ListItem({ icon, name, id, version, downloads, installed, source }) { return $el; } -async function loadAd(el) { - if (!IS_FREE_VERSION) return; +async function loadAd() { + if (!helpers.canShowAds()) return; try { - if (!(await window.iad?.isLoaded())) { - const oldText = el.textContent; - el.textContent = strings["loading..."]; - await window.iad.load(); - el.textContent = oldText; + if (!(await interstitialAd?.isLoaded())) { + await interstitialAd?.load(); } } catch (error) { console.error(error); @@ -678,10 +930,12 @@ async function uninstall(id) { const pluginDir = Url.join(PLUGIN_DIR, id); const state = await InstallState.new(id); await Promise.all([ - loadAd(this), + loadAd(), fsOperation(pluginDir).delete(), state.delete(state.storeUrl), ]); + const pluginMainScript = document.getElementById(`${id}-mainScript`); + if (pluginMainScript) document.head.removeChild(pluginMainScript); acode.unmountPlugin(id); const searchInput = container.querySelector('input[name="search-ext"]'); @@ -690,7 +944,6 @@ async function uninstall(id) { $searchResult.content = ""; // Reset filter state when clearing search results currentFilter = null; - filterCurrentPage = 1; filterHasMore = true; isFilterLoading = false; $searchResult.onscroll = null; @@ -701,9 +954,7 @@ async function uninstall(id) { } // Show Ad If Its Free Version, interstitial Ad(iad) is loaded. - if (IS_FREE_VERSION && (await window.iad?.isLoaded())) { - window.iad.show(); - } + await helpers.showInterstitialIfReady(); } catch (err) { helpers.error(err); } diff --git a/src/sidebarApps/extensions/style.scss b/src/sidebarApps/extensions/style.scss index 18d79cfde2..c123b8dc13 100644 --- a/src/sidebarApps/extensions/style.scss +++ b/src/sidebarApps/extensions/style.scss @@ -1,7 +1,33 @@ @use "../../styles/mixins.scss"; .container.extensions { + display: flex; + flex-direction: column; + overflow: hidden; + + .list.collapsible { + display: flex; + flex-direction: column; + overflow: hidden; + + &:not(.hidden) { + flex: 1; + min-height: 0; + } + + &.hidden { + flex-shrink: 0; + } + + >ul { + flex: 1; + min-height: 0; + overflow-y: auto; + } + } + .header { + flex-shrink: 0; padding: 10px; display: flex; flex-direction: column; @@ -67,7 +93,12 @@ } .list.search-result { - min-height: 0; + flex-shrink: 0; + overflow-y: auto; + + &:empty { + display: none + } &.loading { @include mixins.loader(20px); diff --git a/src/sidebarApps/files/dragMove.js b/src/sidebarApps/files/dragMove.js new file mode 100644 index 0000000000..69a5b207ee --- /dev/null +++ b/src/sidebarApps/files/dragMove.js @@ -0,0 +1,614 @@ +import "./dragMove.scss"; +import tag from "html-tag-js"; +import config from "lib/config"; +import appSettings from "lib/settings"; +import selection from "./selection"; + +// Movement allowed before a touch counts as a scroll instead of a press. +const TOUCH_SLOP = 8; +// After a long press a resting finger still wobbles, so a drag needs a +// clearly deliberate move. +const DRAG_SLOP = 14; +const MOUSE_SLOP = 5; +// Holding still this long after the long press opens the menu without +// waiting for the finger to lift. +const MENU_HOLD_MS = 300; +// Distance from a scroll edge where the list starts scrolling on its own. +const SCROLL_EDGE = 48; +const MAX_SCROLL_SPEED = 14; +// Hovering a closed folder this long opens it. +const SPRING_OPEN_MS = 650; +// Fraction of the remaining distance the preview covers each frame. +const FOLLOW = 0.35; +const SETTLE_MS = 240; + +/** @type {HTMLElement} */ +let container; +/** + * Press that may turn into a drag. + * @type {{$tile: HTMLElement, x: number, y: number, pointer: "touch"|"mouse", armed: boolean, menuOpened?: boolean, menuTimer?: number, $target?: Element, $touchTarget?: EventTarget} | null} + */ +let press = null; +/** @type {DragState|null} */ +let drag = null; +let suppressClick = false; +/** Context menu events re-dispatched after a long press ends without moving. */ +const replayed = new WeakSet(); +/** Touch events already handled, since they can reach two listeners. */ +const handled = new WeakSet(); + +/** + * @typedef {object} DragState + * @property {import("./selection").SelectedEntry[]} items + * @property {HTMLElement[]} $sources + * @property {HTMLElement} $ghost + * @property {DOMRect} origin + * @property {"touch"|"mouse"} pointer + * @property {number} x Pointer position + * @property {number} y + * @property {number} gx Preview position + * @property {number} gy + * @property {number} tilt + * @property {HTMLElement|null} $list Folder the entries would drop into + * @property {HTMLElement|null} $scroller + * @property {number} raf + * @property {number} springTimer + */ + +/** + * Let entries in the files sidebar be dragged onto folders. + * Must run before the selection handlers so a long press can become a drag. + * @param {HTMLElement} $container + */ +function init($container) { + container = $container; + container.addEventListener("touchstart", onTouchStart, { + capture: true, + passive: true, + }); + container.addEventListener("mousedown", onMouseDown, true); + container.addEventListener("contextmenu", onContextMenu, true); + container.addEventListener("click", onClick, true); +} + +/** + * @param {TouchEvent} e + */ +function onTouchStart(e) { + // A drag that lost its touch stream ends with the next touch. + if (drag) finishDrag(false); + endPress(); + if (e.touches.length !== 1) { + endPress(); + return; + } + + const $tile = selection.getEntry(e.target); + if (!$tile) return; + + const { clientX, clientY } = e.touches[0]; + press = { + $tile, + x: clientX, + y: clientY, + pointer: "touch", + armed: false, + $touchTarget: e.target, + }; + // Touch events keep going to the touched element even after it leaves the + // DOM (e.g. its folder collapses mid-drag), where they no longer reach the + // window, so listen on both. + for (const $el of [window, e.target]) { + $el.addEventListener("touchmove", onTouchMove, { + capture: true, + passive: false, + }); + $el.addEventListener("touchend", onTouchEnd, true); + $el.addEventListener("touchcancel", onTouchCancel, true); + } +} + +/** + * @param {TouchEvent} e + */ +function onTouchMove(e) { + if (isHandled(e)) return; + const touch = e.touches[0]; + if (!touch) return; + + if (drag) { + consume(e); + moveDrag(touch.clientX, touch.clientY); + return; + } + + if (!press) return; + + if (!press.armed) { + // Moving before the long press is a scroll. + if (distance(press, touch) > TOUCH_SLOP) endPress(); + return; + } + + // Held long enough: keep the list (and the sidebar) still. + consume(e); + if (press.menuOpened) return; + if (distance(press, touch) > DRAG_SLOP) { + clearTimeout(press.menuTimer); + startDrag(touch.clientX, touch.clientY); + } +} + +/** + * @param {TouchEvent} e + */ +function onTouchEnd(e) { + if (isHandled(e)) return; + if (drag) { + const touch = e.changedTouches[0]; + if (touch) moveDrag(touch.clientX, touch.clientY); + finishDrag(true); + endPress(); + return; + } + + // A long press released in place is a normal context menu request. + if (press?.armed && !press.menuOpened) replayContextMenu(press); + endPress(); +} + +function onTouchCancel(e) { + if (isHandled(e)) return; + if (drag) finishDrag(false); + endPress(); +} + +/** + * Hold the long-press context menu until it's clear whether this is a drag. + * @param {MouseEvent} e + */ +function onContextMenu(e) { + if (replayed.has(e)) return; + if (press?.pointer !== "touch" || press.armed) return; + if (selection.getEntry(e.target) !== press.$tile) return; + + consume(e); + press.armed = true; + press.$target = e.target; + press.$tile.classList.add("drag-armed"); + vibrate(); + + // Holding still means the menu was wanted, not a drag. + const current = press; + current.menuTimer = setTimeout(() => { + if (press !== current || drag) return; + current.menuOpened = true; + current.$tile.classList.remove("drag-armed"); + replayContextMenu(current); + }, MENU_HOLD_MS); +} + +/** + * @param {MouseEvent} e + */ +function onMouseDown(e) { + suppressClick = false; + if (drag || e.button !== 0) return; + + const $tile = selection.getEntry(e.target); + if (!$tile) return; + + press = { + $tile, + x: e.clientX, + y: e.clientY, + pointer: "mouse", + armed: true, + }; + window.addEventListener("mousemove", onMouseMove, true); + window.addEventListener("mouseup", onMouseUp, true); +} + +/** + * @param {MouseEvent} e + */ +function onMouseMove(e) { + if (drag) { + e.preventDefault(); + moveDrag(e.clientX, e.clientY); + return; + } + + if (press && distance(press, e) > MOUSE_SLOP) { + e.preventDefault(); + startDrag(e.clientX, e.clientY); + } +} + +function onMouseUp() { + if (drag) { + // The click that follows mouseup must not open or toggle the entry. + suppressClick = true; + finishDrag(true); + } + endPress(); +} + +/** + * @param {MouseEvent} e + */ +function onClick(e) { + if (!suppressClick) return; + suppressClick = false; + consume(e); +} + +/** + * @param {KeyboardEvent} e + */ +function onKeydown(e) { + if (e.key === "Escape" && drag) { + finishDrag(false); + endPress(); + } +} + +/** + * Any new touch during a drag means its own touch stream was lost. + */ +function onStrayTouch() { + if (drag) finishDrag(false); + endPress(); +} + +/** + * @param {number} x + * @param {number} y + */ +function startDrag(x, y) { + const { $tile, pointer } = press; + const { url, type, name } = $tile.dataset; + + // Dragging a selected entry carries the whole selection along. + const items = selection.isSelected(url) + ? selection.getItems() + : [{ url, type, name, $el: $tile }]; + const $sources = items.flatMap(({ url }) => findTiles(url)); + const origin = $tile.getBoundingClientRect(); + + $tile.classList.remove("drag-armed"); + for (const $el of $sources) $el.classList.add("drag-source"); + document.body.classList.add("file-dragging"); + document.addEventListener("keydown", onKeydown, true); + document.addEventListener("touchstart", onStrayTouch, true); + + drag = { + items, + $sources, + $ghost: createGhost($tile, items), + origin, + pointer, + x, + y, + gx: origin.left, + gy: origin.top, + tilt: 0, + $list: null, + $scroller: null, + raf: 0, + springTimer: 0, + }; + + vibrate(); + updateTarget(); + drag.raf = requestAnimationFrame(frame); +} + +/** + * @param {number} x + * @param {number} y + */ +function moveDrag(x, y) { + drag.x = x; + drag.y = y; + updateTarget(); +} + +/** + * Ease the preview toward the pointer, tilting slightly with its motion, + * and scroll the list when the pointer nears an edge. + */ +function frame() { + if (!drag) return; + + // Keep the preview clear of the finger; beside the cursor for mice. + const isTouch = drag.pointer === "touch"; + const targetX = drag.x + (isTouch ? 16 : 14); + const targetY = drag.y + (isTouch ? -52 : 10); + const dx = targetX - drag.gx; + + drag.gx += dx * FOLLOW; + drag.gy += (targetY - drag.gy) * FOLLOW; + drag.tilt += (clamp(dx * 0.12, -6, 6) - drag.tilt) * 0.2; + drag.$ghost.style.transform = `translate3d(${drag.gx}px, ${drag.gy}px, 0) rotate(${drag.tilt}deg)`; + + autoScroll(); + drag.raf = requestAnimationFrame(frame); +} + +function autoScroll() { + const $scroller = drag.$scroller; + if (!$scroller) return; + + const { top, bottom } = $scroller.getBoundingClientRect(); + let speed = 0; + if (drag.y < top + SCROLL_EDGE) { + speed = + -MAX_SCROLL_SPEED * + Math.min(1, (top + SCROLL_EDGE - drag.y) / SCROLL_EDGE); + } else if (drag.y > bottom - SCROLL_EDGE) { + speed = + MAX_SCROLL_SPEED * + Math.min(1, (drag.y - bottom + SCROLL_EDGE) / SCROLL_EDGE); + } + if (!speed) return; + + const before = $scroller.scrollTop; + $scroller.scrollTop += speed; + if ($scroller.scrollTop !== before) updateTarget(); +} + +/** + * Find the folder under the pointer and highlight it if it can take the drop. + */ +function updateTarget() { + const $el = document.elementFromPoint(drag.x, drag.y); + const $scroller = getScroller($el); + if ($scroller) drag.$scroller = $scroller; + + let $list = getDropList($el); + if ($list && !canDropInto($list)) $list = null; + if ($list === drag.$list) return; + + clearTarget(); + drag.$list = $list; + if (!$list) return; + + $list.classList.add("drop-target"); + + // Spring-loaded folders: hovering a closed one opens it. + if ( + $list.classList.contains("hidden") && + typeof $list.expand === "function" + ) { + $list.classList.add("drop-pending"); + drag.springTimer = setTimeout(() => { + $list.classList.remove("drop-pending"); + if (drag?.$list === $list) $list.expand(); + }, SPRING_OPEN_MS); + } +} + +function clearTarget() { + clearTimeout(drag.springTimer); + drag.$list?.classList.remove("drop-target", "drop-pending"); +} + +/** + * @param {boolean} drop Whether to move the entries into the hovered folder + */ +function finishDrag(drop) { + const state = drag; + drag = null; + cancelAnimationFrame(state.raf); + clearTimeout(state.springTimer); + state.$list?.classList.remove("drop-target", "drop-pending"); + document.body.classList.remove("file-dragging"); + document.removeEventListener("keydown", onKeydown, true); + document.removeEventListener("touchstart", onStrayTouch, true); + for (const $el of state.$sources) $el.classList.remove("drag-source"); + + const $ghost = state.$ghost; + const $title = drop ? state.$list?.firstElementChild : null; + const targetUrl = $title?.dataset.url; + $ghost.classList.add("settling"); + + if (targetUrl) { + // Shrink into the folder it was dropped on. + const rect = $title.getBoundingClientRect(); + const y = rect.top + rect.height / 2 - $ghost.offsetHeight / 2; + $ghost.style.transform = `translate3d(${rect.left + 12}px, ${y}px, 0) scale(0.3)`; + $title.classList.add("drop-flash"); + setTimeout(() => $title.classList.remove("drop-flash"), 600); + vibrate(); + selection.perform("move", state.items, targetUrl); + } else { + // Nowhere to drop: return to where it came from. + const { left, top } = state.origin; + $ghost.style.transform = `translate3d(${left}px, ${top}px, 0)`; + } + + setTimeout(() => $ghost.remove(), SETTLE_MS); +} + +function endPress() { + clearTimeout(press?.menuTimer); + press?.$tile.classList.remove("drag-armed"); + for (const $el of [window, press?.$touchTarget]) { + $el?.removeEventListener("touchmove", onTouchMove, true); + $el?.removeEventListener("touchend", onTouchEnd, true); + $el?.removeEventListener("touchcancel", onTouchCancel, true); + } + press = null; + window.removeEventListener("mousemove", onMouseMove, true); + window.removeEventListener("mouseup", onMouseUp, true); +} + +/** + * Open the context menu the long press would have opened. + * @param {{x: number, y: number, $target?: Element}} state + */ +function replayContextMenu({ x, y, $target }) { + if (!$target?.isConnected) return; + const event = new MouseEvent("contextmenu", { + bubbles: true, + cancelable: true, + clientX: x, + clientY: y, + }); + replayed.add(event); + $target.dispatchEvent(event); +} + +/** + * @param {HTMLElement} $tile + * @param {import("./selection").SelectedEntry[]} items + */ +function createGhost($tile, items) { + const $icon = tag("span", { + className: $tile.firstElementChild?.className || "", + }); + const $chip = tag("div", { + className: "chip", + children: [ + $icon, + tag("span", { className: "name", textContent: items[0].name }), + ], + }); + + if (items.length > 1) { + $chip.append( + tag("span", { className: "badge", textContent: String(items.length) }), + ); + } + + const $ghost = tag("div", { + className: `file-drag-ghost${items.length > 1 ? " multi" : ""}`, + children: [$chip], + }); + const { left, top } = $tile.getBoundingClientRect(); + $ghost.style.transform = `translate3d(${left}px, ${top}px, 0)`; + document.body.append($ghost); + return $ghost; +} + +/** + * @param {Element|null} $el + * @returns {HTMLElement|null} The folder list an entry would be dropped into + */ +function getDropList($el) { + if (!$el || !container.contains($el)) return null; + + const $tile = $el.closest(".tile[data-type]"); + const type = $tile?.dataset.type; + const $list = + type === "dir" || type === "root" + ? $tile.parentElement + : $el.closest(".list.collapsible"); + + if (!$list || !container.contains($list)) return null; + if ($list.classList.contains("file-list")) return null; + return $list; +} + +/** + * @param {HTMLElement} $list + */ +function canDropInto($list) { + const url = $list.firstElementChild?.dataset.url; + if (!url) return false; + + for (const $source of drag.$sources) { + if ($source.dataset.url === url) return false; + // A folder can't go inside itself. + if ( + $source.dataset.type === "dir" && + $source.parentElement.contains($list) + ) { + return false; + } + } + + // Nothing to do if every entry is already in this folder. + return !drag.items.every(({ $el }) => getParentUrl($el) === url); +} + +/** + * @param {HTMLElement} [$el] + * @returns {string|undefined} + */ +function getParentUrl($el) { + if (!$el?.isConnected) return undefined; + const $own = $el.dataset.type === "dir" ? $el.parentElement : $el; + return $own.parentElement?.closest(".list.collapsible")?.firstElementChild + ?.dataset.url; +} + +/** + * @param {Element|null} $el + * @returns {HTMLElement|null} + */ +function getScroller($el) { + while ($el && $el !== container.parentElement) { + if ($el.scrollHeight > $el.clientHeight + 1) { + const { overflowY } = getComputedStyle($el); + if (overflowY === "auto" || overflowY === "scroll") return $el; + } + $el = $el.parentElement; + } + return null; +} + +/** + * @param {string} url + * @returns {HTMLElement[]} + */ +function findTiles(url) { + return Array.from( + container.querySelectorAll(`.tile[data-url="${CSS.escape(url)}"]`), + ).filter(($el) => selection.getEntry($el)); +} + +/** + * @param {{x: number, y: number}} from + * @param {{clientX: number, clientY: number}} to + */ +function distance(from, to) { + return Math.hypot(to.clientX - from.x, to.clientY - from.y); +} + +/** + * @param {Event} e + * @returns {boolean} Whether another listener already handled the event + */ +function isHandled(e) { + if (handled.has(e)) return true; + handled.add(e); + return false; +} + +/** + * @param {number} value + * @param {number} min + * @param {number} max + */ +function clamp(value, min, max) { + return Math.min(max, Math.max(min, value)); +} + +/** + * @param {Event} e + */ +function consume(e) { + if (e.cancelable) e.preventDefault(); + e.stopPropagation(); + e.stopImmediatePropagation(); +} + +function vibrate() { + if (appSettings.value.vibrateOnTap) { + navigator.vibrate(config.VIBRATION_TIME); + } +} + +export default { init }; diff --git a/src/sidebarApps/files/dragMove.scss b/src/sidebarApps/files/dragMove.scss new file mode 100644 index 0000000000..52e961e898 --- /dev/null +++ b/src/sidebarApps/files/dragMove.scss @@ -0,0 +1,179 @@ +// Written without inset, flex gap or unguarded color-mix() so it still works +// on old Android WebViews. +$ease: cubic-bezier(0.2, 0, 0, 1); +$spring: cubic-bezier(0.34, 1.56, 0.64, 1); + +body.file-dragging { + cursor: grabbing; + user-select: none; + -webkit-user-select: none; +} + +#sidebar .container.files { + .tile[data-type="file"], + .tile[data-type="dir"] { + transition: + opacity 160ms ease, + transform 160ms $ease, + background-color 180ms ease; + + // Long press recognised: the row lifts slightly, ready to be dragged. + &.drag-armed { + transform: scale(0.97); + background-color: rgba(127, 127, 127, 0.14); + } + + &.drag-source { + opacity: 0.35; + } + } + + // The whole folder the entries would land in lights up. + .list.collapsible.drop-target { + border-radius: 8px; + background-color: rgba(127, 127, 127, 0.1); + background-color: color-mix(in srgb, var(--active-color) 10%, transparent); + box-shadow: inset 0 0 0 1px rgba(127, 127, 127, 0.35); + box-shadow: inset 0 0 0 1px + color-mix(in srgb, var(--active-color) 45%, transparent); + + > .tile:first-child { + border-radius: 8px; + } + } + + // Closed folder about to spring open. + .list.collapsible.drop-pending > .tile:first-child { + animation: file-drop-pending 650ms ease-in-out; + } + + .tile.drop-flash { + animation: file-drop-flash 600ms ease-out; + } +} + +.file-drag-ghost { + position: fixed; + top: 0; + left: 0; + z-index: 1000; + pointer-events: none; + will-change: transform; + + &.settling { + opacity: 0; + transition: + transform 240ms $ease, + opacity 240ms ease; + } + + .chip { + position: relative; + display: flex; + align-items: center; + box-sizing: border-box; + height: 34px; + max-width: 220px; + padding: 0 10px 0 6px; + border-radius: 10px; + border: 1px solid var(--popup-border-color, var(--border-color)); + background-color: var(--popup-background-color); + color: var(--popup-text-color); + font-size: 13px; + box-shadow: + 0 14px 30px -8px rgba(0, 0, 0, 0.45), + 0 2px 6px rgba(0, 0, 0, 0.2); + animation: file-drag-pick 260ms $spring; + + > :first-child { + flex: none; + width: 22px; + height: 22px; + min-width: 0; + margin-right: 6px; + font-size: 15px; + line-height: 22px; + text-align: center; + background-size: 16px; + background-position: center; + background-repeat: no-repeat; + } + } + + .name { + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + .badge { + flex: none; + min-width: 18px; + height: 18px; + box-sizing: border-box; + margin-left: 8px; + padding: 0 5px; + border-radius: 9px; + background-color: var(--active-color); + color: var(--active-text-color); + font-size: 11px; + font-weight: 600; + line-height: 18px; + text-align: center; + } + + // Several entries: cards stacked behind the chip. + &.multi .chip::before, + &.multi .chip::after { + content: ""; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + z-index: -1; + box-sizing: border-box; + border-radius: 10px; + border: 1px solid var(--popup-border-color, var(--border-color)); + background-color: var(--popup-background-color); + } + + &.multi .chip::before { + transform: translate(4px, 4px) rotate(2deg); + opacity: 0.7; + } + + &.multi .chip::after { + transform: translate(8px, 8px) rotate(4deg); + opacity: 0.4; + } +} + +@keyframes file-drag-pick { + from { + transform: scale(0.85); + opacity: 0; + } +} + +@keyframes file-drop-pending { + 50% { + background-color: rgba(127, 127, 127, 0.22); + } +} + +@keyframes file-drop-flash { + from { + background-color: rgba(127, 127, 127, 0.3); + background-color: color-mix(in srgb, var(--active-color) 35%, transparent); + } +} + +body.no-animation { + .file-drag-ghost, + .file-drag-ghost * { + animation: none !important; + transition: none !important; + } +} diff --git a/src/sidebarApps/files/index.js b/src/sidebarApps/files/index.js index 1c9e900ec8..f07e9a15ca 100644 --- a/src/sidebarApps/files/index.js +++ b/src/sidebarApps/files/index.js @@ -1,6 +1,9 @@ import "./style.scss"; import Sidebar from "components/sidebar"; +import fileIcons from "lib/fileIcons"; import settings from "lib/settings"; +import dragMove from "./dragMove"; +import selection from "./selection"; /**@type {HTMLElement} */ let container; @@ -24,6 +27,10 @@ function initApp(el) { container.setAttribute("data-msg", strings["open folder"]); container.style.overflowX = "auto"; container.addEventListener("click", clickHandler); + // Drag listens first so a long press can become a drag before selection + // or the context menu sees it. + dragMove.init(container); + selection.init(container); editorManager.on( ["new-file", "int-open-file-list", "remove-file"], (position) => { @@ -45,6 +52,15 @@ function initApp(el) { * @param {HTMLElement} el */ function onSelected(el) { + // Phone sidebars and inactive sidebar apps are detached, so document-wide + // icon updates cannot reach them until this view is shown again. + fileIcons.refreshRenderedIcons(container); + selection.syncBar(); + // Heights measured while the sidebar was detached come out wrong. + const $openFolder = container.querySelector( + ":scope > .list:not(.hidden):not(.file-list)", + ); + if ($openFolder) fixHeight($openFolder); const $scrollableLists = container.getAll(":scope .scroll[data-scroll-top]"); $scrollableLists.forEach(($el) => { $el.scrollTop = $el.dataset.scrollTop; @@ -75,8 +91,13 @@ function clickHandler(e) { export function fixHeight(target) { const lists = Array.from(container.getAll(":scope > div")); const ITEM_HEIGHT = 30; + // Headers are taller than rows (36px, 40px on wide screens); measure them so + // the expanded list doesn't overflow below the sidebar. + const headerHeight = + container.querySelector(":scope > .list > .tile")?.offsetHeight || + ITEM_HEIGHT; - let height = (lists.length - 1) * ITEM_HEIGHT; + let height = (lists.length - 1) * headerHeight; let activeFileList; if (settings.value.openFileListPos === settings.OPEN_FILE_LIST_POS_SIDEBAR) { @@ -84,9 +105,9 @@ export function fixHeight(target) { if (firstList.classList.contains("file-list")) { activeFileList = firstList; if (firstList.unclasped) { - const heightOffset = height - ITEM_HEIGHT; + const heightOffset = height - headerHeight; const totalHeight = - ITEM_HEIGHT * activeFileList.$ul.children.length + ITEM_HEIGHT; + ITEM_HEIGHT * activeFileList.$ul.children.length + headerHeight; const maxHeight = lists.length === 1 || !lists.slice(1).find((list) => list.unclasped) ? window.innerHeight @@ -95,7 +116,7 @@ export function fixHeight(target) { activeFileList.style.maxHeight = `${minHeight}px`; activeFileList.style.height = `${minHeight}px`; - height += minHeight - ITEM_HEIGHT; + height += minHeight - headerHeight; } } } diff --git a/src/sidebarApps/files/selection.js b/src/sidebarApps/files/selection.js new file mode 100644 index 0000000000..c6fd69fbbb --- /dev/null +++ b/src/sidebarApps/files/selection.js @@ -0,0 +1,528 @@ +import "./selection.scss"; +import select from "dialogs/select"; +import tag from "html-tag-js"; +import config from "lib/config"; +import appSettings from "lib/settings"; +import helpers from "utils/helpers"; + +/** + * @typedef {"copy"|"cut"|"delete"|"copy-path"|"rename"|"open"|"move"} SelectionAction + */ + +/** + * @typedef {object} SelectedEntry + * @property {string} url + * @property {"file"|"dir"} type + * @property {string} name + * @property {string} [rootUrl] Url of the open folder containing the entry + * @property {HTMLElement} [$el] + */ + +const ACTION_STACK_ID = "file-selection"; +const ENTRY_SELECTOR = + '.tile[data-url][data-type="file"], .tile[data-url][data-type="dir"]'; +// Bar widths below which the label and then the buttons are compacted. +const COMPACT_WIDTH = 270; +const TIGHT_WIDTH = 210; +// Range selections fill in as a short wave instead of all at once. +const WAVE_STEP_MS = 14; +const WAVE_MAX_MS = 180; + +/** @type {Map} */ +const selected = new Map(); +/** @type {HTMLElement} */ +let container; +/** @type {string|null} */ +let anchorUrl = null; +/** @type {(action: SelectionAction, items: SelectedEntry[], targetUrl?: string) => Promise} */ +let actionHandler; +/** @type {MutationObserver} */ +let observer; +/** @type {HTMLElement} */ +let $bar; +/** @type {HTMLElement} */ +let $count; +let busy = false; + +/** + * Attach selection handling to the files sidebar container. + * @param {HTMLElement} $container + */ +function init($container) { + container = $container; + // Capture phase runs before the tree's own tile listeners, so a tap can + // select instead of opening the file or toggling the folder. + container.addEventListener("click", onClick, true); + container.addEventListener("contextmenu", onContextMenu, true); + observer = new MutationObserver(onTreeMutation); + editorManager.on("remove-folder", onRemoveFolder); +} + +/** + * @param {(action: SelectionAction, items: SelectedEntry[], targetUrl?: string) => Promise} handler + * Return false from the handler to keep the selection open. + */ +function onAction(handler) { + actionHandler = handler; +} + +function isActive() { + return !!container?.classList.contains("selecting"); +} + +/** + * Enter selection mode, optionally selecting an entry. + * @param {HTMLElement} [$tile] + */ +function start($tile) { + if (!container) return; + + if (!isActive()) { + container.classList.add("selecting"); + observer.observe(container, { childList: true, subtree: true }); + document.addEventListener("keydown", onKeydown); + actionStack.push({ id: ACTION_STACK_ID, action: exit }); + syncBar(); + updateBarSize(); + vibrate(); + } + + if ($tile && getEntry($tile)) { + setSelected($tile, true); + anchorUrl = $tile.dataset.url; + } + + update(1); +} + +function exit() { + if (!isActive()) return; + + container.classList.remove("selecting"); + for (const $el of container.querySelectorAll(".tile.selected")) { + markEntry($el, false); + } + + selected.clear(); + anchorUrl = null; + observer.disconnect(); + document.removeEventListener("keydown", onKeydown); + actionStack.remove(ACTION_STACK_ID); +} + +/** + * Keep the bar right after the files container so the CSS sibling rule can + * show it only while the files app is the visible sidebar app. + */ +function syncBar() { + if (!container?.isConnected) return; + if (!$bar) createBar(); + if ($bar.previousElementSibling !== container) container.after($bar); +} + +/** + * @param {MouseEvent} e + */ +function onClick(e) { + const $tile = getEntry(e.target); + if (!$tile) return; + + const additive = e.ctrlKey || e.metaKey; + + if (!isActive()) { + if (!additive && !e.shiftKey) return; + consume(e); + start($tile); + return; + } + + // The folder icon keeps expanding folders so nested entries can be reached. + const isPlainTap = !additive && !e.shiftKey; + if (isPlainTap && helpers.isDir($tile.dataset.type) && isOnLead($tile, e)) { + return; + } + + consume(e); + if (e.shiftKey) selectRange($tile); + else toggle($tile); +} + +/** + * @param {PointerEvent} e + */ +function onContextMenu(e) { + if (!isActive()) return; + + const $tile = getEntry(e.target); + if (!$tile) return; + + consume(e); + + // Right click acts on the selection; long press extends it. + if (e.pointerType === "mouse") { + if (!selected.has($tile.dataset.url)) { + setSelected($tile, true); + anchorUrl = $tile.dataset.url; + update(1); + } + showMore(); + return; + } + + vibrate(); + if (anchorUrl && anchorUrl !== $tile.dataset.url) selectRange($tile); + else toggle($tile); +} + +/** + * @param {KeyboardEvent} e + */ +function onKeydown(e) { + if (e.key === "Escape") exit(); +} + +/** + * Re-apply selection to entries re-rendered by the tree (e.g. a folder + * collapsed and expanded again). + * @param {MutationRecord[]} records + */ +function onTreeMutation(records) { + for (const { addedNodes } of records) { + for (const node of addedNodes) { + if (!(node instanceof Element)) continue; + const $tiles = node.matches(ENTRY_SELECTOR) + ? [node] + : node.querySelectorAll(ENTRY_SELECTOR); + for (const $tile of $tiles) { + if (selected.has($tile.dataset.url)) markEntry($tile, true); + } + } + } +} + +/** + * Drop entries of an open folder that was closed. + * @param {{url: string}} folder + */ +function onRemoveFolder({ url } = {}) { + if (!isActive()) return; + for (const [key, entry] of selected) { + if (entry.rootUrl === url) selected.delete(key); + } + update(-1); +} + +/** + * @param {HTMLElement} $tile + */ +function toggle($tile) { + const { url } = $tile.dataset; + const value = !selected.has(url); + setSelected($tile, value); + anchorUrl = url; + update(value ? 1 : -1); +} + +/** + * Select every visible entry between the anchor and the given entry. + * @param {HTMLElement} $tile + */ +function selectRange($tile) { + const $tiles = getVisibleEntries(); + const to = $tiles.indexOf($tile); + const from = $tiles.findIndex(($el) => $el.dataset.url === anchorUrl); + + if (from === -1 || to === -1) { + toggle($tile); + return; + } + + const step = from < to ? 1 : -1; + const range = []; + for (let i = from; i !== to + step; i += step) range.push($tiles[i]); + selectWave(range); +} + +function selectAll() { + const roots = new Set( + Array.from(container.querySelectorAll(".tile.selected"), getRoot), + ); + const $tiles = getVisibleEntries().filter( + ($el) => !roots.size || roots.has(getRoot($el)), + ); + selectWave($tiles); +} + +/** + * Select entries in order with a slight stagger. + * @param {HTMLElement[]} $tiles + */ +function selectWave($tiles) { + let delay = 0; + for (const $tile of $tiles) { + if (selected.has($tile.dataset.url)) continue; + $tile.style.setProperty("--select-delay", `${delay}ms`); + setSelected($tile, true); + delay = Math.min(delay + WAVE_STEP_MS, WAVE_MAX_MS); + setTimeout(() => $tile.style.removeProperty("--select-delay"), 400); + } + update(1); +} + +/** + * @param {HTMLElement} $tile + * @param {boolean} value + */ +function setSelected($tile, value) { + const { url, type, name } = $tile.dataset; + const rootUrl = getRoot($tile).firstElementChild?.dataset.url; + if (value) selected.set(url, { url, type, name, rootUrl }); + else selected.delete(url); + + for (const $el of findEntries(url)) markEntry($el, value); +} + +/** + * @param {HTMLElement} $tile + * @param {boolean} value + */ +function markEntry($tile, value) { + $tile.classList.toggle("selected", value); + // Lets CSS tint a selected folder's contents without :has(). + if (helpers.isDir($tile.dataset.type)) { + $tile.parentElement?.classList.toggle("has-selected-title", value); + } +} + +/** + * Sync the bar with the selection, leaving selection mode once it's empty. + * @param {1|-1} direction Whether the count went up or down + */ +function update(direction) { + if (!selected.size) { + exit(); + return; + } + + if (!$bar) return; + const count = String(selected.size); + if ($count.textContent === count) return; + + $count.textContent = count; + $count.classList.remove("up", "down"); + void $count.offsetWidth; // restart the animation + $count.classList.add(direction > 0 ? "up" : "down"); +} + +/** + * @param {SelectionAction} action + */ +async function run(action) { + if (!selected.size) return; + await perform(action, getItems()); +} + +/** + * Run an action on the given entries, then leave selection mode. + * @param {SelectionAction} action + * @param {SelectedEntry[]} items + * @param {string} [targetUrl] + */ +async function perform(action, items, targetUrl) { + if (busy || !actionHandler || !items.length) return; + + busy = true; + $bar?.classList.add("busy"); + try { + const result = await actionHandler(action, items, targetUrl); + if (result !== false) exit(); + } catch (error) { + console.error(error); + helpers.error(error); + } finally { + busy = false; + $bar?.classList.remove("busy"); + } +} + +/** + * @returns {SelectedEntry[]} Selected entries with their rendered elements + */ +function getItems() { + return Array.from(selected.values(), (item) => ({ + ...item, + $el: findEntries(item.url)[0], + })); +} + +async function showMore() { + const items = Array.from(selected.values()); + const files = items.filter(({ type }) => helpers.isFile(type)).length; + const openText = strings.open || "Open"; + const options = [ + ["select-all", strings["select all"], "library_add_check"], + ["copy-path", strings["copy relative path"], "attach_file"], + ]; + + if (items.length === 1) { + options.push(["rename", strings.rename, "edit"]); + } + + if (files) { + const text = files > 1 ? `${openText} (${files})` : openText; + options.push(["open", text, "launchopen_in_new"]); + } + + const action = await select(getLabel(), options); + if (!isActive()) return; + if (action === "select-all") selectAll(); + else run(action); +} + +function createBar() { + $count = tag("span", { className: "count" }); + $bar = tag("div", { + className: "file-selection-bar", + children: [ + barButton("exit", "clearclose", strings.cancel), + tag("div", { + className: "label", + children: [ + $count, + tag("span", { + className: "unit", + textContent: strings.selected || "selected", + }), + ], + }), + barButton("copy", "copy", strings.copy), + barButton("cut", "cut", strings.cut), + barButton("delete", "delete danger", strings.delete), + barButton("more", "more_vert", strings.more || "More"), + ], + }); + + $bar.setAttribute("role", "toolbar"); + if (window.ResizeObserver) { + new ResizeObserver(updateBarSize).observe($bar); + } + $bar.addEventListener("click", (e) => { + const action = e.target.closest("[data-action]")?.dataset.action; + if (!action) return; + if (action === "exit") exit(); + else if (action === "more") showMore(); + else run(action); + }); +} + +/** + * Stand-in for container queries, which old WebViews don't support. + */ +function updateBarSize() { + if (!$bar) return; + const width = $bar.clientWidth; + if (!width) return; + $bar.classList.toggle("compact", width < COMPACT_WIDTH); + $bar.classList.toggle("tight", width < TIGHT_WIDTH); +} + +/** + * @param {string} action + * @param {string} icon + * @param {string} title + */ +function barButton(action, icon, title) { + const $button = tag("button", { type: "button", className: `icon ${icon}` }); + $button.dataset.action = action; + $button.title = title; + $button.setAttribute("aria-label", title); + return $button; +} + +function getLabel() { + return `${selected.size} ${strings.selected || "selected"}`; +} + +/** + * @param {EventTarget} target + * @returns {HTMLElement|null} The selectable tree entry for the target + */ +function getEntry(target) { + if (!(target instanceof Element)) return null; + const $tile = target.closest(ENTRY_SELECTOR); + if (!$tile || !container.contains($tile)) return null; + if ($tile.closest(".file-list")) return null; + return $tile; +} + +/** + * @param {string} url + * @returns {HTMLElement[]} + */ +function findEntries(url) { + return Array.from( + container.querySelectorAll(`.tile[data-url="${CSS.escape(url)}"]`), + ).filter(($el) => getEntry($el)); +} + +/** + * Entries in display order, skipping those inside collapsed folders. + * @returns {HTMLElement[]} + */ +function getVisibleEntries() { + return Array.from(container.querySelectorAll(ENTRY_SELECTOR)).filter( + ($el) => getEntry($el) && $el.getClientRects().length, + ); +} + +/** + * @param {HTMLElement} $el + * @returns {HTMLElement} The top level open folder containing the entry + */ +function getRoot($el) { + while ($el.parentElement && $el.parentElement !== container) { + $el = $el.parentElement; + } + return $el; +} + +/** + * @param {HTMLElement} $tile + * @param {MouseEvent} e + */ +function isOnLead($tile, e) { + const $lead = $tile.firstElementChild; + if (!$lead) return false; + const { left, right } = $lead.getBoundingClientRect(); + return e.clientX >= left && e.clientX <= right; +} + +/** + * @param {Event} e + */ +function consume(e) { + e.preventDefault(); + e.stopPropagation(); + e.stopImmediatePropagation(); +} + +function vibrate() { + if (appSettings.value.vibrateOnTap) { + navigator.vibrate(config.VIBRATION_TIME); + } +} + +export default { + init, + onAction, + start, + exit, + syncBar, + perform, + getItems, + getEntry, + isSelected: (url) => selected.has(url), + get active() { + return isActive(); + }, +}; diff --git a/src/sidebarApps/files/selection.scss b/src/sidebarApps/files/selection.scss new file mode 100644 index 0000000000..c8e0937a06 --- /dev/null +++ b/src/sidebarApps/files/selection.scss @@ -0,0 +1,273 @@ +// Avoids :is(), :has(), color-mix() without fallback, container queries and +// flex gap so the styles still work on old Android WebViews. +$ease: cubic-bezier(0.2, 0, 0, 1); +$spring: cubic-bezier(0.34, 1.56, 0.64, 1); +$delay: var(--select-delay, 0ms); + +@mixin entries { + > .list:not(.file-list) { + .tile[data-type="file"], + .tile[data-type="dir"] { + @content; + } + } +} + +#sidebar .container.files { + transition: padding-bottom 220ms $ease; + + &.selecting { + // Keeps the last entries reachable above the floating bar. + padding-bottom: 64px; + } + + @include entries { + transition: background-color 180ms ease $delay; + + &.selected { + background-color: rgba(127, 127, 127, 0.18); + background-color: color-mix(in srgb, var(--active-color) 18%, transparent); + } + } + + &.selecting { + user-select: none; + -webkit-user-select: none; + -webkit-touch-callout: none; + -webkit-tap-highlight-color: transparent; + + @include entries { + &:active { + background-color: rgba(127, 127, 127, 0.1); + } + + &.selected:active { + background-color: rgba(127, 127, 127, 0.26); + background-color: color-mix( + in srgb, + var(--active-color) 26%, + transparent + ); + } + } + + // Entries inside a selected folder are included implicitly. + .list.collapsible.has-selected-title > ul { + .tile[data-type="file"]:not(.selected), + .tile[data-type="dir"]:not(.selected) { + background-color: rgba(127, 127, 127, 0.08); + background-color: color-mix( + in srgb, + var(--active-color) 8%, + transparent + ); + } + } + } +} + +#sidebar .file-selection-bar { + position: absolute; + z-index: 111; + left: 60px; + right: 10px; + bottom: 12px; + bottom: calc(12px + env(safe-area-inset-bottom, 0px)); + height: 44px; + box-sizing: border-box; + display: flex; + align-items: center; + padding: 0 5px; + border-radius: 14px; + border: 1px solid var(--popup-border-color, var(--border-color)); + background-color: var(--popup-background-color); + color: var(--popup-text-color); + box-shadow: + 0 10px 28px -8px var(--box-shadow-color), + 0 2px 6px var(--box-shadow-color); + opacity: 0; + visibility: hidden; + pointer-events: none; + transform: translateY(16px) scale(0.96); + transform-origin: 50% 100%; + transition: + opacity 140ms ease, + transform 200ms $ease, + visibility 0s linear 200ms; + + .label { + flex: 1; + min-width: 0; + display: flex; + align-items: baseline; + padding: 0 4px; + overflow: hidden; + white-space: nowrap; + font-size: 0.9em; + } + + .count { + display: inline-block; + font-weight: 600; + font-variant-numeric: tabular-nums; + + &.up { + animation: file-selection-count-up 260ms $spring; + } + + &.down { + animation: file-selection-count-down 260ms $spring; + } + } + + .unit { + margin-left: 4px; + opacity: 0.6; + overflow: hidden; + text-overflow: ellipsis; + } + + button { + flex: none; + display: flex; + align-items: center; + justify-content: center; + width: 34px; + height: 34px; + padding: 0; + border: none; + border-radius: 10px; + background-color: transparent; + color: inherit; + font-size: 1.15em; + cursor: pointer; + margin-left: 2px; + transition: + transform 160ms $ease, + background-color 120ms ease, + color 120ms ease; + + &:active { + transform: scale(0.86); + background-color: rgba(127, 127, 127, 0.2); + } + + &:focus-visible { + outline: 2px solid var(--active-color); + outline-offset: -2px; + } + + &.danger:active { + color: var(--danger-color); + background-color: rgba(127, 127, 127, 0.2); + background-color: color-mix(in srgb, var(--danger-color) 16%, transparent); + } + } + + @media (hover: hover) { + button:hover { + background-color: rgba(127, 127, 127, 0.12); + } + + button.danger:hover { + color: var(--danger-color); + background-color: rgba(127, 127, 127, 0.12); + background-color: color-mix(in srgb, var(--danger-color) 12%, transparent); + } + } + + &.busy { + overflow: hidden; + pointer-events: none; + + &::after { + content: ""; + position: absolute; + left: 0; + bottom: 0; + width: 100%; + height: 2px; + background-color: var(--active-color); + animation: bar-loader-animation 1.5s cubic-bezier(0.4, 0, 0.2, 1) infinite; + } + + button { + opacity: 0.45; + } + } + + // Size classes are set from JS (container queries need newer WebViews). + // Too narrow for "3 selected": keep just the number. + &.compact .unit { + display: none; + } + + // Minimum sidebar width: tighten the buttons so they still fit. + &.tight button { + width: 28px; + } +} + +#sidebar .container.files.selecting + .file-selection-bar { + opacity: 1; + visibility: visible; + pointer-events: auto; + transform: none; + transition: + opacity 180ms ease, + transform 340ms $spring, + visibility 0s; + + // Bar contents settle in one after another. + > * { + animation: file-selection-item-in 300ms $spring backwards; + } + + @for $i from 2 through 6 { + > :nth-child(#{$i}) { + animation-delay: #{($i - 1) * 25}ms; + } + } +} + +@keyframes file-selection-item-in { + from { + opacity: 0; + transform: translateY(5px); + } +} + +@keyframes file-selection-count-up { + from { + opacity: 0; + transform: translateY(70%); + } +} + +@keyframes file-selection-count-down { + from { + opacity: 0; + transform: translateY(-70%); + } +} + +body.no-animation #sidebar { + .container.files, + .container.files *::before, + .container.files *::after, + .file-selection-bar, + .file-selection-bar * { + transition: none !important; + animation: none !important; + } +} + +@media (prefers-reduced-motion: reduce) { + #sidebar .container.files *::before, + #sidebar .container.files *::after, + #sidebar .file-selection-bar, + #sidebar .file-selection-bar * { + transition-duration: 1ms !important; + animation: none !important; + } +} diff --git a/src/sidebarApps/files/style.scss b/src/sidebarApps/files/style.scss index 906d1d6470..2c740d17aa 100644 --- a/src/sidebarApps/files/style.scss +++ b/src/sidebarApps/files/style.scss @@ -64,6 +64,13 @@ } } + > .list > .tile[data-type="root"] > .text { + min-width: 0; + width: auto !important; + overflow: hidden !important; + text-overflow: ellipsis !important; + } + /* Add indent guides for folders (excluding first level) */ .list.collapsible > ul > .collapsible > ul { position: relative; @@ -97,3 +104,77 @@ } } } + +// Open folder header actions: on hover with a mouse, a single menu button on +// touch, and nothing on collapsed folders. +$root-actions-ease: cubic-bezier(0.2, 0, 0, 1); + +#sidebar .container.files > .list > .tile[data-type="root"] .root-actions { + display: flex; + flex: none; + align-items: center; + margin: 0 4px 0 auto; + + .icon { + display: none; + width: 28px; + min-width: 28px; + height: 28px; + border-radius: 8px; + font-size: 1em; + line-height: 28px; + opacity: 0.55; + transition: + opacity 120ms ease, + transform 160ms $root-actions-ease, + background-color 120ms ease; + + &:active { + opacity: 1; + transform: scale(0.86); + background-color: rgba(127, 127, 127, 0.2); + } + + &.spinning { + animation: root-action-spin 700ms linear infinite; + } + } + + .icon.more-actions { + display: block; + } + + @media (hover: hover) and (pointer: fine) { + opacity: 0; + transition: opacity 120ms ease; + + .icon { + display: block; + + &:hover { + opacity: 1; + background-color: rgba(127, 127, 127, 0.14); + } + } + + .icon.more-actions { + display: none; + } + } +} + +@media (hover: hover) and (pointer: fine) { + #sidebar .container.files > .list > .tile[data-type="root"]:hover .root-actions { + opacity: 1; + } +} + +#sidebar .container.files > .list.hidden > .tile[data-type="root"] .root-actions { + display: none; +} + +@keyframes root-action-spin { + to { + transform: rotate(360deg); + } +} diff --git a/src/sidebarApps/index.js b/src/sidebarApps/index.js index 3cead9b7a2..91ded69c5a 100644 --- a/src/sidebarApps/index.js +++ b/src/sidebarApps/index.js @@ -1,3 +1,4 @@ +import appSettings from "lib/settings"; import Sponsors from "pages/sponsors"; import SidebarApp from "./sidebarApp"; @@ -11,13 +12,15 @@ let $sidebar; let currentSection = localStorage.getItem(SIDEBAR_APPS_LAST_SECTION); /**@type {SidebarApp[]} */ const apps = []; +/**@type {HTMLSpanElement | null} */ +let $sponsorIcon = null; /** * @param {string} icon icon of the app * @param {string} id id of the app * @param {HTMLElement} el element to show in sidebar * @param {string} title title of the app - * @param {(container:HTMLElement)=>void} initFunction + * @param {(container:HTMLElement)=>(void|Function)} initFunction * @param {boolean} prepend weather to show this app at the top of the sidebar or not * @param {(container:HTMLElement)=>void} onSelected * @returns {void} @@ -32,12 +35,13 @@ function add( ) { currentSection ??= id; - const active = currentSection === id; const app = new SidebarApp(icon, id, title, initFunction, onSelected); - - app.active = active; - app.install(prepend); apps.push(app); + app.install(prepend); + + if (currentSection === id) { + setActiveApp(id); + } } /** @@ -48,11 +52,18 @@ function add( function remove(id) { const app = apps.find((app) => app.id === id); if (!app) return; + const wasActive = app.active; app.remove(); apps.splice(apps.indexOf(app), 1); - if (app.active) { - const firstApp = apps[0]; - firstApp.active = true; + if (wasActive && apps.length > 0) { + const preferredApp = apps.find((app) => app.id === currentSection); + setActiveApp(preferredApp?.id || apps[0].id); + return; + } + + if (!apps.length) { + currentSection = null; + localStorage.removeItem(SIDEBAR_APPS_LAST_SECTION); } } @@ -65,6 +76,10 @@ function init($el) { $apps = $sidebar.get(".app-icons-container"); $apps.addEventListener("click", onclick); SidebarApp.init($el, $apps); + appSettings.on( + "update:showSponsorSidebarApp", + setSponsorSidebarAppVisibility, + ); } /** @@ -75,7 +90,58 @@ async function loadApps() { add(...(await import("./searchInFiles")).default); add(...(await import("./extensions")).default); add(...(await import("./notification")).default); - $apps.append(); + setSponsorSidebarAppVisibility(appSettings.value.showSponsorSidebarApp); +} + +/** + * Adds or removes the sponsor icon in sidebar based on settings. + * @param {boolean} visible + */ +function setSponsorSidebarAppVisibility(visible) { + if (!$apps) return; + + if (visible) { + if ($sponsorIcon?.isConnected) return; + $sponsorIcon = ( + + ); + // Keep it out of the app list so it isn't tapped by mistake (#2866) + $apps.after($sponsorIcon); + return; + } + + if ($sponsorIcon) { + $sponsorIcon.remove(); + $sponsorIcon = null; + } +} + +/** + * Ensures that at least one app is active. + * Call this AFTER all plugins have been loaded to handle cases where + * the stored section was from an uninstalled plugin. + * @returns {void} + */ +function ensureActiveApp() { + const activeApps = apps.filter((app) => app.active); + if (activeApps.length === 1) return; + + if (activeApps.length > 1) { + const preferredActiveApp = activeApps.find( + (app) => app.id === currentSection, + ); + setActiveApp(preferredActiveApp?.id || activeApps[0].id); + return; + } + + if (apps.length > 0) { + const preferredApp = apps.find((app) => app.id === currentSection); + setActiveApp(preferredApp?.id || apps[0].id); + } } /** @@ -98,11 +164,24 @@ function onclick(e) { if (action !== "sidebar-app") return; - localStorage.setItem(SIDEBAR_APPS_LAST_SECTION, id); - const activeApp = apps.find((app) => app.active); + setActiveApp(id); +} + +/** + * Activates the given sidebar app and deactivates all others. + * @param {string} id + * @returns {void} + */ +function setActiveApp(id) { const app = apps.find((app) => app.id === id); - activeApp.active = false; - app.active = true; + if (!app) return; + + currentSection = id; + localStorage.setItem(SIDEBAR_APPS_LAST_SECTION, id); + + for (const currentApp of apps) { + currentApp.active = currentApp.id === id; + } } export default { @@ -111,4 +190,5 @@ export default { get, remove, loadApps, + ensureActiveApp, }; diff --git a/src/sidebarApps/notification/index.js b/src/sidebarApps/notification/index.js index fb823d6136..0719604c79 100644 --- a/src/sidebarApps/notification/index.js +++ b/src/sidebarApps/notification/index.js @@ -1,14 +1,12 @@ -import NotificationManager from "lib/notificationManager"; import "./style.scss"; import Sidebar from "components/sidebar"; +import notificationManager from "lib/notificationManager"; /**@type {HTMLElement} */ let container; /** @type {HTMLElement} */ let $notificationContainer = null; -let notificationManager; - export default [ "notifications", // icon "notification", // id @@ -25,9 +23,11 @@ const $header = (
@@ -46,8 +46,6 @@ function initApp(el) { ); container.append($notificationContainer); - notificationManager = new NotificationManager(); - Sidebar.on("show", onSelected); } @@ -56,6 +54,8 @@ function initApp(el) { * @param {HTMLElement} el */ function onSelected(el) { + // Sidebar "show" fires for every app; only mark read when this one is open + if (container.isConnected) notificationManager.markAllRead(); const $scrollableLists = container.getAll(":scope .scroll[data-scroll-top]"); $scrollableLists.forEach(($el) => { $el.scrollTop = $el.dataset.scrollTop; diff --git a/src/sidebarApps/notification/style.scss b/src/sidebarApps/notification/style.scss index c46d996a8e..d66b71edaa 100644 --- a/src/sidebarApps/notification/style.scss +++ b/src/sidebarApps/notification/style.scss @@ -47,109 +47,41 @@ flex-direction: column; gap: 8px; + .notification-item { + padding-bottom: 5px; + margin-bottom: 10px; + border-radius: 0; + animation: slideIn 0.3s ease-out; + } + .empty-state { text-align: center; color: var(--secondary-text-color); padding: 20px; font-size: 14px; } + } +} - .notification-item { - padding: 10px 12px; - border-radius: 6px; - background: var(--popup-background-color); - display: flex; - gap: 10px; - align-items: flex-start; - animation: slideIn 0.3s ease-out; - border: 1px solid var(--popup-border-color); - transition: all 0.2s ease; - - &:hover { - background: rgba($color: #000000, $alpha: 0.2); - border-color: var(--popup-border-color); - } - - .notification-icon { - width: 20px; - height: 20px; - display: flex; - align-items: center; - justify-content: center; - flex-shrink: 0; - color: var(--primary-text-color); - } - - .notification-content { - flex: 1; - min-width: 0; - - .notification-title { - font-size: 13px; - font-weight: 500; - margin-bottom: 4px; - white-space: nowrap; - overflow: hidden; - word-wrap: break-word; - color: var(--primary-text-color); - display: flex; - justify-content: space-between; - align-items: center; - - .notification-time { - font-size: 11px; - color: var(--secondary-text-color); - } - } - - .notification-message { - font-size: 12px; - color: var(--secondary-text-color); - line-height: 1.4; - } - - .notification-actions { - margin-top: 8px; - display: flex; - justify-content: flex-end; - .action-button { - font-size: 11px; - padding: 6px 12px; - border-radius: 4px; - background: transparent; - color: var(--secondary-text-color); - cursor: pointer; - transition: all 0.2s ease; - border: 1px solid var(--border-color); - display: flex; - align-items: center; - gap: 4px; +@supports not (gap: 1px) { + .title>*+* { + margin-left: 4px; + } - &:hover { - background: rgba($color: var(--border-color), $alpha: 0.6); - color: var(--primary-text-color); - border-color: var(--border-color); - } + .notifications-container>*+* { + margin-top: 8px; + } - &:active { - transform: translateY(1px); - } + .notification-item>*+* { + margin-left: 10px; + } - &::before { - content: '×'; - font-size: 14px; - line-height: 1; - opacity: 0.8; - } - } - } - } - } + .action-button>*+* { + margin-left: 4px; } } - @keyframes slideIn { from { transform: translateX(100%); diff --git a/src/sidebarApps/searchInFiles/cmResultView.js b/src/sidebarApps/searchInFiles/cmResultView.js new file mode 100644 index 0000000000..4d755f3586 --- /dev/null +++ b/src/sidebarApps/searchInFiles/cmResultView.js @@ -0,0 +1,429 @@ +import { EditorState, StateEffect, StateField } from "@codemirror/state"; +import { + Decoration, + EditorView, + ViewPlugin, + WidgetType, +} from "@codemirror/view"; +import appSettings from "lib/settings"; +import helpers from "utils/helpers"; + +/** + * CodeMirror view to render search results + * + * @param {HTMLElement} container + * @param {object} opts + * @param {(lineIndex:number)=>void} opts.onLineClick + * @param {()=>string[]} opts.getWords - returns list of words to highlight + * @param {(lineIndex:number)=>object} opts.getFileInfo - file metadata for a result row + */ +export function createSearchResultView( + container, + { onLineClick, getWords, getFileInfo, getRegex }, +) { + let view; + let isGhostText = false; + + // Effect and field to maintain collapsed headers (by line number) + const toggleFold = StateEffect.define(); + const foldState = StateField.define({ + create() { + return new Set(); + }, + update(value, tr) { + let next = value; + for (const e of tr.effects) { + if (e.is(toggleFold)) { + if (next === value) next = new Set(value); + const ln = e.value; + if (next.has(ln)) next.delete(ln); + else next.add(ln); + } + } + // Reset folds on full document reset + if (tr.docChanged && tr.startState.doc.length === 0) return new Set(); + return next; + }, + }); + + function eachGroup(doc, fn) { + // Groups start at lines not beginning with a tab + const total = doc.lines; + let start = 1; + while (start <= total) { + const header = doc.line(start); + // If header starts with tab, advance until a non-tab header + if (header.text.startsWith("\t")) { + start++; + continue; + } + let end = start; + for (let i = start + 1; i <= total; i++) { + const line = doc.line(i); + if (!line.text.startsWith("\t")) break; + end = i; + } + fn({ start, end }); + start = end + 1; + } + } + + class ChevronWidget extends WidgetType { + constructor(collapsed) { + super(); + this.collapsed = collapsed; + } + eq(other) { + return other.collapsed === this.collapsed; + } + toDOM() { + const span = document.createElement("span"); + span.className = `cm-foldChevron icon keyboard_arrow_${this.collapsed ? "down" : "up"}`; + return span; + } + ignoreEvent() { + return false; + } + } + + class SummaryWidget extends WidgetType { + constructor(text) { + super(); + this.text = text; + } + eq(other) { + return other.text === this.text; + } + toDOM() { + const div = document.createElement("div"); + div.className = "cm-collapsedSummary"; + div.textContent = this.text; + return div; + } + ignoreEvent() { + return false; + } + } + + class CountWidget extends WidgetType { + constructor(count) { + super(); + this.count = count; + } + eq(other) { + return other.count === this.count; + } + toDOM() { + const span = document.createElement("span"); + span.className = "cm-fileCount"; + span.textContent = String(this.count); + return span; + } + ignoreEvent() { + return true; + } + } + + class FileIconWidget extends WidgetType { + constructor(className, name) { + super(); + this.className = className; + this.name = name; + } + eq(other) { + return other.className === this.className && other.name === this.name; + } + toDOM() { + const span = document.createElement("span"); + span.className = `${helpers.getIconForFile(this.name)} cm-fileIcon`; + span.dataset.fileIconName = this.name; + span.dataset.fileIconExtra = "cm-fileIcon"; + return span; + } + ignoreEvent() { + return false; + } + } + + function buildGroupDecos(state) { + const doc = state.doc; + const folded = state.field(foldState, false) || new Set(); + if (isGhostText || doc.length === 0 || doc.lines === 0) + return Decoration.none; + + const builder = []; + // Build header chevrons and collapses per group + eachGroup(doc, ({ start, end }) => { + const header = doc.line(start); + const key = start - 1; + const collapsed = folded.has(key); // zero-based line index + // Header line class and chevron widget + builder.push( + Decoration.line({ class: "cm-fileName" }).range(header.from), + ); + // File icon + const fileInfo = getFileInfo?.(key) || {}; + const fname = + typeof fileInfo === "string" ? fileInfo : fileInfo.name || ""; + const iconClass = helpers.getIconForFile(fname); + builder.push( + Decoration.widget({ + widget: new FileIconWidget(iconClass, fname), + side: -1, + }).range(header.from), + ); + // Count badge on right + const count = + typeof fileInfo === "object" && Number.isFinite(fileInfo.count) + ? fileInfo.count + : Math.max(0, end - start); + builder.push( + Decoration.widget({ widget: new CountWidget(count), side: 1 }).range( + header.to, + ), + ); + builder.push( + Decoration.widget({ + widget: new ChevronWidget(collapsed), + side: 1, + }).range(header.to), + ); + + if (collapsed && end > start) { + // Hide content lines and show a summary placeholder + const first = doc.line(start + 1); + const last = doc.line(end); + builder.push( + Decoration.replace({ block: true }).range(first.from, last.to), + ); + const count2 = count; + builder.push( + Decoration.widget({ + widget: new SummaryWidget( + `${count2} result${count2 > 1 ? "s" : ""}`, + ), + side: 1, + block: true, + }).range(first.from), + ); + } + }); + + return Decoration.set(builder, true); + } + + const groupDecoField = StateField.define({ + create(state) { + return buildGroupDecos(state); + }, + update(decos, tr) { + if ( + tr.docChanged || + tr.startState.field(foldState, false) !== + tr.state.field(foldState, false) + ) { + return buildGroupDecos(tr.state); + } + return decos.map(tr.changes); + }, + provide: (f) => EditorView.decorations.from(f), + }); + + const decorationsPlugin = ViewPlugin.fromClass( + class { + constructor(view) { + this.decorations = this.buildDecos(view); + } + + update(update) { + if ( + update.docChanged || + update.viewportChanged || + update.startState.field(foldState) !== update.state.field(foldState) + ) { + this.decorations = this.buildDecos(update.view); + } + } + + buildDecos(view) { + const builder = []; + if (isGhostText) return Decoration.none; + let searchRegex = null; + if (typeof getRegex === "function") { + const r = getRegex(); + if (r && r.source) { + const flags = (r.ignoreCase ? "i" : "") + "g"; + try { + searchRegex = new RegExp(r.source, flags); + } catch {} + } + } + const words = searchRegex ? [] : (getWords?.() || []).filter(Boolean); + + let wordRegex = null; + if (!searchRegex && words.length) { + const escaped = words + .map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) + .join("|"); + try { + wordRegex = new RegExp(escaped, "g"); + } catch {} + } + // Add match highlights only on visible lines to keep it fast + const matcher = searchRegex || wordRegex; + if (matcher) { + for (const { from, to } of view.visibleRanges) { + let pos = from; + while (pos <= to) { + const line = view.state.doc.lineAt(pos); + const text = line.text; + if (text && text.charCodeAt(0) === 9) { + const lineNumberMatch = text.match(/^\t\d+: /); + const searchStart = lineNumberMatch + ? lineNumberMatch[0].length + : 0; + if (lineNumberMatch) { + builder.push( + Decoration.mark({ + class: "cm-resultLineNumber", + }).range( + line.from + 1, + line.from + lineNumberMatch[0].length, + ), + ); + } + matcher.lastIndex = 0; + let m; + while ((m = matcher.exec(text))) { + if (m.index < searchStart) { + if (m.index === matcher.lastIndex) matcher.lastIndex++; + continue; + } + const fromPos = line.from + m.index; + const toPos = fromPos + m[0].length; + builder.push( + Decoration.mark({ class: "cm-match" }).range( + fromPos, + toPos, + ), + ); + if (m.index === matcher.lastIndex) matcher.lastIndex++; + } + } + if (line.to >= to) break; + pos = line.to + 1; + } + } + } + + return Decoration.set(builder, true); + } + }, + { + decorations: (v) => v.decorations, + eventHandlers: { + mousedown(event, view) { + if (isGhostText) return; + // Only react when clicking on a line element, not empty space + const lineEl = + event.target && event.target.closest + ? event.target.closest(".cm-line") + : null; + if (!lineEl) return; + const pos = view.posAtDOM(lineEl, 0); + const ln = view.state.doc.lineAt(pos).number - 1; // zero-based + const lineText = view.state.doc.line(ln + 1).text; + const clickedHeader = lineEl.classList.contains("cm-fileName"); + const isHeader = lineText.length > 0 && lineText.charCodeAt(0) !== 9; + if (clickedHeader || isHeader) { + // Toggle collapse on header click + view.dispatch({ effects: toggleFold.of(ln) }); + event.preventDefault(); + event.stopPropagation(); + return; + } + // Only trigger navigation for match lines (start with tab) + if (!(lineText && lineText.charCodeAt(0) === 9)) return; + onLineClick?.(ln); + }, + }, + }, + ); + + const readOnly = EditorState.readOnly.of(true); + const lineWrap = EditorView.lineWrapping; + const noCursor = EditorView.editable.of(false); + + function getEditorFontFamily() { + const font = appSettings?.value?.editorFont || "Roboto Mono"; + return `${font}, Noto Mono, Monaco, monospace`; + } + + const theme = EditorView.theme({ + "&": { + fontSize: String(appSettings?.value?.fontSize || "12px"), + lineHeight: String(appSettings?.value?.lineHeight || 1.5), + }, + ".cm-content": { + padding: 0, + fontFamily: getEditorFontFamily(), + }, + ".cm-line": { + color: "var(--primary-text-color)", + }, + }); + + const state = EditorState.create({ + doc: "", + extensions: [ + EditorState.tabSize.of(4), + readOnly, + noCursor, + lineWrap, + theme, + foldState, + groupDecoField, + decorationsPlugin, + ], + }); + + view = new EditorView({ state, parent: container }); + + return { + setValue(text) { + isGhostText = false; + view.dispatch({ + changes: { from: 0, to: view.state.doc.length, insert: text || "" }, + }); + }, + insert(text) { + if (!text) return; + view.dispatch({ changes: { from: view.state.doc.length, insert: text } }); + }, + setGhostText(text) { + isGhostText = true; + view.dispatch({ + changes: { from: 0, to: view.state.doc.length, insert: text || "" }, + }); + }, + removeGhostText() { + isGhostText = false; + this.setValue(""); + }, + getScrollPosition() { + return { + top: view.scrollDOM?.scrollTop ?? 0, + left: view.scrollDOM?.scrollLeft ?? 0, + }; + }, + setScrollPosition({ top = 0, left = 0 } = {}) { + const scroller = view.scrollDOM; + if (!scroller) return; + scroller.scrollTop = top; + scroller.scrollLeft = left; + }, + get view() { + return view; + }, + }; +} diff --git a/src/sidebarApps/searchInFiles/index.js b/src/sidebarApps/searchInFiles/index.js index 5fc6829119..35ef095b07 100644 --- a/src/sidebarApps/searchInFiles/index.js +++ b/src/sidebarApps/searchInFiles/index.js @@ -1,17 +1,25 @@ import "./styles.scss"; import fsOperation from "fileSystem"; -import addTouchListeners from "ace/touchHandler"; import autosize from "autosize"; +import { getDocText } from "cm/editorUtils"; import Checkbox from "components/checkbox"; import Sidebar, { preventSlide } from "components/sidebar"; import escapeStringRegexp from "escape-string-regexp"; import Reactive from "html-tag-js/reactive"; import Ref from "html-tag-js/ref"; -import files, { Tree } from "lib/fileList"; +import fileIndex from "lib/fileIndex"; +import files, { Tree, whenReady as waitForFileList } from "lib/fileList"; import openFile from "lib/openFile"; +import { addedFolder } from "lib/openFolder"; import settings from "lib/settings"; import helpers from "utils/helpers"; -import { fileNames, words } from "./searchResultMode"; +import { createSearchResultView } from "./cmResultView"; +import navigateToResult from "./navigateToResult"; + +// Local highlight sources +const words = []; +const fileNames = []; +const MAX_HL_WORDS = 400; // cap to avoid massive regex in result view const workers = []; const results = []; @@ -26,10 +34,18 @@ const $exclude = Ref(); const $include = Ref(); const $wholeWord = Ref(); const $caseSensitive = Ref(); +const $useIndex = Ref(); const $btnReplaceAll = Ref(); const $resultOverview = Ref(); +const $resultHeader = Ref(); const $error = Reactive(); const $progress = Reactive(); +const $indexStatus = Reactive(""); + +const FILE_LIST_WAIT_TIMEOUT = 250; +const FILE_LIST_MAX_WAIT = 5000; +let pendingDiscoveryVersion = null; +const SEARCH_WORKER_COUNT = 1; const resultOverview = { filesCount: 0, @@ -47,6 +63,7 @@ const WHOLE_WORD = "search-in-files-whole-word"; const REG_EXP = "search-in-files-reg-exp"; const EXCLUDE = "search-in-files-exclude"; const INCLUDE = "search-in-files-include"; +const USE_INDEX = "search-in-files-use-native-index"; const store = { get caseSensitive() { @@ -79,20 +96,43 @@ const store = { set include(value) { return localStorage.setItem(INCLUDE, value); }, + get useIndex() { + return localStorage.getItem(USE_INDEX) === "true"; + }, + set useIndex(value) { + localStorage.setItem(USE_INDEX, value); + }, }; const debounceSearch = helpers.debounce(searchAll, 500); -let useIncludeAndExclude = false; -/**@type {AceAjax.Editor} */ -let searchResult = null; +let showReplace = false; +let showExtras = !!(store.exclude || store.include); +let useIncludeAndExclude = showExtras; +const $headerEl = Ref(); +let searchResult = null; // CM6 wrapper from createSearchResultView +let currentSearchRegex = null; +let resultScrollTop = 0; +let resultScrollLeft = 0; +let resultScrollRestoreFrame = 0; let replacing = false; let newFiles = 0; let searching = false; +let searchVersion = 0; +let pendingResultText = ""; +let pendingResultFlush = 0; +let nativeResultQueue = []; +let nativeResultCursor = 0; +let nativeResultFrame = 0; +let pendingNativeSearchFinishVersion = null; +let nativeSearchId = null; +let activeSearchTasks = 0; +let activeReplaceTasks = 0; addEventListener($regExp, "change", onInput); addEventListener($wholeWord, "change", onInput); addEventListener($caseSensitive, "change", onInput); +addEventListener($useIndex, "change", onInput); addEventListener($search, "input", onInput); addEventListener($include, "input", onInput); addEventListener($exclude, "input", onInput); @@ -104,88 +144,137 @@ files.on("push-file", () => { }); $container.onref = ($el) => { - searchResult = ace.edit($el, { - readOnly: true, - useWorker: false, - showLineNumbers: false, - fontSize: "14px", - mode: "ace/mode/search_result", + searchResult = createSearchResultView($el, { + onLineClick: onCursorChange, + getWords: () => words, + getFileInfo: (line) => fileNames[results[line]?.file], + getRegex: () => currentSearchRegex, }); - searchResult.focus = () => {}; + searchResult.view.scrollDOM?.addEventListener( + "scroll", + rememberResultScroll, + { + passive: true, + }, + ); + restoreResultScroll(); $container.style.lineHeight = "1.5"; - searchResult.session.setTabSize(1); - searchResult.renderer.setMargin(0, 0, -20, 0); - addTouchListeners(searchResult, true, onCursorChange); - searchResult.session.setUseWrapMode(true); }; preventSlide((target) => { return $container.el?.contains(target); }); +function toggleReplace() { + showReplace = !showReplace; + $headerEl.el.classList.toggle("show-replace", showReplace); + const $btn = $headerEl.el.querySelector(".actions button:first-child"); + if ($btn) $btn.classList.toggle("active", showReplace); +} + +function toggleExtras() { + showExtras = !showExtras; + $headerEl.el.classList.toggle("show-extras", showExtras); + const $btn = $headerEl.el.querySelector(".actions button:last-child"); + if ($btn) $btn.classList.toggle("active", showExtras); + useIncludeAndExclude = showExtras; + if ($exclude.el?.value || $include.el?.value) { + onInput(); + } +} + export default [ "search", "searchInFiles", strings["search in files"], (/**@type {HTMLElement} */ el) => { el.classList.add("search-in-files"); + Sidebar.on("show", restoreResultScroll); el.content = ( <> -
+
+
+ {strings["search in files"]} +
+ + +
+
+
+
-
- -