[
  {
    "path": ".cirrus.yml",
    "content": "freebsd_instance:\n  image_family: freebsd-16-0-snap\n\ntask:\n  name: FreeBSD\n  env:\n    IGNORE_OSVERSION: yes\n  skip_notifications: true\n  prerequisites_script:\n    - pkg update -f\n    - pkg upgrade -y\n    - pkg install -y devel/git devel/pkgconf graphics/vips www/node22 www/npm\n    - pkg-config --modversion vips-cpp\n  install_script:\n    - npm install\n    - npm run build\n  test_script:\n    - node --test test/unit/io.js\n"
  },
  {
    "path": ".editorconfig",
    "content": "# http://editorconfig.org\nroot = true\n\n[*]\nindent_style = space\nindent_size = 2\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\nmax_line_length = 120\n"
  },
  {
    "path": ".github/CONTRIBUTING.md",
    "content": "# Contributing to sharp\n\nHello, thank you for your interest in helping!\n\n## Submit a new bug report\n\nPlease create a [new issue](https://github.com/lovell/sharp/issues/new) containing the steps to reproduce the problem.\n\nNew bugs are assigned a `triage` label whilst under investigation.\n\n## Submit a new feature request\n\nIf a [similar request](https://github.com/lovell/sharp/labels/enhancement) exists,\nit's probably fastest to add a comment to it about your requirement.\n\nImplementation is usually straightforward if libvips\n[already supports](https://www.libvips.org/API/current/function-list.html)\nthe feature you need.\n\n## Submit a Pull Request to fix a bug\n\nThank you! To prevent the problem occurring again, please add unit tests that would have failed.\n\nPlease select the `main` branch as the destination for your Pull Request so your fix can be included in the next minor release.\n\nPlease squash your changes into a single commit using a command like `git rebase -i upstream/main`.\n\nTo test C++ changes, you can compile the module using `npm run build` and then run the tests using `npm test`.\n\n## Submit a Pull Request with a new feature\n\nPlease add JavaScript [unit tests](https://github.com/lovell/sharp/tree/main/test/unit) to cover your new feature.\nPlease also update the [TypeScript definitions](https://github.com/lovell/sharp/tree/main/lib/index.d.ts), along with the [type definition tests](https://github.com/lovell/sharp/tree/main/test/types/sharp.test-d.ts).\n\nWhere possible, the functional tests use gradient-based perceptual hashes\nbased on [dHash](http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html)\nto compare expected vs actual images.\n\nYou deserve to add your details to the [list of contributors](https://github.com/lovell/sharp/blob/main/package.json#L5).\n\nAny change that modifies the existing public API should be added to the relevant work-in-progress branch for inclusion in the next major release.\n\nPlease squash your changes into a single commit using a command like `git rebase -i upstream/<wip-branch>`.\n\n### Add a new public method\n\nThe API tries to be as fluent as possible.\nImage processing concepts follow the naming conventions from libvips and, to a lesser extent, ImageMagick.\n\nMost methods have optional parameters and assume sensible defaults.\nPlease ensure backwards compatibility where possible.\n\nFeel free to create a [new issue](https://github.com/lovell/sharp/issues/new) to gather feedback on a potential API change.\n\n### Remove an existing public method\n\nA method to be removed should be deprecated in the next major version then removed in the following major version.\n\nBy way of example, the `background()` method present in v0.20.0 was deprecated in v0.21.0 and removed in v0.22.0.\n\n## Documentation\n\nThe public API is documented with [JSDoc](https://jsdoc.app/) annotated comments.\n\nThese can be converted to Markdown by running:\n```sh\nnpm run docs-build\n```\n\nPlease include documentation updates in any Pull Request that modifies the public API.\n\n## Run the tests\n\n### Functional tests and static code analysis\n\n```sh\nnpm test\n```\n\n### Memory leak tests\n\nRequires [Valgrind](http://valgrind.org/).\n\n```sh\nnpm run test-leak\n```\n\n## Finally\n\nPlease feel free to ask any questions via a\n[new issue](https://github.com/lovell/sharp/issues/new).\n\nIf you're unable to post details publicly, please\n[e-mail](https://github.com/lovell/sharp/blob/main/package.json#L5)\nfor private, paid consulting.\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "open_collective: libvips\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: Documentation\n    url: https://sharp.pixelplumbing.com/\n    about: Installation instructions, complete API documentation with examples, changelog\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea\nlabels: enhancement\n\n---\n\n## Feature request\n\n### What are you trying to achieve?\n\n<!-- Please provide context here. -->\n\n### When you searched for similar feature requests, what did you find that might be related?\n\n<!-- Please demonstrate your research here. -->\n\n### What would you expect the API to look like?\n\n<!-- Please provide your suggestions here. -->\n\n### What alternatives have you considered?\n\n<!-- Please provide your ideas here. -->\n\n### Please provide sample image(s) that help explain this feature\n\n<!-- Please provide links to one or more images here. -->\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/installation.md",
    "content": "---\nname: Installation\nabout: Something went wrong during either 'npm install sharp' or 'require(\"sharp\")'\nlabels: installation\n\n---\n\n<!-- Please try to answer as many of these questions as possible. -->\n\n## Possible install-time or require-time problem\n\n<!-- Please place an [x] in the box to confirm. -->\n\n- [ ] I have read and understood all of the [documentation relating to installation](https://sharp.pixelplumbing.com/install).\n- [ ] I have searched for known bugs relating to this problem in my choice of package manager.\n\nYou must confirm both of these before continuing.\n\n### Are you using the latest version of sharp?\n\n<!-- Please place an [x] in the box to confirm. -->\n\n- [ ] I am using the latest version of `sharp` as reported by `npm view sharp dist-tags.latest`.\n\nIf you cannot confirm this, please upgrade to the latest version and try again before opening an issue.\n\nIf you are using another package which depends on a version of `sharp` that is not the latest,\nplease open an issue against that package instead.\n\n### Are you using a supported runtime?\n\n<!-- Please place an [x] in the relevant box to confirm. -->\n\n- [ ] I am using Node.js with a version that satisfies `^18.17.0 || ^20.3.0 || >=21.0.0`\n- [ ] I am using Deno\n- [ ] I am using Bun\n\nIf you cannot confirm any of these,\nplease upgrade to the latest version\nand try again before opening an issue.\n\n### Are you using a supported package manager and installing optional dependencies?\n\n<!-- Please place an [x] in the relevant box to confirm. -->\n\n- [ ] I am using npm >= 10.1.0 with `--include=optional`\n- [ ] I am using yarn >= 3.2.0\n- [ ] I am using pnpm >= 7.1.0 with `--no-optional=false`\n- [ ] I am using Deno\n- [ ] I am using Bun\n\nIf you cannot confirm any of these, please upgrade to the latest version of your chosen package manager\nand ensure you are allowing the installation of optional or multi-platform dependencies before opening an issue.\n\n### What is the complete error message, including the full stack trace?\n\n<!-- Please provide the error message and stack trace here. -->\n\n### What is the complete output of running `npm install --verbose --foreground-scripts sharp` in an empty directory?\n\n<details>\n\n<!-- Please provide output of `npm install --verbose --foreground-scripts sharp` in an empty directory here. -->\n\n</details>\n\n### What is the output of running `npx envinfo --binaries --system --npmPackages=sharp --npmGlobalPackages=sharp`?\n\n<!-- Please provide output of `npx envinfo --binaries --system --npmPackages=sharp --npmGlobalPackages=sharp` here. -->\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/possible-bug.md",
    "content": "---\nname: Possible bug\nabout: Installation of sharp was successful but then something unexpected occurred using one of its features\nlabels: triage\n\n---\n\n<!-- If this issue relates to installation, please use https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md instead. -->\n\n## Possible bug\n\n### Is this a possible bug in a feature of sharp, unrelated to installation?\n\n<!-- Please place an [x] in the box to confirm. -->\n\n- [ ] Running `npm install sharp` completes without error.\n- [ ] Running `node -e \"require('sharp')\"` completes without error.\n\nIf you cannot confirm both of these, please open an [installation issue](https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md) instead.\n\n### Are you using the latest version of sharp?\n\n<!-- Please place an [x] in the box to confirm. -->\n\n- [ ] I am using the latest version of `sharp` as reported by `npm view sharp dist-tags.latest`.\n\nIf you cannot confirm this, please upgrade to the latest version and try again before opening an issue.\n\nIf you are using another package which depends on a version of `sharp` that is not the latest, please open an issue against that package instead.\n\n### What is the output of running `npx envinfo --binaries --system --npmPackages=sharp --npmGlobalPackages=sharp`?\n\n<!-- Please provide output of the above command here. -->\n\n### Does this problem relate to file caching?\n\nThe default behaviour of libvips is to cache input files, which can lead to `EBUSY` or `EPERM` errors on Windows.\nUse [`sharp.cache(false)`](https://sharp.pixelplumbing.com/api-utility#cache) to switch this feature off.\n\n- [ ] Adding `sharp.cache(false)` does not fix this problem.\n\n### Does this problem relate to images appearing to have been rotated by 90 degrees?\n\nImages that contain EXIF Orientation metadata are not auto-oriented. By default, EXIF metadata is removed.\n\n- To auto-orient pixel values use the parameter-less [`rotate()`](https://sharp.pixelplumbing.com/api-operation#rotate) operation.\n- To retain EXIF Orientation use [`keepExif()`](https://sharp.pixelplumbing.com/api-output#keepexif).\n\n- [ ] Using `rotate()` or `keepExif()` does not fix this problem.\n\n### What are the steps to reproduce?\n\n<!-- Please enter steps to reproduce here. -->\n\n### What is the expected behaviour?\n\n<!-- Please enter the expected behaviour here. -->\n\n### Please provide a minimal, standalone code sample, without other dependencies, that demonstrates this problem\n\n<!-- Please provide either formatted code or a link to a repo/gist that allows someone else to reproduce here. -->\n\n### Please provide sample image(s) that help explain this problem\n\n<!-- Please provide links to one or more images here. -->\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/question.md",
    "content": "---\nname: Question\nabout: For help understanding an existing feature\nlabels: question\n\n---\n\n<!-- If this issue relates to installation, please use https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md instead. -->\n\n## Question about an existing feature\n\n### What are you trying to achieve?\n\n<!-- Please provide context here. -->\n\n### When you searched for similar issues, what did you find that might be related?\n\n<!-- Please demonstrate your research here. -->\n\n### Please provide a minimal, standalone code sample, without other dependencies, that demonstrates this question\n\n<!-- Please provide either formatted code or a link to a repo/gist that helps someone else understand here. -->\n\n### Please provide sample image(s) that help explain this question\n\n<!-- Please provide links to one or more images here. -->\n"
  },
  {
    "path": ".github/SECURITY.md",
    "content": "# Security Policy\n\n## Supported Versions\n\nThe latest version of `sharp` as published to npm\nand reported by `npm view sharp dist-tags.latest`\nis supported with security updates.\n\n## Reporting a Vulnerability\n\nPlease use\n[e-mail](https://github.com/lovell/sharp/blob/main/package.json#L5)\nto report a vulnerability.\n\nYou can expect a response within 48 hours\nif you are a human reporting a genuine issue.\n\nThank you in advance.\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\non:\n  - push\n  - pull_request\npermissions: {}\njobs:\n  lint:\n    permissions:\n      contents: read\n    runs-on: ubuntu-24.04\n    steps:\n      - uses: actions/checkout@v4\n      - uses: actions/setup-node@v5\n        with:\n          node-version: \"24\"\n      - run: npm install --ignore-scripts\n      - run: npm run lint-cpp\n      - run: npm run lint-js\n      - run: npm run lint-types\n  build-native:\n    permissions:\n      contents: read\n    needs: lint\n    name: \"build-${{ matrix.platform }} [Node.js ${{ matrix.nodejs_version_major }}] ${{ matrix.package && '[package]' }}\"\n    runs-on: ${{ matrix.os }}\n    container: ${{ matrix.container }}\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - os: ubuntu-24.04\n            container: rockylinux:8\n            nodejs_arch: x64\n            nodejs_version: \"^18.17.0\"\n            nodejs_version_major: 18\n            platform: linux-x64\n            package: true\n          - os: ubuntu-24.04\n            container: rockylinux:8\n            nodejs_arch: x64\n            nodejs_version: \"^20.3.0\"\n            nodejs_version_major: 20\n            platform: linux-x64\n          - os: ubuntu-24.04\n            container: rockylinux:8\n            nodejs_arch: x64\n            nodejs_version: \"^22.9.0\"\n            nodejs_version_major: 22\n            platform: linux-x64\n          - os: ubuntu-24.04\n            container: node:18-alpine3.17\n            nodejs_version_major: 18\n            platform: linuxmusl-x64\n            package: true\n          - os: ubuntu-24.04\n            container: node:20-alpine3.18\n            nodejs_version_major: 20\n            platform: linuxmusl-x64\n          - os: ubuntu-24.04\n            container: node:22-alpine3.20\n            nodejs_version_major: 22\n            platform: linuxmusl-x64\n          - os: ubuntu-24.04-arm\n            container: arm64v8/rockylinux:8\n            nodejs_arch: arm64\n            nodejs_version: \"^18.17.0\"\n            nodejs_version_major: 18\n            platform: linux-arm64\n            package: true\n          - os: ubuntu-24.04-arm\n            container: arm64v8/rockylinux:8\n            nodejs_arch: arm64\n            nodejs_version: \"^20.3.0\"\n            nodejs_version_major: 20\n            platform: linux-arm64\n          - os: macos-15-intel\n            nodejs_arch: x64\n            nodejs_version: \"^18.17.0\"\n            nodejs_version_major: 18\n            platform: darwin-x64\n            package: true\n          - os: macos-15-intel\n            nodejs_arch: x64\n            nodejs_version: \"^20.3.0\"\n            nodejs_version_major: 20\n            platform: darwin-x64\n          - os: macos-15-intel\n            nodejs_arch: x64\n            nodejs_version: \"^22.9.0\"\n            nodejs_version_major: 22\n            platform: darwin-x64\n          - os: macos-15\n            nodejs_arch: arm64\n            nodejs_version: \"^18.17.0\"\n            nodejs_version_major: 18\n            platform: darwin-arm64\n            package: true\n          - os: macos-15\n            nodejs_arch: arm64\n            nodejs_version: \"^20.3.0\"\n            nodejs_version_major: 20\n            platform: darwin-arm64\n          - os: macos-15\n            nodejs_arch: arm64\n            nodejs_version: \"^22.9.0\"\n            nodejs_version_major: 22\n            platform: darwin-arm64\n          - os: windows-2022\n            nodejs_arch: x86\n            nodejs_version: \"18.18.2\" # pinned to avoid 18.19.0 and npm 10\n            nodejs_version_major: 18\n            platform: win32-ia32\n            package: true\n          - os: windows-2022\n            nodejs_arch: x86\n            nodejs_version: \"^20.3.0\"\n            nodejs_version_major: 20\n            platform: win32-ia32\n          - os: windows-2022\n            nodejs_arch: x86\n            nodejs_version: \"^22.9.0\"\n            nodejs_version_major: 22\n            platform: win32-ia32\n          - os: windows-2022\n            nodejs_arch: x64\n            nodejs_version: \"^18.17.0\"\n            nodejs_version_major: 18\n            platform: win32-x64\n            package: true\n          - os: windows-2022\n            nodejs_arch: x64\n            nodejs_version: \"^20.3.0\"\n            nodejs_version_major: 20\n            platform: win32-x64\n          - os: windows-2022\n            nodejs_arch: x64\n            nodejs_version: \"^22.9.0\"\n            nodejs_version_major: 22\n            platform: win32-x64\n          - os: windows-11-arm\n            nodejs_arch: arm64\n            nodejs_version: \"^20.3.0\"\n            nodejs_version_major: 20\n            platform: win32-arm64\n            package: true\n          - os: windows-11-arm\n            nodejs_arch: arm64\n            nodejs_version: \"^22.9.0\"\n            nodejs_version_major: 22\n            platform: win32-arm64\n    steps:\n      - name: Dependencies (Rocky Linux glibc)\n        if: contains(matrix.container, 'rockylinux')\n        run: |\n          dnf install -y gcc-toolset-14-gcc-c++ make git python3.12 fontconfig google-noto-sans-fonts\n          echo \"/opt/rh/gcc-toolset-14/root/usr/bin\" >> $GITHUB_PATH\n      - name: Dependencies (Linux musl)\n        if: contains(matrix.container, 'alpine')\n        run: apk add build-base git python3 font-noto --update-cache\n      - name: Dependencies (Python 3.11 - macOS, Windows)\n        if: contains(matrix.os, 'macos') || contains(matrix.os, 'windows')\n        uses: actions/setup-python@v5\n        with:\n          python-version: \"3.12\"\n      - name: Dependencies (Node.js)\n        if: \"!contains(matrix.platform, 'linuxmusl')\"\n        uses: actions/setup-node@v5\n        with:\n          node-version: ${{ matrix.nodejs_version }}\n          architecture: ${{ matrix.nodejs_arch }}\n      - uses: actions/checkout@v4\n      - run: npm install\n      - run: npm run build\n      - run: npm run test-unit\n      - if: matrix.package\n        run: npm run package-from-local-build\n      - uses: actions/upload-artifact@v4\n        if: matrix.package\n        with:\n          name: ${{ matrix.platform }}\n          path: npm/${{ matrix.platform }}\n          retention-days: 1\n          if-no-files-found: error\n  build-linuxmusl-arm64:\n    permissions:\n      contents: read\n    needs: lint\n    name: \"build-linuxmusl-arm64 [Node.js ${{ matrix.nodejs_version_major }}] ${{ matrix.package && '[package]' }}\"\n    runs-on: ubuntu-24.04-arm\n    container:\n      image: ${{ matrix.container }}\n      volumes:\n        - /opt:/opt:rw,rshared\n        - /opt:/__e/node20:ro,rshared\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n        - container: node:18-alpine3.17\n          nodejs_version_major: 18\n          package: true\n        - container: node:20-alpine3.18\n          nodejs_version_major: 20\n    steps:\n      - name: Allow Linux musl containers on ARM64 runners # https://github.com/actions/runner/issues/801#issuecomment-2394425757\n        shell: sh\n        run: |\n          sed -i \"/^ID=/s/alpine/NotpineForGHA/\" /etc/os-release\n          apk add nodejs --update-cache\n          mkdir /opt/bin\n          ln -s /usr/bin/node /opt/bin/node\n      - name: Dependencies\n        run: apk add build-base git python3 font-noto --update-cache\n      - uses: actions/checkout@v4\n      - run: npm install\n      - run: npm run build\n      - run: npm run test-unit\n      - if: matrix.package\n        run: npm run package-from-local-build\n      - uses: actions/upload-artifact@v4\n        if: matrix.package\n        with:\n          name: linuxmusl-arm64\n          path: npm/linuxmusl-arm64\n          retention-days: 1\n          if-no-files-found: error\n  build-qemu:\n    permissions:\n      contents: read\n    needs: lint\n    name: \"build-${{ matrix.platform }} [Node.js ${{ matrix.nodejs_version_major }}] [package]\"\n    runs-on: ubuntu-24.04\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - platform: linux-arm\n            base_image: \"balenalib/rpi-raspbian:bullseye\"\n            nodejs_arch: armv6l\n            nodejs_hostname: unofficial-builds.nodejs.org\n            nodejs_version: \"18.17.0\"\n            nodejs_version_major: 18\n          - platform: linux-s390x\n            base_image: \"--platform=linux/s390x s390x/debian:bookworm\"\n            nodejs_arch: s390x\n            nodejs_hostname: nodejs.org\n            nodejs_version: \"18.17.0\"\n            nodejs_version_major: 18\n          - platform: linux-ppc64\n            base_image: \"--platform=linux/ppc64le ppc64le/debian:bookworm\"\n            nodejs_arch: ppc64le\n            nodejs_hostname: nodejs.org\n            nodejs_version: \"18.17.0\"\n            nodejs_version_major: 18\n          - platform: linux-riscv64\n            base_image: \"--platform=linux/riscv64 riscv64/debian:trixie\"\n            compiler_flags: \"-march=rv64gc\"\n            nodejs_arch: riscv64\n            nodejs_hostname: unofficial-builds.nodejs.org\n            nodejs_version: \"20.19.5\"\n            nodejs_version_major: 20\n    steps:\n      - uses: actions/checkout@v4\n      - uses: uraimo/run-on-arch-action@v3\n        with:\n          arch: none\n          distro: none\n          base_image: ${{ matrix.base_image }}\n          env: |\n            CFLAGS: \"${{ matrix.compiler_flags }}\"\n            CXXFLAGS: \"${{ matrix.compiler_flags }}\"\n          run: |\n            apt-get update\n            apt-get install -y curl g++ git libatomic1 make python3 xz-utils\n            mkdir /opt/nodejs\n            curl --silent https://${{ matrix.nodejs_hostname }}/download/release/v${{ matrix.nodejs_version}}/node-v${{ matrix.nodejs_version}}-linux-${{ matrix.nodejs_arch }}.tar.xz | tar xJC /opt/nodejs --strip-components=1\n            export PATH=$PATH:/opt/nodejs/bin\n            npm install\n            npm run build\n            node --test test/unit/io.js\n            npm run package-from-local-build\n      - uses: actions/upload-artifact@v4\n        with:\n          name: ${{ matrix.platform }}\n          path: npm/${{ matrix.platform }}\n          retention-days: 1\n          if-no-files-found: error\n  build-emscripten:\n    permissions:\n      contents: read\n    needs: lint\n    name: \"build-wasm32 [package]\"\n    runs-on: ubuntu-24.04\n    container: \"emscripten/emsdk:4.0.18\"\n    steps:\n      - uses: actions/checkout@v4\n      - name: Dependencies\n        run: apt-get update && apt-get install -y pkg-config\n      - name: Dependencies (Node.js)\n        uses: actions/setup-node@v5\n        with:\n          node-version: \"20\"\n      - run: npm install\n      - run: emmake npm run build\n      - name: Verify emscripten versions match\n        run: |\n          EMSCRIPTEN_VERSION_LIBVIPS=$(node -p \"require('@img/sharp-libvips-dev-wasm32/versions').emscripten\")\n          EMSCRIPTEN_VERSION_SHARP=$(emcc -dumpversion)\n          echo \"libvips built with emscripten $EMSCRIPTEN_VERSION_LIBVIPS\"\n          echo \"sharp built with emscripten $EMSCRIPTEN_VERSION_SHARP\"\n          test \"$EMSCRIPTEN_VERSION_LIBVIPS\" = \"$EMSCRIPTEN_VERSION_SHARP\"\n      - run: emmake npm run test-unit\n      - run: emmake npm run package-from-local-build\n      - uses: actions/upload-artifact@v4\n        with:\n          name: wasm32\n          path: npm/wasm32\n          retention-days: 1\n          if-no-files-found: error\n  release:\n    permissions:\n      contents: write\n      id-token: write\n    runs-on: ubuntu-24.04\n    needs:\n      - build-native\n      - build-linuxmusl-arm64\n      - build-qemu\n      - build-emscripten\n    steps:\n      - uses: actions/checkout@v4\n      - uses: actions/download-artifact@v4\n        with:\n          path: npm\n      - name: Create npm workspace tarball\n        run: tar -vcaf npm-workspace.tar.xz --directory npm --exclude=from-local-build.js .\n      - uses: actions/setup-node@v5\n        with:\n          node-version: '24'\n      - name: Create release notes\n        run: npm run package-release-notes\n      - name: Create GitHub release for tag\n        if: startsWith(github.ref, 'refs/tags/v')\n        uses: ncipollo/release-action@v1\n        with:\n          artifacts: npm-workspace.tar.xz\n          artifactContentType: application/x-xz\n          prerelease: ${{ contains(github.ref, '-rc') }}\n          makeLatest: ${{ !contains(github.ref, '-rc') }}\n          bodyFile: release-notes.md\n      - name: Publish platform-specific npm packages\n        if: startsWith(github.ref, 'refs/tags/v')\n        run: cd npm && npm publish --workspaces --tag=${{ contains(github.ref, '-rc') && 'next' || 'latest' }}\n      - name: Publish sharp npm package\n        if: startsWith(github.ref, 'refs/tags/v')\n        run: npm publish --tag=${{ contains(github.ref, '-rc') && 'next' || 'latest' }}\n"
  },
  {
    "path": ".github/workflows/npm.yml",
    "content": "name: \"CI: npm smoke test\"\n\non:\n  push:\n    tags:\n      - \"v**\"\n\npermissions: {}\n\njobs:\n  release-smoke-test:\n    name: \"${{ github.ref_name }} ${{ matrix.name }}\"\n    runs-on: ${{ matrix.runs-on }}\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - name: linux-x64-node-npm\n            runs-on: ubuntu-24.04\n            runtime: node\n            package-manager: npm\n          - name: linux-x64-node-pnpm\n            runs-on: ubuntu-24.04\n            runtime: node\n            package-manager: pnpm\n          - name: linux-x64-node-yarn\n            runs-on: ubuntu-24.04\n            runtime: node\n            package-manager: yarn\n          - name: linux-x64-node-yarn-pnp\n            runs-on: ubuntu-24.04\n            runtime: node\n            package-manager: yarn-pnp\n          - name: linux-x64-node-yarn-v1\n            runs-on: ubuntu-24.04\n            runtime: node\n            package-manager: yarn-v1\n          - name: linux-x64-deno\n            runs-on: ubuntu-24.04\n            runtime: deno\n          - name: linux-x64-bun\n            runs-on: ubuntu-24.04\n            runtime: bun\n\n          - name: darwin-x64-node-npm\n            runs-on: macos-15-intel\n            runtime: node\n            package-manager: npm\n          - name: darwin-x64-node-pnpm\n            runs-on: macos-15-intel\n            runtime: node\n            package-manager: pnpm\n          - name: darwin-x64-node-yarn\n            runs-on: macos-15-intel\n            runtime: node\n            package-manager: yarn\n          - name: darwin-x64-node-yarn-pnp\n            runs-on: macos-15-intel\n            runtime: node\n            package-manager: yarn-pnp\n          - name: darwin-x64-node-yarn-v1\n            runs-on: macos-15-intel\n            runtime: node\n            package-manager: yarn-v1\n          - name: darwin-x64-deno\n            runs-on: macos-15-intel\n            runtime: deno\n          - name: darwin-x64-bun\n            runs-on: macos-15-intel\n            runtime: bun\n\n          - name: win32-x64-node-npm\n            runs-on: windows-2022\n            runtime: node\n            package-manager: npm\n          - name: win32-x64-node-pnpm\n            runs-on: windows-2022\n            runtime: node\n            package-manager: pnpm\n          - name: win32-x64-node-yarn\n            runs-on: windows-2022\n            runtime: node\n            package-manager: yarn\n          - name: win32-x64-node-yarn-pnp\n            runs-on: windows-2022\n            runtime: node\n            package-manager: yarn-pnp\n          - name: win32-x64-node-yarn-v1\n            runs-on: windows-2022\n            runtime: node\n            package-manager: yarn-v1\n          - name: win32-x64-deno\n            runs-on: windows-2022\n            runtime: deno\n\n    steps:\n      - name: Install Node.js\n        if: ${{ matrix.runtime == 'node' }}\n        uses: actions/setup-node@v5\n        with:\n          node-version: 20\n      - name: Install pnpm\n        if: ${{ matrix.package-manager == 'pnpm' }}\n        uses: pnpm/action-setup@v4\n        with:\n          version: 8\n      - name: Install Deno\n        if: ${{ matrix.runtime == 'deno' }}\n        uses: denoland/setup-deno@v2\n        with:\n          deno-version: v2.x\n      - name: Install Bun\n        if: ${{ matrix.runtime == 'bun' }}\n        uses: oven-sh/setup-bun@v2\n        with:\n          bun-version: latest\n\n      - name: Version\n        id: version\n        uses: actions/github-script@v8\n        with:\n          script: |\n            core.setOutput('semver', context.ref.replace('refs/tags/v',''))\n      - name: Create package.json\n        uses: DamianReeves/write-file-action@v1.3\n        with:\n          path: package.json\n          contents: |\n            {\n              \"dependencies\": {\n                \"sharp\": \"${{ steps.version.outputs.semver }}\"\n              },\n              \"type\": \"module\"\n            }\n      - name: Create release.mjs\n        uses: DamianReeves/write-file-action@v1.3\n        with:\n          path: release.mjs\n          contents: |\n            import { deepStrictEqual } from 'node:assert';\n            import sharp from 'sharp';\n            deepStrictEqual(['.jpg', '.jpeg', '.jpe', '.jfif'], sharp.format.jpeg.input.fileSuffix);\n\n      - name: Run with Node.js + npm\n        if: ${{ matrix.package-manager == 'npm' }}\n        run: |\n          npm install --ignore-scripts\n          node release.mjs\n\n      - name: Run with Node.js + pnpm\n        if: ${{ matrix.package-manager == 'pnpm' }}\n        run: |\n          pnpm install --ignore-scripts\n          node release.mjs\n\n      - name: Run with Node.js + yarn\n        if: ${{ matrix.package-manager == 'yarn' }}\n        run: |\n          corepack enable\n          yarn set version stable\n          yarn config set enableImmutableInstalls false\n          yarn config set enableScripts false\n          yarn config set nodeLinker node-modules\n          yarn install\n          node release.mjs\n\n      - name: Run with Node.js + yarn pnp\n        if: ${{ matrix.package-manager == 'yarn-pnp' }}\n        run: |\n          corepack enable\n          yarn set version stable\n          yarn config set enableImmutableInstalls false\n          yarn config set enableScripts false\n          yarn config set nodeLinker pnp\n          yarn install\n          yarn node release.mjs\n\n      - name: Run with Node.js + yarn v1\n        if: ${{ matrix.package-manager == 'yarn-v1' }}\n        run: |\n          corepack enable\n          yarn set version classic\n          yarn install\n          node release.mjs\n\n      - name: Run with Deno\n        if: ${{ matrix.runtime == 'deno' }}\n        run: |\n          deno install\n          deno run --allow-env --allow-ffi --allow-read --allow-sys release.mjs\n\n      - name: Run with Bun\n        if: ${{ matrix.runtime == 'bun' }}\n        run: |\n          bun install --ignore-scripts\n          bun release.mjs\n"
  },
  {
    "path": ".gitignore",
    "content": "src/build\nsrc/node_modules\nnode_modules\n/coverage\nnpm/*/*\n!npm/*/package.json\ntest/bench/node_modules\ntest/fixtures/output*\ntest/fixtures/vips-properties.xml\ntest/leak/libvips.supp\n.DS_Store\n.nyc_output\n.vscode/\npackage-lock.json\n.idea\n.firebase\n.astro\ndocs/dist\nrelease-notes.md\n"
  },
  {
    "path": "LICENSE",
    "content": "Apache License\nVersion 2.0, January 2004\nhttp://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n\"License\" shall mean the terms and conditions for use, reproduction, and\ndistribution as defined by Sections 1 through 9 of this document.\n\n\"Licensor\" shall mean the copyright owner or entity authorized by the copyright\nowner that is granting the License.\n\n\"Legal Entity\" shall mean the union of the acting entity and all other entities\nthat control, are controlled by, or are under common control with that entity.\nFor the purposes of this definition, \"control\" means (i) the power, direct or\nindirect, to cause the direction or management of such entity, whether by\ncontract or otherwise, or (ii) ownership of fifty percent (50%) or more of the\noutstanding shares, or (iii) beneficial ownership of such entity.\n\n\"You\" (or \"Your\") shall mean an individual or Legal Entity exercising\npermissions granted by this License.\n\n\"Source\" form shall mean the preferred form for making modifications, including\nbut not limited to software source code, documentation source, and configuration\nfiles.\n\n\"Object\" form shall mean any form resulting from mechanical transformation or\ntranslation of a Source form, including but not limited to compiled object code,\ngenerated documentation, and conversions to other media types.\n\n\"Work\" shall mean the work of authorship, whether in Source or Object form, made\navailable under the License, as indicated by a copyright notice that is included\nin or attached to the work (an example is provided in the Appendix below).\n\n\"Derivative Works\" shall mean any work, whether in Source or Object form, that\nis based on (or derived from) the Work and for which the editorial revisions,\nannotations, elaborations, or other modifications represent, as a whole, an\noriginal work of authorship. For the purposes of this License, Derivative Works\nshall not include works that remain separable from, or merely link (or bind by\nname) to the interfaces of, the Work and Derivative Works thereof.\n\n\"Contribution\" shall mean any work of authorship, including the original version\nof the Work and any modifications or additions to that Work or Derivative Works\nthereof, that is intentionally submitted to Licensor for inclusion in the Work\nby the copyright owner or by an individual or Legal Entity authorized to submit\non behalf of the copyright owner. For the purposes of this definition,\n\"submitted\" means any form of electronic, verbal, or written communication sent\nto the Licensor or its representatives, including but not limited to\ncommunication on electronic mailing lists, source code control systems, and\nissue tracking systems that are managed by, or on behalf of, the Licensor for\nthe purpose of discussing and improving the Work, but excluding communication\nthat is conspicuously marked or otherwise designated in writing by the copyright\nowner as \"Not a Contribution.\"\n\n\"Contributor\" shall mean Licensor and any individual or Legal Entity on behalf\nof whom a Contribution has been received by Licensor and subsequently\nincorporated within the Work.\n\n2. Grant of Copyright License.\n\nSubject to the terms and conditions of this License, each Contributor hereby\ngrants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,\nirrevocable copyright license to reproduce, prepare Derivative Works of,\npublicly display, publicly perform, sublicense, and distribute the Work and such\nDerivative Works in Source or Object form.\n\n3. Grant of Patent License.\n\nSubject to the terms and conditions of this License, each Contributor hereby\ngrants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,\nirrevocable (except as stated in this section) patent license to make, have\nmade, use, offer to sell, sell, import, and otherwise transfer the Work, where\nsuch license applies only to those patent claims licensable by such Contributor\nthat are necessarily infringed by their Contribution(s) alone or by combination\nof their Contribution(s) with the Work to which such Contribution(s) was\nsubmitted. If You institute patent litigation against any entity (including a\ncross-claim or counterclaim in a lawsuit) alleging that the Work or a\nContribution incorporated within the Work constitutes direct or contributory\npatent infringement, then any patent licenses granted to You under this License\nfor that Work shall terminate as of the date such litigation is filed.\n\n4. Redistribution.\n\nYou may reproduce and distribute copies of the Work or Derivative Works thereof\nin any medium, with or without modifications, and in Source or Object form,\nprovided that You meet the following conditions:\n\nYou must give any other recipients of the Work or Derivative Works a copy of\nthis License; and\nYou must cause any modified files to carry prominent notices stating that You\nchanged the files; and\nYou must retain, in the Source form of any Derivative Works that You distribute,\nall copyright, patent, trademark, and attribution notices from the Source form\nof the Work, excluding those notices that do not pertain to any part of the\nDerivative Works; and\nIf the Work includes a \"NOTICE\" text file as part of its distribution, then any\nDerivative Works that You distribute must include a readable copy of the\nattribution notices contained within such NOTICE file, excluding those notices\nthat do not pertain to any part of the Derivative Works, in at least one of the\nfollowing places: within a NOTICE text file distributed as part of the\nDerivative Works; within the Source form or documentation, if provided along\nwith the Derivative Works; or, within a display generated by the Derivative\nWorks, if and wherever such third-party notices normally appear. The contents of\nthe NOTICE file are for informational purposes only and do not modify the\nLicense. You may add Your own attribution notices within Derivative Works that\nYou distribute, alongside or as an addendum to the NOTICE text from the Work,\nprovided that such additional attribution notices cannot be construed as\nmodifying the License.\nYou may add Your own copyright statement to Your modifications and may provide\nadditional or different license terms and conditions for use, reproduction, or\ndistribution of Your modifications, or for any such Derivative Works as a whole,\nprovided Your use, reproduction, and distribution of the Work otherwise complies\nwith the conditions stated in this License.\n\n5. Submission of Contributions.\n\nUnless You explicitly state otherwise, any Contribution intentionally submitted\nfor inclusion in the Work by You to the Licensor shall be under the terms and\nconditions of this License, without any additional terms or conditions.\nNotwithstanding the above, nothing herein shall supersede or modify the terms of\nany separate license agreement you may have executed with Licensor regarding\nsuch Contributions.\n\n6. Trademarks.\n\nThis License does not grant permission to use the trade names, trademarks,\nservice marks, or product names of the Licensor, except as required for\nreasonable and customary use in describing the origin of the Work and\nreproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty.\n\nUnless required by applicable law or agreed to in writing, Licensor provides the\nWork (and each Contributor provides its Contributions) on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,\nincluding, without limitation, any warranties or conditions of TITLE,\nNON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are\nsolely responsible for determining the appropriateness of using or\nredistributing the Work and assume any risks associated with Your exercise of\npermissions under this License.\n\n8. Limitation of Liability.\n\nIn no event and under no legal theory, whether in tort (including negligence),\ncontract, or otherwise, unless required by applicable law (such as deliberate\nand grossly negligent acts) or agreed to in writing, shall any Contributor be\nliable to You for damages, including any direct, indirect, special, incidental,\nor consequential damages of any character arising as a result of this License or\nout of the use or inability to use the Work (including but not limited to\ndamages for loss of goodwill, work stoppage, computer failure or malfunction, or\nany and all other commercial damages or losses), even if such Contributor has\nbeen advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability.\n\nWhile redistributing the Work or Derivative Works thereof, You may choose to\noffer, and charge a fee for, acceptance of support, warranty, indemnity, or\nother liability obligations and/or rights consistent with this License. However,\nin accepting such obligations, You may act only on Your own behalf and on Your\nsole responsibility, not on behalf of any other Contributor, and only if You\nagree to indemnify, defend, and hold each Contributor harmless for any liability\nincurred by, or claims asserted against, such Contributor by reason of your\naccepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work\n\nTo apply the Apache License to your work, attach the following boilerplate\nnotice, with the fields enclosed by brackets \"[]\" replaced with your own\nidentifying information. (Don't include the brackets!) The text should be\nenclosed in the appropriate comment syntax for the file format. We also\nrecommend that a file or class name and description of purpose be included on\nthe same \"printed page\" as the copyright notice for easier identification within\nthird-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# sharp\n\n<img src=\"https://sharp.pixelplumbing.com/sharp-logo.svg\" width=\"160\" height=\"160\" alt=\"sharp logo\" align=\"right\">\n\nThe typical use case for this high speed Node-API module\nis to convert large images in common formats to\nsmaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.\n\nIt can be used with all JavaScript runtimes\nthat provide support for Node-API v9, including\nNode.js (^18.17.0 or >= 20.3.0), Deno and Bun.\n\nResizing an image is typically 4x-5x faster than using the\nquickest ImageMagick and GraphicsMagick settings\ndue to its use of [libvips](https://github.com/libvips/libvips).\n\nColour spaces, embedded ICC profiles and alpha transparency channels are all handled correctly.\nLanczos resampling ensures quality is not sacrificed for speed.\n\nAs well as image resizing, operations such as\nrotation, extraction, compositing and gamma correction are available.\n\nMost modern macOS, Windows and Linux systems\ndo not require any additional install or runtime dependencies.\n\n## Documentation\n\nVisit [sharp.pixelplumbing.com](https://sharp.pixelplumbing.com/) for complete\n[installation instructions](https://sharp.pixelplumbing.com/install),\n[API documentation](https://sharp.pixelplumbing.com/api-constructor),\n[benchmark tests](https://sharp.pixelplumbing.com/performance) and\n[changelog](https://sharp.pixelplumbing.com/changelog).\n\n## Examples\n\n```sh\nnpm install sharp\n```\n\n```javascript\nconst sharp = require('sharp');\n```\n\n### Callback\n\n```javascript\nsharp(inputBuffer)\n  .resize(320, 240)\n  .toFile('output.webp', (err, info) => { ... });\n```\n\n### Promise\n\n```javascript\nsharp('input.jpg')\n  .rotate()\n  .resize(200)\n  .jpeg({ mozjpeg: true })\n  .toBuffer()\n  .then( data => { ... })\n  .catch( err => { ... });\n```\n\n### Async/await\n\n```javascript\nconst semiTransparentRedPng = await sharp({\n  create: {\n    width: 48,\n    height: 48,\n    channels: 4,\n    background: { r: 255, g: 0, b: 0, alpha: 0.5 }\n  }\n})\n  .png()\n  .toBuffer();\n```\n\n### Stream\n\n```javascript\nconst roundedCorners = Buffer.from(\n  '<svg><rect x=\"0\" y=\"0\" width=\"200\" height=\"200\" rx=\"50\" ry=\"50\"/></svg>'\n);\n\nconst roundedCornerResizer =\n  sharp()\n    .resize(200, 200)\n    .composite([{\n      input: roundedCorners,\n      blend: 'dest-in'\n    }])\n    .png();\n\nreadableStream\n  .pipe(roundedCornerResizer)\n  .pipe(writableStream);\n```\n\n## Contributing\n\nA [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)\ncovers reporting bugs, requesting features and submitting code changes.\n\n## Licensing\n\nCopyright 2013 Lovell Fuller and others.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n"
  },
  {
    "path": "biome.json",
    "content": "{\n  \"$schema\": \"https://biomejs.dev/schemas/2.3.4/schema.json\",\n  \"vcs\": {\n    \"enabled\": true,\n    \"clientKind\": \"git\",\n    \"useIgnoreFile\": true\n  },\n  \"files\": {\n    \"ignoreUnknown\": true\n  },\n  \"linter\": {\n    \"enabled\": true,\n    \"rules\": {\n      \"recommended\": true\n    }\n  },\n  \"formatter\": {\n    \"enabled\": false,\n    \"useEditorconfig\": true\n  },\n  \"javascript\": {\n    \"formatter\": {\n      \"quoteStyle\": \"single\"\n    }\n  }\n}\n"
  },
  {
    "path": "docs/astro.config.mjs",
    "content": "// @ts-check\nimport starlight from '@astrojs/starlight';\nimport { defineConfig } from 'astro/config';\nimport starlightAutoSidebar from 'starlight-auto-sidebar';\n\nimport { version } from '../package.json';\n\nexport default defineConfig({\n  site: 'https://sharp.pixelplumbing.com',\n  integrations: [\n    starlight({\n      title: 'sharp',\n      description:\n        'High performance Node.js image processing. The fastest module to resize JPEG, PNG, WebP and TIFF images.',\n      logo: {\n        src: './src/assets/sharp-logo.svg',\n        alt: '#'\n      },\n      customCss: ['./src/styles/custom.css'],\n      head: [{\n        tag: 'meta',\n        attrs: {\n          'http-equiv': 'Content-Security-Policy',\n          content: \"default-src 'self'; connect-src 'self'; object-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://static.cloudflareinsights.com/beacon.min.js/;\"\n        }\n      }, {\n        tag: 'link',\n        attrs: {\n          rel: 'author',\n          href: '/humans.txt',\n          type: 'text/plain'\n        }\n      }, {\n        tag: 'script',\n        attrs: {\n          type: 'application/ld+json'\n        },\n        content: JSON.stringify({\n          '@context': 'https://schema.org',\n          '@type': 'SoftwareSourceCode',\n          name: 'sharp',\n          description: 'High performance Node.js image processing',\n          url: 'https://sharp.pixelplumbing.com',\n          codeRepository: 'https://github.com/lovell/sharp',\n          programmingLanguage: ['JavaScript', 'C++'],\n          runtimePlatform: 'Node.js',\n          copyrightHolder: {\n            '@context': 'https://schema.org',\n            '@type': 'Person',\n            name: 'Lovell Fuller'\n          },\n          copyrightYear: 2013,\n          license: 'https://www.apache.org/licenses/LICENSE-2.0'\n        })\n      }],\n      sidebar: [\n        { label: 'Home', link: '/' },\n        { label: 'Installation', slug: 'install' },\n        {\n          label: 'API',\n          items: [\n            { label: 'Constructor', slug: 'api-constructor' },\n            { label: 'Input metadata', slug: 'api-input' },\n            { label: 'Output options', slug: 'api-output' },\n            { label: 'Resizing images', slug: 'api-resize' },\n            { label: 'Compositing images', slug: 'api-composite' },\n            { label: 'Image operations', slug: 'api-operation' },\n            { label: 'Colour manipulation', slug: 'api-colour' },\n            { label: 'Channel manipulation', slug: 'api-channel' },\n            { label: 'Global properties', slug: 'api-utility' }\n          ]\n        },\n        { label: 'Performance', slug: 'performance' },\n        {\n          label: 'Changelog',\n          collapsed: true,\n          autogenerate: { directory: 'changelog' }\n        }\n      ],\n      social: [\n        { icon: 'openCollective', label: 'Open Collective', href: 'https://opencollective.com/libvips' },\n        { icon: 'github', label: 'GitHub', href: 'https://github.com/lovell/sharp' }\n      ],\n      plugins: [starlightAutoSidebar()]\n    })\n  ],\n  redirects: {\n    '/changelog': `/changelog/v${version}`\n  }\n});\n"
  },
  {
    "path": "docs/build.mjs",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport jsdoc2md from 'jsdoc-to-markdown';\n\nconst pages = {\n  constructor: 'Constructor',\n  input: 'Input metadata',\n  resize: 'Resizing images',\n  composite: 'Compositing images',\n  operation: 'Image operations',\n  colour: 'Colour manipulation',\n  channel: 'Channel manipulation',\n  output: 'Output options',\n  utility: 'Global properties'\n};\n\nObject.keys(pages).forEach(async (m) => {\n  const input = path.join('lib', `${m}.js`);\n  const output = path.join('docs', 'src', 'content', 'docs', `api-${m}.md`);\n\n  const ast = await jsdoc2md.getTemplateData({ files: input });\n  const markdown = await jsdoc2md.render({\n    data: ast,\n    'global-index-format': 'none',\n    'module-index-format': 'none'\n  });\n\n  const cleanMarkdown =\n    `---\\n# This file was auto-generated from JSDoc in lib/${m}.js\\ntitle: ${pages[m]}\\n---\\n\\n` +\n    markdown\n      .replace(/(## )([A-Za-z0-9]+)([^\\n]*)/g, '$1$2\\n> $2$3\\n') // simplify headings\n      .replace(/<a name=\"[A-Za-z0-9+]+\"><\\/a>/g, '') // remove anchors\n      .replace(/\\*\\*Kind\\*\\*: global[^\\n]+/g, '') // remove all \"global\" Kind labels (requires JSDoc refactoring)\n      .trim();\n\n  await fs.writeFile(output, cleanMarkdown);\n});\n"
  },
  {
    "path": "docs/firebase.json",
    "content": "{\n  \"hosting\": {\n    \"site\": \"pixelplumbing-sharp\",\n    \"public\": \"dist\",\n    \"headers\": [\n      {\n        \"source\": \"**\",\n        \"headers\": [\n          { \"key\": \"Cache-Control\", \"value\": \"max-age=86400\" },\n          { \"key\": \"X-Content-Type-Options\", \"value\": \"nosniff\" },\n          { \"key\": \"X-Frame-Options\", \"value\": \"SAMEORIGIN\" }\n        ]\n      }\n    ]\n  }\n}\n"
  },
  {
    "path": "docs/package.json",
    "content": "{\n  \"name\": \"sharp-docs\",\n  \"type\": \"module\",\n  \"version\": \"0.0.1\",\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"astro dev\",\n    \"start\": \"astro dev\",\n    \"build\": \"astro build\",\n    \"preview\": \"astro preview\",\n    \"astro\": \"astro\"\n  },\n  \"dependencies\": {\n    \"@astrojs/starlight\": \"^0.36.2\",\n    \"astro\": \"^5.15.3\",\n    \"starlight-auto-sidebar\": \"^0.1.3\"\n  }\n}\n"
  },
  {
    "path": "docs/public/humans.txt",
    "content": "/* THANKS */\n\nName: John Cupitt\nGitHub: https://github.com/jcupitt\n\nName: Pierre Inglebert\nGitHub: https://github.com/pierreinglebert\n\nName: Jonathan Ong\nGitHub: https://github.com/jonathanong\n\nName: Chanon Sajjamanochai\nGitHub: https://github.com/chanon\n\nName: Juliano Julio\nGitHub: https://github.com/julianojulio\n\nName: Daniel Gasienica\nGitHub: https://github.com/gasi\n\nName: Julian Walker\nGitHub: https://github.com/julianwa\n\nName: Amit Pitaru\nGitHub: https://github.com/apitaru\n\nName: Brandon Aaron\nGitHub: https://github.com/brandonaaron\n\nName: Andreas Lind\nGitHub: https://github.com/papandreou\n\nName: Maurus Cuelenaere\nGitHub: https://github.com/mcuelenaere\n\nName: Linus Unnebäck\nGitHub: https://github.com/LinusU\n\nName: Victor Mateevitsi\nGitHub: https://github.com/mvictoras\n\nName: Alaric Holloway\nGitHub: https://github.com/skedastik\n\nName: Bernhard K. Weisshuhn\nGitHub: https://github.com/bkw\n\nName: David A. Carley\nGitHub: https://github.com/dacarley\n\nName: John Tobin\nGitHub: https://github.com/jtobinisaniceguy\n\nName: Kenton Gray\nGitHub: https://github.com/kentongray\n\nName: Felix Bünemann\nGitHub: https://github.com/felixbuenemann\n\nName: Samy Al Zahrani\nGitHub: https://github.com/salzhrani\n\nName: Chintan Thakkar\nGitHub: https://github.com/lemnisk8\n\nName: F. Orlando Galashan\nGitHub: https://github.com/frulo\n\nName: Kleis Auke Wolthuizen\nGitHub: https://github.com/kleisauke\n\nName: Matt Hirsch\nGitHub: https://github.com/mhirsch\n\nName: Rahul Nanwani\nGitHub: https://github.com/rnanwani\n\nName: Matthias Thoemmes\nGitHub: https://github.com/cmtt\n\nName: Patrick Paskaris\nGitHub: https://github.com/ppaskaris\n\nName: Jérémy Lal\nGitHub: https://github.com/kapouer\n\nName: Alice Monday\nGitHub: https://github.com/alice0meta\n\nName: Kristo Jorgenson\nGitHub: https://github.com/kristojorg\n\nName: Yves Bos\nGitHub: https://github.com/YvesBos\n\nName: Nicolas Coden\nGitHub: https://github.com/ncoden\n\nName: Matt Parrish\nGitHub: https://github.com/pbomb\n\nName: Matthew McEachen\nGitHub: https://github.com/mceachen\n\nName: Jarda Kotěšovec\nGitHub: https://github.com/jardakotesovec\n\nName: Kenric D'Souza\nGitHub: https://github.com/AzureByte\n\nName: Oleh Aleinyk\nGitHub: https://github.com/oaleynik\n\nName: Marcel Bretschneider\nGitHub: https://github.com/3epnm\n\nName: Andrea Bianco\nGitHub: https://github.com/BiancoA\n\nName: Rik Heywood\nGitHub: https://github.com/rikh42\n\nName: Thomas Parisot\nGitHub: https://github.com/oncletom\n\nName: Nathan Graves\nGitHub: https://github.com/woolite64\n\nName: Tom Lokhorst\nGitHub: https://github.com/tomlokhorst\n\nName: Espen Hovlandsdal\nGitHub: https://github.com/rexxars\n\nName: Sylvain Dumont\nGitHub: https://github.com/sylvaindumont\n\nName: Alun Davies\nGitHub: https://github.com/alundavies\n\nName: Aidan Hoolachan\nGitHub: https://github.com/ajhool\n\nName: Axel Eirola\nGitHub: https://github.com/aeirola\n\nName: Freezy\nGitHub: https://github.com/freezy\n\nName: Julian Aubourg\nGitHub: https://github.com/jaubourg\n\nName: Keith Belovay\nGitHub: https://github.com/fromkeith\n\nName: Michael B. Klein\nGitHub: https://github.com/mbklein\n\nName: Jakub Michálek\nGitHub: https://github.com/Goues\n\nName: Ilya Ovdin\nGitHub: https://github.com/iovdin\n\nName: Andargor\nGitHub: https://github.com/Andargor\n\nName: Nicolas Stepien\nGitHub: https://github.com/MayhemYDG\n\nName: Paul Neave\nGitHub: https://github.com/neave\n\nName: Brendan Kennedy\nGitHub: https://github.com/rustyguts\n\nName: Brychan Bennett-Odlum\nGitHub: https://github.com/BrychanOdlum\n\nName: Edward Silverton\nGitHub: https://github.com/edsilv\n\nName: Dumitru Deveatii\nGitHub: https://github.com/dimadeveatii\n\nName: Roland Asmann\nGitHub: https://github.com/malice00\n\nName: Roman Malieiev\nGitHub: https://github.com/romaleev\n\nName: Jerome Vouillon\nGitHub: https://github.com/vouillon\n\nName: Tomáš Szabo\nGitHub: https://github.com/deftomat\n\nName: Robert O'Rourke\nGitHub: https://github.com/roborourke\n\nName: Denis Soldatov\nGitHub: https://github.com/derom\n\nName: Stefan Probst\nGitHub: https://github.com/stefanprobst\n\nName: Thomas Beiganz\nGitHub: https://github.com/beig\n\nName: Florian Busch\nGitHub: https://github.com/florian-busch\n\nName: Matthieu Salettes\nGitHub: https://github.com/msalettes\n\nName: Taneli Vatanen\nGitHub: https://github.com/Daiz\n\nName: Mart Jansink\nGitHub: https://github.com/mart-jansink\n\nName: Tenpi\nGitHub: https://github.com/Tenpi\n\nName: Zaruike\nGitHub: https://github.com/Zaruike\n\nName: Erlend F\nGitHub: https://github.com/erf\n\nName: Drian Naude\nGitHub: https://github.com/driannaude\n\nName: Max Gordon\nGitHub: https://github.com/gforge\n\nName: Chris Banks\nGitHub: https://github.com/christopherbradleybanks\n\nName: codepage949\nGitHub: https://github.com/codepage949\n\nName: Chris Hranj\nGitHub: https://github.com/Brodan\n\nName: Ankur Parihar\nGitHub: https://github.com/ankurparihar\n\nName: Joona Heinikoski\nGitHub: https://github.com/joonamo\n\nName: AlexanderTheGrey\nGitHub: https://github.com/AlexanderTheGrey\n\nName: Blayne Chard\nGitHub: https://github.com/blacha\n\nName: Brahim\nGitHub: https://github.com/brahima\n\nName: Anton Marsden\nGitHub: https://github.com/antonmarsden\n\nName: Marcos Casagrande\nGitHub: https://github.com/marcosc90\n\nName: Emanuel Jöbstl\nGitHub: https://github.com/ejoebstl\n\nName: Tomasz Janowski\nGitHub: https://github.com/janaz\n\nName: Lachlan Newman\nGitHub: https://github.com/LachlanNewman\n\nName: BJJ\nGitHub: https://github.com/bianjunjie1981\n\nName: Dennis Beatty\nGitHub: https://github.com/dnsbty\n\nName: Ingvar Stepanyan\nGitHub: https://github.com/RReverser\n\nName: Tamás András Horváth\nGitHub: https://github.com/icetee\n\nName: Aaron Che\nGitHub: https://github.com/yolopunk\n\nName: Mert Alev\nGitHub: https://github.com/mertalev\n\nName: Adriaan Meuris\nGitHub: https://github.com/adriaanmeuris\n\nName: Richard Hillmann\nGitHub: https://github.com/project0\n\nName: Pongsatorn Manusopit\nGitHub: https://github.com/ton11797\n\nName: Nathan Keynes\nGitHub: https://github.com/nkeynes\n\nName: Sumit D\nGitHub: https://github.com/sumitd2\n\nName: Caleb Meredith\nGitHub: https://github.com/calebmer\n\nName: Don Denton\nGitHub: https://github.com/happycollision\n\nName: Florent Zabera\nGitHub: https://github.com/florentzabera\n\nName: Quentin Pinçon\nGitHub: https://github.com/qpincon\n\nName: Hans Chen\nGitHub: https://github.com/hans00\n\nName: Thibaut Patel\nGitHub: https://github.com/tpatel\n\nName: Maël Nison\nGitHub: https://github.com/arcanis\n"
  },
  {
    "path": "docs/public/robots.txt",
    "content": "User-agent: *\nDisallow:\n\nSitemap: https://sharp.pixelplumbing.com/sitemap-index.xml\n"
  },
  {
    "path": "docs/src/content/docs/api-channel.md",
    "content": "---\n# This file was auto-generated from JSDoc in lib/channel.js\ntitle: Channel manipulation\n---\n\n## removeAlpha\n> removeAlpha() ⇒ <code>Sharp</code>\n\nRemove alpha channels, if any. This is a no-op if the image does not have an alpha channel.\n\nSee also [flatten](/api-operation/#flatten).\n\n\n**Example**  \n```js\nsharp('rgba.png')\n  .removeAlpha()\n  .toFile('rgb.png', function(err, info) {\n    // rgb.png is a 3 channel image without an alpha channel\n  });\n```\n\n\n## ensureAlpha\n> ensureAlpha([alpha]) ⇒ <code>Sharp</code>\n\nEnsure the output image has an alpha transparency channel.\nIf missing, the added alpha channel will have the specified\ntransparency level, defaulting to fully-opaque (1).\nThis is a no-op if the image already has an alpha channel.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid alpha transparency level\n\n**Since**: 0.21.2  \n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [alpha] | <code>number</code> | <code>1</code> | alpha transparency level (0=fully-transparent, 1=fully-opaque) |\n\n**Example**  \n```js\n// rgba.png will be a 4 channel image with a fully-opaque alpha channel\nawait sharp('rgb.jpg')\n  .ensureAlpha()\n  .toFile('rgba.png')\n```\n**Example**  \n```js\n// rgba is a 4 channel image with a fully-transparent alpha channel\nconst rgba = await sharp(rgb)\n  .ensureAlpha(0)\n  .toBuffer();\n```\n\n\n## extractChannel\n> extractChannel(channel) ⇒ <code>Sharp</code>\n\nExtract a single channel from a multi-channel image.\n\nThe output colourspace will be either `b-w` (8-bit) or `grey16` (16-bit).\n\n\n**Throws**:\n\n- <code>Error</code> Invalid channel\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| channel | <code>number</code> \\| <code>string</code> | zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`. |\n\n**Example**  \n```js\n// green.jpg is a greyscale image containing the green channel of the input\nawait sharp(input)\n  .extractChannel('green')\n  .toFile('green.jpg');\n```\n**Example**  \n```js\n// red1 is the red value of the first pixel, red2 the second pixel etc.\nconst [red1, red2, ...] = await sharp(input)\n  .extractChannel(0)\n  .raw()\n  .toBuffer();\n```\n\n\n## joinChannel\n> joinChannel(images, options) ⇒ <code>Sharp</code>\n\nJoin one or more channels to the image.\nThe meaning of the added channels depends on the output colourspace, set with `toColourspace()`.\nBy default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.\nChannel ordering follows vips convention:\n- sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.\n- CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.\n\nBuffers may be any of the image formats supported by sharp.\nFor raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| images | <code>Array.&lt;(string\\|Buffer)&gt;</code> \\| <code>string</code> \\| <code>Buffer</code> | one or more images (file paths, Buffers). |\n| options | <code>Object</code> | image options, see `sharp()` constructor. |\n\n\n\n## bandbool\n> bandbool(boolOp) ⇒ <code>Sharp</code>\n\nPerform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| boolOp | <code>string</code> | one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. |\n\n**Example**  \n```js\nsharp('3-channel-rgb-input.png')\n  .bandbool(sharp.bool.and)\n  .toFile('1-channel-output.png', function (err, info) {\n    // The output will be a single channel image where each pixel `P = R & G & B`.\n    // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]`\n    // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`.\n  });\n```"
  },
  {
    "path": "docs/src/content/docs/api-colour.md",
    "content": "---\n# This file was auto-generated from JSDoc in lib/colour.js\ntitle: Colour manipulation\n---\n\n## tint\n> tint(tint) ⇒ <code>Sharp</code>\n\nTint the image using the provided colour.\nAn alpha channel may be present and will be unchanged by the operation.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameter\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| tint | <code>string</code> \\| <code>Object</code> | Parsed by the [color](https://www.npmjs.org/package/color) module. |\n\n**Example**  \n```js\nconst output = await sharp(input)\n  .tint({ r: 255, g: 240, b: 16 })\n  .toBuffer();\n```\n\n\n## greyscale\n> greyscale([greyscale]) ⇒ <code>Sharp</code>\n\nConvert to 8-bit greyscale; 256 shades of grey.\nThis is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.\nBy default the output image will be web-friendly sRGB and contain three (identical) colour channels.\nThis may be overridden by other sharp operations such as `toColourspace('b-w')`,\nwhich will produce an output image containing one colour channel.\nAn alpha channel may be present, and will be unchanged by the operation.\n\n\n\n| Param | Type | Default |\n| --- | --- | --- |\n| [greyscale] | <code>Boolean</code> | <code>true</code> | \n\n**Example**  \n```js\nconst output = await sharp(input).greyscale().toBuffer();\n```\n\n\n## grayscale\n> grayscale([grayscale]) ⇒ <code>Sharp</code>\n\nAlternative spelling of `greyscale`.\n\n\n\n| Param | Type | Default |\n| --- | --- | --- |\n| [grayscale] | <code>Boolean</code> | <code>true</code> | \n\n\n\n## pipelineColourspace\n> pipelineColourspace([colourspace]) ⇒ <code>Sharp</code>\n\nSet the pipeline colourspace.\n\nThe input image will be converted to the provided colourspace at the start of the pipeline.\nAll operations will use this colourspace before converting to the output colourspace,\nas defined by [toColourspace](#tocolourspace).\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n**Since**: 0.29.0  \n\n| Param | Type | Description |\n| --- | --- | --- |\n| [colourspace] | <code>string</code> | pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://www.libvips.org/API/current/enum.Interpretation.html) |\n\n**Example**  \n```js\n// Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB.\nawait sharp(input)\n .pipelineColourspace('rgb16')\n .toColourspace('srgb')\n .toFile('16bpc-pipeline-to-8bpc-output.png')\n```\n\n\n## pipelineColorspace\n> pipelineColorspace([colorspace]) ⇒ <code>Sharp</code>\n\nAlternative spelling of `pipelineColourspace`.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| [colorspace] | <code>string</code> | pipeline colorspace. |\n\n\n\n## toColourspace\n> toColourspace([colourspace]) ⇒ <code>Sharp</code>\n\nSet the output colourspace.\nBy default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| [colourspace] | <code>string</code> | output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/enum.Interpretation.html) |\n\n**Example**  \n```js\n// Output 16 bits per pixel RGB\nawait sharp(input)\n .toColourspace('rgb16')\n .toFile('16-bpp.png')\n```\n\n\n## toColorspace\n> toColorspace([colorspace]) ⇒ <code>Sharp</code>\n\nAlternative spelling of `toColourspace`.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| [colorspace] | <code>string</code> | output colorspace. |"
  },
  {
    "path": "docs/src/content/docs/api-composite.md",
    "content": "---\n# This file was auto-generated from JSDoc in lib/composite.js\ntitle: Compositing images\n---\n\n## composite\n> composite(images) ⇒ <code>Sharp</code>\n\nComposite image(s) over the processed (resized, extracted etc.) image.\n\nThe images to composite must be the same size or smaller than the processed image.\nIf both `top` and `left` options are provided, they take precedence over `gravity`.\n\nOther operations in the same processing pipeline (e.g. resize, rotate, flip,\nflop, extract) will always be applied to the input image before composition.\n\nThe `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,\n`dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`,\n`xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`,\n`colour-dodge`, `color-dodge`, `colour-burn`,`color-burn`,\n`hard-light`, `soft-light`, `difference`, `exclusion`.\n\nMore information about blend modes can be found at\nhttps://www.libvips.org/API/current/enum.BlendMode.html\nand https://www.cairographics.org/operators/\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n**Since**: 0.22.0  \n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| images | <code>Array.&lt;Object&gt;</code> |  | Ordered list of images to composite |\n| [images[].input] | <code>Buffer</code> \\| <code>String</code> |  | Buffer containing image data, String containing the path to an image file, or Create object (see below) |\n| [images[].input.create] | <code>Object</code> |  | describes a blank overlay to be created. |\n| [images[].input.create.width] | <code>Number</code> |  |  |\n| [images[].input.create.height] | <code>Number</code> |  |  |\n| [images[].input.create.channels] | <code>Number</code> |  | 3-4 |\n| [images[].input.create.background] | <code>String</code> \\| <code>Object</code> |  | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |\n| [images[].input.text] | <code>Object</code> |  | describes a new text image to be created. |\n| [images[].input.text.text] | <code>string</code> |  | text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`. |\n| [images[].input.text.font] | <code>string</code> |  | font name to render with. |\n| [images[].input.text.fontfile] | <code>string</code> |  | absolute filesystem path to a font file that can be used by `font`. |\n| [images[].input.text.width] | <code>number</code> | <code>0</code> | integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. |\n| [images[].input.text.height] | <code>number</code> | <code>0</code> | integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. |\n| [images[].input.text.align] | <code>string</code> | <code>&quot;&#x27;left&#x27;&quot;</code> | text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). |\n| [images[].input.text.justify] | <code>boolean</code> | <code>false</code> | set this to true to apply justification to the text. |\n| [images[].input.text.dpi] | <code>number</code> | <code>72</code> | the resolution (size) at which to render the text. Does not take effect if `height` is specified. |\n| [images[].input.text.rgba] | <code>boolean</code> | <code>false</code> | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground=\"red\">Red!</span>`. |\n| [images[].input.text.spacing] | <code>number</code> | <code>0</code> | text line height in points. Will use the font line height if none is specified. |\n| [images[].autoOrient] | <code>Boolean</code> | <code>false</code> | set to true to use EXIF orientation data, if present, to orient the image. |\n| [images[].blend] | <code>String</code> | <code>&#x27;over&#x27;</code> | how to blend this image with the image below. |\n| [images[].gravity] | <code>String</code> | <code>&#x27;centre&#x27;</code> | gravity at which to place the overlay. |\n| [images[].top] | <code>Number</code> |  | the pixel offset from the top edge. |\n| [images[].left] | <code>Number</code> |  | the pixel offset from the left edge. |\n| [images[].tile] | <code>Boolean</code> | <code>false</code> | set to true to repeat the overlay image across the entire image with the given `gravity`. |\n| [images[].premultiplied] | <code>Boolean</code> | <code>false</code> | set to true to avoid premultiplying the image below. Equivalent to the `--premultiplied` vips option. |\n| [images[].density] | <code>Number</code> | <code>72</code> | number representing the DPI for vector overlay image. |\n| [images[].raw] | <code>Object</code> |  | describes overlay when using raw pixel data. |\n| [images[].raw.width] | <code>Number</code> |  |  |\n| [images[].raw.height] | <code>Number</code> |  |  |\n| [images[].raw.channels] | <code>Number</code> |  |  |\n| [images[].animated] | <code>boolean</code> | <code>false</code> | Set to `true` to read all frames/pages of an animated image. |\n| [images[].failOn] | <code>string</code> | <code>&quot;&#x27;warning&#x27;&quot;</code> | @see [constructor parameters](/api-constructor/) |\n| [images[].limitInputPixels] | <code>number</code> \\| <code>boolean</code> | <code>268402689</code> | @see [constructor parameters](/api-constructor/) |\n\n**Example**  \n```js\nawait sharp(background)\n  .composite([\n    { input: layer1, gravity: 'northwest' },\n    { input: layer2, gravity: 'southeast' },\n  ])\n  .toFile('combined.png');\n```\n**Example**  \n```js\nconst output = await sharp('input.gif', { animated: true })\n  .composite([\n    { input: 'overlay.png', tile: true, blend: 'saturate' }\n  ])\n  .toBuffer();\n```\n**Example**  \n```js\nsharp('input.png')\n  .rotate(180)\n  .resize(300)\n  .flatten( { background: '#ff6600' } )\n  .composite([{ input: 'overlay.png', gravity: 'southeast' }])\n  .sharpen()\n  .withMetadata()\n  .webp( { quality: 90 } )\n  .toBuffer()\n  .then(function(outputBuffer) {\n    // outputBuffer contains upside down, 300px wide, alpha channel flattened\n    // onto orange background, composited with overlay.png with SE gravity,\n    // sharpened, with metadata, 90% quality WebP image data. Phew!\n  });\n```"
  },
  {
    "path": "docs/src/content/docs/api-constructor.md",
    "content": "---\n# This file was auto-generated from JSDoc in lib/constructor.js\ntitle: Constructor\n---\n\n## Sharp\n> Sharp\n\n\n**Emits**: <code>Sharp#event:info</code>, <code>Sharp#event:warning</code>  \n<a name=\"new_Sharp_new\"></a>\n\n### new\n> new Sharp([input], [options])\n\nConstructor factory to create an instance of `sharp`, to which further methods are chained.\n\nJPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object.\nWhen using Stream based output, derived attributes are available from the `info` event.\n\nNon-critical problems encountered during processing are emitted as `warning` events.\n\nImplements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.\n\nWhen loading more than one page/frame of an animated image,\nthese are combined as a vertically-stacked \"toilet roll\" image\nwhere the overall height is the `pageHeight` multiplied by the number of `pages`.\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [input] | <code>Buffer</code> \\| <code>ArrayBuffer</code> \\| <code>Uint8Array</code> \\| <code>Uint8ClampedArray</code> \\| <code>Int8Array</code> \\| <code>Uint16Array</code> \\| <code>Int16Array</code> \\| <code>Uint32Array</code> \\| <code>Int32Array</code> \\| <code>Float32Array</code> \\| <code>Float64Array</code> \\| <code>string</code> \\| <code>Array</code> |  | if present, can be  a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or  a TypedArray containing raw pixel image data, or  a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.  An array of inputs can be provided, and these will be joined together.  JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. |\n| [options] | <code>Object</code> |  | if present, is an Object with optional attributes. |\n| [options.failOn] | <code>string</code> | <code>&quot;&#x27;warning&#x27;&quot;</code> | When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort. |\n| [options.limitInputPixels] | <code>number</code> \\| <code>boolean</code> | <code>268402689</code> | Do not process input images where the number of pixels  (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.  An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). |\n| [options.unlimited] | <code>boolean</code> | <code>false</code> | Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). |\n| [options.autoOrient] | <code>boolean</code> | <code>false</code> | Set this to `true` to rotate/flip the image to match EXIF `Orientation`, if any. |\n| [options.sequentialRead] | <code>boolean</code> | <code>true</code> | Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. |\n| [options.density] | <code>number</code> | <code>72</code> | number representing the DPI for vector images in the range 1 to 100000. |\n| [options.ignoreIcc] | <code>number</code> | <code>false</code> | should the embedded ICC profile, if any, be ignored. |\n| [options.pages] | <code>number</code> | <code>1</code> | Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages. |\n| [options.page] | <code>number</code> | <code>0</code> | Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based. |\n| [options.animated] | <code>boolean</code> | <code>false</code> | Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`. |\n| [options.raw] | <code>Object</code> |  | describes raw pixel input image data. See `raw()` for pixel ordering. |\n| [options.raw.width] | <code>number</code> |  | integral number of pixels wide. |\n| [options.raw.height] | <code>number</code> |  | integral number of pixels high. |\n| [options.raw.channels] | <code>number</code> |  | integral number of channels, between 1 and 4. |\n| [options.raw.premultiplied] | <code>boolean</code> |  | specifies that the raw input has already been premultiplied, set to `true`  to avoid sharp premultiplying the image. (optional, default `false`) |\n| [options.raw.pageHeight] | <code>number</code> |  | The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`. |\n| [options.create] | <code>Object</code> |  | describes a new image to be created. |\n| [options.create.width] | <code>number</code> |  | integral number of pixels wide. |\n| [options.create.height] | <code>number</code> |  | integral number of pixels high. |\n| [options.create.channels] | <code>number</code> |  | integral number of channels, either 3 (RGB) or 4 (RGBA). |\n| [options.create.background] | <code>string</code> \\| <code>Object</code> |  | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |\n| [options.create.pageHeight] | <code>number</code> |  | The pixel height of each page/frame for animated images, must be an integral factor of `create.height`. |\n| [options.create.noise] | <code>Object</code> |  | describes a noise to be created. |\n| [options.create.noise.type] | <code>string</code> |  | type of generated noise, currently only `gaussian` is supported. |\n| [options.create.noise.mean] | <code>number</code> | <code>128</code> | Mean value of pixels in the generated noise. |\n| [options.create.noise.sigma] | <code>number</code> | <code>30</code> | Standard deviation of pixel values in the generated noise. |\n| [options.text] | <code>Object</code> |  | describes a new text image to be created. |\n| [options.text.text] | <code>string</code> |  | text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`. |\n| [options.text.font] | <code>string</code> |  | font name to render with. |\n| [options.text.fontfile] | <code>string</code> |  | absolute filesystem path to a font file that can be used by `font`. |\n| [options.text.width] | <code>number</code> | <code>0</code> | Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. |\n| [options.text.height] | <code>number</code> | <code>0</code> | Maximum integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. |\n| [options.text.align] | <code>string</code> | <code>&quot;&#x27;left&#x27;&quot;</code> | Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`). |\n| [options.text.justify] | <code>boolean</code> | <code>false</code> | set this to true to apply justification to the text. |\n| [options.text.dpi] | <code>number</code> | <code>72</code> | the resolution (size) at which to render the text. Does not take effect if `height` is specified. |\n| [options.text.rgba] | <code>boolean</code> | <code>false</code> | set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground=\"red\">Red!</span>`. |\n| [options.text.spacing] | <code>number</code> | <code>0</code> | text line height in points. Will use the font line height if none is specified. |\n| [options.text.wrap] | <code>string</code> | <code>&quot;&#x27;word&#x27;&quot;</code> | word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'. |\n| [options.join] | <code>Object</code> |  | describes how an array of input images should be joined. |\n| [options.join.across] | <code>number</code> | <code>1</code> | number of images to join horizontally. |\n| [options.join.animated] | <code>boolean</code> | <code>false</code> | set this to `true` to join the images as an animated image. |\n| [options.join.shim] | <code>number</code> | <code>0</code> | number of pixels to insert between joined images. |\n| [options.join.background] | <code>string</code> \\| <code>Object</code> |  | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |\n| [options.join.halign] | <code>string</code> | <code>&quot;&#x27;left&#x27;&quot;</code> | horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`). |\n| [options.join.valign] | <code>string</code> | <code>&quot;&#x27;top&#x27;&quot;</code> | vertical alignment style for images joined vertically (`'top'`, `'centre'`, `'center'`, `'bottom'`). |\n| [options.tiff] | <code>Object</code> |  | Describes TIFF specific options. |\n| [options.tiff.subifd] | <code>number</code> | <code>-1</code> | Sub Image File Directory to extract for OME-TIFF, defaults to main image. |\n| [options.svg] | <code>Object</code> |  | Describes SVG specific options. |\n| [options.svg.stylesheet] | <code>string</code> |  | Custom CSS for SVG input, applied with a User Origin during the CSS cascade. |\n| [options.svg.highBitdepth] | <code>boolean</code> | <code>false</code> | Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA. |\n| [options.pdf] | <code>Object</code> |  | Describes PDF specific options. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick. |\n| [options.pdf.background] | <code>string</code> \\| <code>Object</code> |  | Background colour to use when PDF is partially transparent. Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |\n| [options.openSlide] | <code>Object</code> |  | Describes OpenSlide specific options. Requires the use of a globally-installed libvips compiled with support for OpenSlide. |\n| [options.openSlide.level] | <code>number</code> | <code>0</code> | Level to extract from a multi-level input, zero based. |\n| [options.jp2] | <code>Object</code> |  | Describes JPEG 2000 specific options. Requires the use of a globally-installed libvips compiled with support for OpenJPEG. |\n| [options.jp2.oneshot] | <code>boolean</code> | <code>false</code> | Set to `true` to decode tiled JPEG 2000 images in a single operation, improving compatibility. |\n\n**Example**  \n```js\nsharp('input.jpg')\n  .resize(300, 200)\n  .toFile('output.jpg', function(err) {\n    // output.jpg is a 300 pixels wide and 200 pixels high image\n    // containing a scaled and cropped version of input.jpg\n  });\n```\n**Example**  \n```js\n// Read image data from remote URL,\n// resize to 300 pixels wide,\n// emit an 'info' event with calculated dimensions\n// and finally write image data to writableStream\nconst { body } = fetch('https://...');\nconst readableStream = Readable.fromWeb(body);\nconst transformer = sharp()\n  .resize(300)\n  .on('info', ({ height }) => {\n    console.log(`Image height is ${height}`);\n  });\nreadableStream.pipe(transformer).pipe(writableStream);\n```\n**Example**  \n```js\n// Create a blank 300x200 PNG image of semi-translucent red pixels\nsharp({\n  create: {\n    width: 300,\n    height: 200,\n    channels: 4,\n    background: { r: 255, g: 0, b: 0, alpha: 0.5 }\n  }\n})\n.png()\n.toBuffer()\n.then( ... );\n```\n**Example**  \n```js\n// Convert an animated GIF to an animated WebP\nawait sharp('in.gif', { animated: true }).toFile('out.webp');\n```\n**Example**  \n```js\n// Read a raw array of pixels and save it to a png\nconst input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray\nconst image = sharp(input, {\n  // because the input does not contain its dimensions or how many channels it has\n  // we need to specify it in the constructor options\n  raw: {\n    width: 2,\n    height: 1,\n    channels: 3\n  }\n});\nawait image.toFile('my-two-pixels.png');\n```\n**Example**  \n```js\n// Generate RGB Gaussian noise\nawait sharp({\n  create: {\n    width: 300,\n    height: 200,\n    channels: 3,\n    noise: {\n      type: 'gaussian',\n      mean: 128,\n      sigma: 30\n    }\n }\n}).toFile('noise.png');\n```\n**Example**  \n```js\n// Generate an image from text\nawait sharp({\n  text: {\n    text: 'Hello, world!',\n    width: 400, // max width\n    height: 300 // max height\n  }\n}).toFile('text_bw.png');\n```\n**Example**  \n```js\n// Generate an rgba image from text using pango markup and font\nawait sharp({\n  text: {\n    text: '<span foreground=\"red\">Red!</span><span background=\"cyan\">blue</span>',\n    font: 'sans',\n    rgba: true,\n    dpi: 300\n  }\n}).toFile('text_rgba.png');\n```\n**Example**  \n```js\n// Join four input images as a 2x2 grid with a 4 pixel gutter\nconst data = await sharp(\n [image1, image2, image3, image4],\n { join: { across: 2, shim: 4 } }\n).toBuffer();\n```\n**Example**  \n```js\n// Generate a two-frame animated image from emoji\nconst images = ['😀', '😛'].map(text => ({\n  text: { text, width: 64, height: 64, channels: 4, rgba: true }\n}));\nawait sharp(images, { join: { animated: true } }).toFile('out.gif');\n```\n\n\n## clone\n> clone() ⇒ [<code>Sharp</code>](#Sharp)\n\nTake a \"snapshot\" of the Sharp instance, returning a new instance.\nCloned instances inherit the input of their parent instance.\nThis allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.\n\n\n**Example**  \n```js\nconst pipeline = sharp().rotate();\npipeline.clone().resize(800, 600).pipe(firstWritableStream);\npipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream);\nreadableStream.pipe(pipeline);\n// firstWritableStream receives auto-rotated, resized readableStream\n// secondWritableStream receives auto-rotated, extracted region of readableStream\n```\n**Example**  \n```js\n// Create a pipeline that will download an image, resize it and format it to different files\n// Using Promises to know when the pipeline is complete\nconst fs = require(\"fs\");\nconst got = require(\"got\");\nconst sharpStream = sharp({ failOn: 'none' });\n\nconst promises = [];\n\npromises.push(\n  sharpStream\n    .clone()\n    .jpeg({ quality: 100 })\n    .toFile(\"originalFile.jpg\")\n);\n\npromises.push(\n  sharpStream\n    .clone()\n    .resize({ width: 500 })\n    .jpeg({ quality: 80 })\n    .toFile(\"optimized-500.jpg\")\n);\n\npromises.push(\n  sharpStream\n    .clone()\n    .resize({ width: 500 })\n    .webp({ quality: 80 })\n    .toFile(\"optimized-500.webp\")\n);\n\n// https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md\ngot.stream(\"https://www.example.com/some-file.jpg\").pipe(sharpStream);\n\nPromise.all(promises)\n  .then(res => { console.log(\"Done!\", res); })\n  .catch(err => {\n    console.error(\"Error processing files, let's clean it up\", err);\n    try {\n      fs.unlinkSync(\"originalFile.jpg\");\n      fs.unlinkSync(\"optimized-500.jpg\");\n      fs.unlinkSync(\"optimized-500.webp\");\n    } catch (e) {}\n  });\n```"
  },
  {
    "path": "docs/src/content/docs/api-input.md",
    "content": "---\n# This file was auto-generated from JSDoc in lib/input.js\ntitle: Input metadata\n---\n\n## metadata\n> metadata([callback]) ⇒ <code>Promise.&lt;Object&gt;</code> \\| <code>Sharp</code>\n\nFast access to (uncached) image metadata without decoding any compressed pixel data.\n\nThis is read from the header of the input image.\nIt does not take into consideration any operations to be applied to the output image,\nsuch as resize or rotate.\n\nDimensions in the response will respect the `page` and `pages` properties of the\n[constructor parameters](/api-constructor/).\n\nA `Promise` is returned when `callback` is not provided.\n\n- `format`: Name of decoder used to parse image e.g. `jpeg`, `png`, `webp`, `gif`, `svg`, `heif`, `tiff`\n- `size`: Total size of image in bytes, for Stream and Buffer input only\n- `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below)\n- `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below)\n- `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/enum.Interpretation.html)\n- `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK\n- `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://www.libvips.org/API/current/enum.BandFormat.html)\n- `density`: Number of pixels per inch (DPI), if present\n- `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK\n- `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan\n- `isPalette`: Boolean indicating whether the image is palette-based (GIF, PNG).\n- `bitsPerSample`: Number of bits per sample for each channel (GIF, PNG, HEIF).\n- `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP\n- `pageHeight`: Number of pixels high each page in a multi-page image will be.\n- `loop`: Number of times to loop an animated image, zero refers to a continuous loop.\n- `delay`: Delay in ms between each page in an animated image, provided as an array of integers.\n- `pagePrimary`: Number of the primary page in a HEIF image\n- `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide\n- `subifds`: Number of Sub Image File Directories in an OME-TIFF image\n- `background`: Default background colour, if present, for PNG (bKGD) and GIF images\n- `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)\n- `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present\n- `hasProfile`: Boolean indicating the presence of an embedded ICC profile\n- `hasAlpha`: Boolean indicating the presence of an alpha transparency channel\n- `orientation`: Number value of the EXIF Orientation header, if present\n- `exif`: Buffer containing raw EXIF data, if present\n- `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present\n- `iptc`: Buffer containing raw IPTC data, if present\n- `xmp`: Buffer containing raw XMP data, if present\n- `xmpAsString`: String containing XMP data, if valid UTF-8.\n- `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present\n- `formatMagick`: String containing format for images loaded via *magick\n- `comments`: Array of keyword/text pairs representing PNG text blocks, if present.\n\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| [callback] | <code>function</code> | called with the arguments `(err, metadata)` |\n\n**Example**  \n```js\nconst metadata = await sharp(input).metadata();\n```\n**Example**  \n```js\nconst image = sharp(inputJpg);\nimage\n  .metadata()\n  .then(function(metadata) {\n    return image\n      .resize(Math.round(metadata.width / 2))\n      .webp()\n      .toBuffer();\n  })\n  .then(function(data) {\n    // data contains a WebP image half the width and height of the original JPEG\n  });\n```\n**Example**  \n```js\n// Get dimensions taking EXIF Orientation into account.\nconst { autoOrient } = await sharp(input).metadata();\nconst { width, height } = autoOrient;\n```\n\n\n## stats\n> stats([callback]) ⇒ <code>Promise.&lt;Object&gt;</code>\n\nAccess to pixel-derived image statistics for every channel in the image.\nA `Promise` is returned when `callback` is not provided.\n\n- `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains\n    - `min` (minimum value in the channel)\n    - `max` (maximum value in the channel)\n    - `sum` (sum of all values in a channel)\n    - `squaresSum` (sum of squared values in a channel)\n    - `mean` (mean of the values in a channel)\n    - `stdev` (standard deviation for the values in a channel)\n    - `minX` (x-coordinate of one of the pixel where the minimum lies)\n    - `minY` (y-coordinate of one of the pixel where the minimum lies)\n    - `maxX` (x-coordinate of one of the pixel where the maximum lies)\n    - `maxY` (y-coordinate of one of the pixel where the maximum lies)\n- `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.\n- `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.\n- `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any.\n- `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram.\n\n**Note**: Statistics are derived from the original input image. Any operations performed on the image must first be\nwritten to a buffer in order to run `stats` on the result (see third example).\n\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| [callback] | <code>function</code> | called with the arguments `(err, stats)` |\n\n**Example**  \n```js\nconst image = sharp(inputJpg);\nimage\n  .stats()\n  .then(function(stats) {\n     // stats contains the channel-wise statistics array and the isOpaque value\n  });\n```\n**Example**  \n```js\nconst { entropy, sharpness, dominant } = await sharp(input).stats();\nconst { r, g, b } = dominant;\n```\n**Example**  \n```js\nconst image = sharp(input);\n// store intermediate result\nconst part = await image.extract(region).toBuffer();\n// create new instance to obtain statistics of extracted region\nconst stats = await sharp(part).stats();\n```"
  },
  {
    "path": "docs/src/content/docs/api-operation.md",
    "content": "---\n# This file was auto-generated from JSDoc in lib/operation.js\ntitle: Image operations\n---\n\n## rotate\n> rotate([angle], [options]) ⇒ <code>Sharp</code>\n\nRotate the output image.\n\nThe provided angle is converted to a valid positive degree rotation.\nFor example, `-450` will produce a 270 degree rotation.\n\nWhen rotating by an angle other than a multiple of 90,\nthe background colour can be provided with the `background` option.\n\nFor backwards compatibility, if no angle is provided, `.autoOrient()` will be called.\n\nOnly one rotation can occur per pipeline (aside from an initial call without\narguments to orient via EXIF data). Previous calls to `rotate` in the same\npipeline will be ignored.\n\nMulti-page images can only be rotated by 180 degrees.\n\nMethod order is important when rotating, resizing and/or extracting regions,\nfor example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [angle] | <code>number</code> | <code>auto</code> | angle of rotation. |\n| [options] | <code>Object</code> |  | if present, is an Object with optional attributes. |\n| [options.background] | <code>string</code> \\| <code>Object</code> | <code>&quot;\\&quot;#000000\\&quot;&quot;</code> | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |\n\n**Example**  \n```js\nconst rotateThenResize = await sharp(input)\n  .rotate(90)\n  .resize({ width: 16, height: 8, fit: 'fill' })\n  .toBuffer();\nconst resizeThenRotate = await sharp(input)\n  .resize({ width: 16, height: 8, fit: 'fill' })\n  .rotate(90)\n  .toBuffer();\n```\n\n\n## autoOrient\n> autoOrient() ⇒ <code>Sharp</code>\n\nAuto-orient based on the EXIF `Orientation` tag, then remove the tag.\nMirroring is supported and may infer the use of a flip operation.\n\nPrevious or subsequent use of `rotate(angle)` and either `flip()` or `flop()`\nwill logically occur after auto-orientation, regardless of call order.\n\n\n**Example**  \n```js\nconst output = await sharp(input).autoOrient().toBuffer();\n```\n**Example**  \n```js\nconst pipeline = sharp()\n  .autoOrient()\n  .resize(null, 200)\n  .toBuffer(function (err, outputBuffer, info) {\n    // outputBuffer contains 200px high JPEG image data,\n    // auto-oriented using EXIF Orientation tag\n    // info.width and info.height contain the dimensions of the resized image\n  });\nreadableStream.pipe(pipeline);\n```\n\n\n## flip\n> flip([flip]) ⇒ <code>Sharp</code>\n\nMirror the image vertically (up-down) about the x-axis.\nThis always occurs before rotation, if any.\n\nThis operation does not work correctly with multi-page images.\n\n\n\n| Param | Type | Default |\n| --- | --- | --- |\n| [flip] | <code>Boolean</code> | <code>true</code> | \n\n**Example**  \n```js\nconst output = await sharp(input).flip().toBuffer();\n```\n\n\n## flop\n> flop([flop]) ⇒ <code>Sharp</code>\n\nMirror the image horizontally (left-right) about the y-axis.\nThis always occurs before rotation, if any.\n\n\n\n| Param | Type | Default |\n| --- | --- | --- |\n| [flop] | <code>Boolean</code> | <code>true</code> | \n\n**Example**  \n```js\nconst output = await sharp(input).flop().toBuffer();\n```\n\n\n## affine\n> affine(matrix, [options]) ⇒ <code>Sharp</code>\n\nPerform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.\n\nYou must provide an array of length 4 or a 2x2 affine transformation matrix.\nBy default, new pixels are filled with a black background. You can provide a background colour with the `background` option.\nA particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.\n\nIn the case of a 2x2 matrix, the transform is:\n- X = `matrix[0, 0]` \\* (x + `idx`) + `matrix[0, 1]` \\* (y + `idy`) + `odx`\n- Y = `matrix[1, 0]` \\* (x + `idx`) + `matrix[1, 1]` \\* (y + `idy`) + `ody`\n\nwhere:\n- x and y are the coordinates in input image.\n- X and Y are the coordinates in output image.\n- (0,0) is the upper left corner.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n**Since**: 0.27.0  \n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| matrix | <code>Array.&lt;Array.&lt;number&gt;&gt;</code> \\| <code>Array.&lt;number&gt;</code> |  | affine transformation matrix |\n| [options] | <code>Object</code> |  | if present, is an Object with optional attributes. |\n| [options.background] | <code>String</code> \\| <code>Object</code> | <code>&quot;#000000&quot;</code> | parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. |\n| [options.idx] | <code>Number</code> | <code>0</code> | input horizontal offset |\n| [options.idy] | <code>Number</code> | <code>0</code> | input vertical offset |\n| [options.odx] | <code>Number</code> | <code>0</code> | output horizontal offset |\n| [options.ody] | <code>Number</code> | <code>0</code> | output vertical offset |\n| [options.interpolator] | <code>String</code> | <code>sharp.interpolators.bicubic</code> | interpolator |\n\n**Example**  \n```js\nconst pipeline = sharp()\n  .affine([[1, 0.3], [0.1, 0.7]], {\n     background: 'white',\n     interpolator: sharp.interpolators.nohalo\n  })\n  .toBuffer((err, outputBuffer, info) => {\n     // outputBuffer contains the transformed image\n     // info.width and info.height contain the new dimensions\n  });\n\ninputStream\n  .pipe(pipeline);\n```\n\n\n## sharpen\n> sharpen([options], [flat], [jagged]) ⇒ <code>Sharp</code>\n\nSharpen the image.\n\nWhen used without parameters, performs a fast, mild sharpen of the output image.\n\nWhen a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.\nFine-grained control over the level of sharpening in \"flat\" (m1) and \"jagged\" (m2) areas is available.\n\nSee [libvips sharpen](https://www.libvips.org/API/current/method.Image.sharpen.html) operation.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> \\| <code>number</code> |  | if present, is an Object with attributes |\n| [options.sigma] | <code>number</code> |  | the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10 |\n| [options.m1] | <code>number</code> | <code>1.0</code> | the level of sharpening to apply to \"flat\" areas, between 0 and 1000000 |\n| [options.m2] | <code>number</code> | <code>2.0</code> | the level of sharpening to apply to \"jagged\" areas, between 0 and 1000000 |\n| [options.x1] | <code>number</code> | <code>2.0</code> | threshold between \"flat\" and \"jagged\", between 0 and 1000000 |\n| [options.y2] | <code>number</code> | <code>10.0</code> | maximum amount of brightening, between 0 and 1000000 |\n| [options.y3] | <code>number</code> | <code>20.0</code> | maximum amount of darkening, between 0 and 1000000 |\n| [flat] | <code>number</code> |  | (deprecated) see `options.m1`. |\n| [jagged] | <code>number</code> |  | (deprecated) see `options.m2`. |\n\n**Example**  \n```js\nconst data = await sharp(input).sharpen().toBuffer();\n```\n**Example**  \n```js\nconst data = await sharp(input).sharpen({ sigma: 2 }).toBuffer();\n```\n**Example**  \n```js\nconst data = await sharp(input)\n  .sharpen({\n    sigma: 2,\n    m1: 0,\n    m2: 3,\n    x1: 3,\n    y2: 15,\n    y3: 15,\n  })\n  .toBuffer();\n```\n\n\n## median\n> median([size]) ⇒ <code>Sharp</code>\n\nApply median filter.\nWhen used without parameters the default window is 3x3.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [size] | <code>number</code> | <code>3</code> | square mask size: size x size |\n\n**Example**  \n```js\nconst output = await sharp(input).median().toBuffer();\n```\n**Example**  \n```js\nconst output = await sharp(input).median(5).toBuffer();\n```\n\n\n## blur\n> blur([options]) ⇒ <code>Sharp</code>\n\nBlur the image.\n\nWhen used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter).\n\nWhen a `sigma` is provided, performs a slower, more accurate Gaussian blur.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> \\| <code>number</code> \\| <code>Boolean</code> |  |  |\n| [options.sigma] | <code>number</code> |  | a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. |\n| [options.precision] | <code>string</code> | <code>&quot;&#x27;integer&#x27;&quot;</code> | How accurate the operation should be, one of: integer, float, approximate. |\n| [options.minAmplitude] | <code>number</code> | <code>0.2</code> | A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. |\n\n**Example**  \n```js\nconst boxBlurred = await sharp(input)\n  .blur()\n  .toBuffer();\n```\n**Example**  \n```js\nconst gaussianBlurred = await sharp(input)\n  .blur(5)\n  .toBuffer();\n```\n\n\n## dilate\n> dilate([width]) ⇒ <code>Sharp</code>\n\nExpand foreground objects using the dilate morphological operator.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [width] | <code>Number</code> | <code>1</code> | dilation width in pixels. |\n\n**Example**  \n```js\nconst output = await sharp(input)\n  .dilate()\n  .toBuffer();\n```\n\n\n## erode\n> erode([width]) ⇒ <code>Sharp</code>\n\nShrink foreground objects using the erode morphological operator.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [width] | <code>Number</code> | <code>1</code> | erosion width in pixels. |\n\n**Example**  \n```js\nconst output = await sharp(input)\n  .erode()\n  .toBuffer();\n```\n\n\n## flatten\n> flatten([options]) ⇒ <code>Sharp</code>\n\nMerge alpha transparency channel, if any, with a background, then remove the alpha channel.\n\nSee also [removeAlpha](/api-channel#removealpha).\n\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  |  |\n| [options.background] | <code>string</code> \\| <code>Object</code> | <code>&quot;{r: 0, g: 0, b: 0}&quot;</code> | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black. |\n\n**Example**  \n```js\nawait sharp(rgbaInput)\n  .flatten({ background: '#F0A703' })\n  .toBuffer();\n```\n\n\n## unflatten\n> unflatten()\n\nEnsure the image has an alpha channel\nwith all white pixel values made fully transparent.\n\nExisting alpha channel values for non-white pixels remain unchanged.\n\nThis feature is experimental and the API may change.\n\n\n**Since**: 0.32.1  \n**Example**  \n```js\nawait sharp(rgbInput)\n  .unflatten()\n  .toBuffer();\n```\n**Example**  \n```js\nawait sharp(rgbInput)\n  .threshold(128, { grayscale: false }) // converter bright pixels to white\n  .unflatten()\n  .toBuffer();\n```\n\n\n## gamma\n> gamma([gamma], [gammaOut]) ⇒ <code>Sharp</code>\n\nApply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma`\nthen increasing the encoding (brighten) post-resize at a factor of `gamma`.\nThis can improve the perceived brightness of a resized image in non-linear colour spaces.\nJPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation\nwhen applying a gamma correction.\n\nSupply a second argument to use a different output gamma value, otherwise the first value is used in both cases.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [gamma] | <code>number</code> | <code>2.2</code> | value between 1.0 and 3.0. |\n| [gammaOut] | <code>number</code> |  | value between 1.0 and 3.0. (optional, defaults to same as `gamma`) |\n\n\n\n## negate\n> negate([options]) ⇒ <code>Sharp</code>\n\nProduce the \"negative\" of the image.\n\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  |  |\n| [options.alpha] | <code>Boolean</code> | <code>true</code> | Whether or not to negate any alpha channel |\n\n**Example**  \n```js\nconst output = await sharp(input)\n  .negate()\n  .toBuffer();\n```\n**Example**  \n```js\nconst output = await sharp(input)\n  .negate({ alpha: false })\n  .toBuffer();\n```\n\n\n## normalise\n> normalise([options]) ⇒ <code>Sharp</code>\n\nEnhance output image contrast by stretching its luminance to cover a full dynamic range.\n\nUses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes.\n\nLuminance values below the `lower` percentile will be underexposed by clipping to zero.\nLuminance values above the `upper` percentile will be overexposed by clipping to the max pixel value.\n\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  |  |\n| [options.lower] | <code>number</code> | <code>1</code> | Percentile below which luminance values will be underexposed. |\n| [options.upper] | <code>number</code> | <code>99</code> | Percentile above which luminance values will be overexposed. |\n\n**Example**  \n```js\nconst output = await sharp(input)\n  .normalise()\n  .toBuffer();\n```\n**Example**  \n```js\nconst output = await sharp(input)\n  .normalise({ lower: 0, upper: 100 })\n  .toBuffer();\n```\n\n\n## normalize\n> normalize([options]) ⇒ <code>Sharp</code>\n\nAlternative spelling of normalise.\n\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  |  |\n| [options.lower] | <code>number</code> | <code>1</code> | Percentile below which luminance values will be underexposed. |\n| [options.upper] | <code>number</code> | <code>99</code> | Percentile above which luminance values will be overexposed. |\n\n**Example**  \n```js\nconst output = await sharp(input)\n  .normalize()\n  .toBuffer();\n```\n\n\n## clahe\n> clahe(options) ⇒ <code>Sharp</code>\n\nPerform contrast limiting adaptive histogram equalization\n[CLAHE](https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE).\n\nThis will, in general, enhance the clarity of the image by bringing out darker details.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n**Since**: 0.28.3  \n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| options | <code>Object</code> |  |  |\n| options.width | <code>number</code> |  | Integral width of the search window, in pixels. |\n| options.height | <code>number</code> |  | Integral height of the search window, in pixels. |\n| [options.maxSlope] | <code>number</code> | <code>3</code> | Integral level of brightening, between 0 and 100, where 0 disables contrast limiting. |\n\n**Example**  \n```js\nconst output = await sharp(input)\n  .clahe({\n    width: 3,\n    height: 3,\n  })\n  .toBuffer();\n```\n\n\n## convolve\n> convolve(kernel) ⇒ <code>Sharp</code>\n\nConvolve the image with the specified kernel.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| kernel | <code>Object</code> |  |  |\n| kernel.width | <code>number</code> |  | width of the kernel in pixels. |\n| kernel.height | <code>number</code> |  | height of the kernel in pixels. |\n| kernel.kernel | <code>Array.&lt;number&gt;</code> |  | Array of length `width*height` containing the kernel values. |\n| [kernel.scale] | <code>number</code> | <code>sum</code> | the scale of the kernel in pixels. |\n| [kernel.offset] | <code>number</code> | <code>0</code> | the offset of the kernel in pixels. |\n\n**Example**  \n```js\nsharp(input)\n  .convolve({\n    width: 3,\n    height: 3,\n    kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1]\n  })\n  .raw()\n  .toBuffer(function(err, data, info) {\n    // data contains the raw pixel data representing the convolution\n    // of the input image with the horizontal Sobel operator\n  });\n```\n\n\n## threshold\n> threshold([threshold], [options]) ⇒ <code>Sharp</code>\n\nAny pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [threshold] | <code>number</code> | <code>128</code> | a value in the range 0-255 representing the level at which the threshold will be applied. |\n| [options] | <code>Object</code> |  |  |\n| [options.greyscale] | <code>Boolean</code> | <code>true</code> | convert to single channel greyscale. |\n| [options.grayscale] | <code>Boolean</code> | <code>true</code> | alternative spelling for greyscale. |\n\n\n\n## boolean\n> boolean(operand, operator, [options]) ⇒ <code>Sharp</code>\n\nPerform a bitwise boolean operation with operand image.\n\nThis operation creates an output image where each pixel is the result of\nthe selected bitwise boolean `operation` between the corresponding pixels of the input images.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| operand | <code>Buffer</code> \\| <code>string</code> | Buffer containing image data or string containing the path to an image file. |\n| operator | <code>string</code> | one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. |\n| [options] | <code>Object</code> |  |\n| [options.raw] | <code>Object</code> | describes operand when using raw pixel data. |\n| [options.raw.width] | <code>number</code> |  |\n| [options.raw.height] | <code>number</code> |  |\n| [options.raw.channels] | <code>number</code> |  |\n\n\n\n## linear\n> linear([a], [b]) ⇒ <code>Sharp</code>\n\nApply the linear formula `a` * input + `b` to the image to adjust image levels.\n\nWhen a single number is provided, it will be used for all image channels.\nWhen an array of numbers is provided, the array length must match the number of channels.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [a] | <code>number</code> \\| <code>Array.&lt;number&gt;</code> | <code>[]</code> | multiplier |\n| [b] | <code>number</code> \\| <code>Array.&lt;number&gt;</code> | <code>[]</code> | offset |\n\n**Example**  \n```js\nawait sharp(input)\n  .linear(0.5, 2)\n  .toBuffer();\n```\n**Example**  \n```js\nawait sharp(rgbInput)\n  .linear(\n    [0.25, 0.5, 0.75],\n    [150, 100, 50]\n  )\n  .toBuffer();\n```\n\n\n## recomb\n> recomb(inputMatrix) ⇒ <code>Sharp</code>\n\nRecombine the image with the specified matrix.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n**Since**: 0.21.1  \n\n| Param | Type | Description |\n| --- | --- | --- |\n| inputMatrix | <code>Array.&lt;Array.&lt;number&gt;&gt;</code> | 3x3 or 4x4 Recombination matrix |\n\n**Example**  \n```js\nsharp(input)\n  .recomb([\n   [0.3588, 0.7044, 0.1368],\n   [0.2990, 0.5870, 0.1140],\n   [0.2392, 0.4696, 0.0912],\n  ])\n  .raw()\n  .toBuffer(function(err, data, info) {\n    // data contains the raw pixel data after applying the matrix\n    // With this example input, a sepia filter has been applied\n  });\n```\n\n\n## modulate\n> modulate([options]) ⇒ <code>Sharp</code>\n\nTransforms the image using brightness, saturation, hue rotation, and lightness.\nBrightness and lightness both operate on luminance, with the difference being that\nbrightness is multiplicative whereas lightness is additive.\n\n\n**Since**: 0.22.1  \n\n| Param | Type | Description |\n| --- | --- | --- |\n| [options] | <code>Object</code> |  |\n| [options.brightness] | <code>number</code> | Brightness multiplier |\n| [options.saturation] | <code>number</code> | Saturation multiplier |\n| [options.hue] | <code>number</code> | Degrees for hue rotation |\n| [options.lightness] | <code>number</code> | Lightness addend |\n\n**Example**  \n```js\n// increase brightness by a factor of 2\nconst output = await sharp(input)\n  .modulate({\n    brightness: 2\n  })\n  .toBuffer();\n```\n**Example**  \n```js\n// hue-rotate by 180 degrees\nconst output = await sharp(input)\n  .modulate({\n    hue: 180\n  })\n  .toBuffer();\n```\n**Example**  \n```js\n// increase lightness by +50\nconst output = await sharp(input)\n  .modulate({\n    lightness: 50\n  })\n  .toBuffer();\n```\n**Example**  \n```js\n// decrease brightness and saturation while also hue-rotating by 90 degrees\nconst output = await sharp(input)\n  .modulate({\n    brightness: 0.5,\n    saturation: 0.5,\n    hue: 90,\n  })\n  .toBuffer();\n```"
  },
  {
    "path": "docs/src/content/docs/api-output.md",
    "content": "---\n# This file was auto-generated from JSDoc in lib/output.js\ntitle: Output options\n---\n\n## toFile\n> toFile(fileOut, [callback]) ⇒ <code>Promise.&lt;Object&gt;</code>\n\nWrite output image data to a file.\n\nIf an explicit output format is not selected, it will be inferred from the extension,\nwith JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported.\nNote that raw pixel data is only supported for buffer output.\n\nBy default all metadata will be removed, which includes EXIF-based orientation.\nSee [withMetadata](#withmetadata) for control over this.\n\nThe caller is responsible for ensuring directory structures and permissions exist.\n\nA `Promise` is returned when `callback` is not provided.\n\n\n**Returns**: <code>Promise.&lt;Object&gt;</code> - - when no callback is provided  \n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| fileOut | <code>string</code> | the path to write the image data to. |\n| [callback] | <code>function</code> | called on completion with two arguments `(err, info)`. `info` contains the output image `format`, `size` (bytes), `width`, `height`, `channels` and `premultiplied` (indicating if premultiplication was used). When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region. Animated output will also contain `pageHeight` and `pages`. May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. |\n\n**Example**  \n```js\nsharp(input)\n  .toFile('output.png', (err, info) => { ... });\n```\n**Example**  \n```js\nsharp(input)\n  .toFile('output.png')\n  .then(info => { ... })\n  .catch(err => { ... });\n```\n\n\n## toBuffer\n> toBuffer([options], [callback]) ⇒ <code>Promise.&lt;Buffer&gt;</code>\n\nWrite output to a Buffer.\nJPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.\n\nUse [toFormat](#toformat) or one of the format-specific functions such as [jpeg](#jpeg), [png](#png) etc. to set the output format.\n\nIf no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.\n\nBy default all metadata will be removed, which includes EXIF-based orientation.\nSee [withMetadata](#withmetadata) for control over this.\n\n`callback`, if present, gets three arguments `(err, data, info)` where:\n- `err` is an error, if any.\n- `data` is the output image data.\n- `info` contains the output image `format`, `size` (bytes), `width`, `height`,\n`channels` and `premultiplied` (indicating if premultiplication was used).\nWhen using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.\nAnimated output will also contain `pageHeight` and `pages`.\nMay also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.\n\nA `Promise` is returned when `callback` is not provided.\n\n\n**Returns**: <code>Promise.&lt;Buffer&gt;</code> - - when no callback is provided  \n\n| Param | Type | Description |\n| --- | --- | --- |\n| [options] | <code>Object</code> |  |\n| [options.resolveWithObject] | <code>boolean</code> | Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`. |\n| [callback] | <code>function</code> |  |\n\n**Example**  \n```js\nsharp(input)\n  .toBuffer((err, data, info) => { ... });\n```\n**Example**  \n```js\nsharp(input)\n  .toBuffer()\n  .then(data => { ... })\n  .catch(err => { ... });\n```\n**Example**  \n```js\nsharp(input)\n  .png()\n  .toBuffer({ resolveWithObject: true })\n  .then(({ data, info }) => { ... })\n  .catch(err => { ... });\n```\n**Example**  \n```js\nconst { data, info } = await sharp('my-image.jpg')\n  // output the raw pixels\n  .raw()\n  .toBuffer({ resolveWithObject: true });\n\n// create a more type safe way to work with the raw pixel data\n// this will not copy the data, instead it will change `data`s underlying ArrayBuffer\n// so `data` and `pixelArray` point to the same memory location\nconst pixelArray = new Uint8ClampedArray(data.buffer);\n\n// When you are done changing the pixelArray, sharp takes the `pixelArray` as an input\nconst { width, height, channels } = info;\nawait sharp(pixelArray, { raw: { width, height, channels } })\n  .toFile('my-changed-image.jpg');\n```\n\n\n## keepExif\n> keepExif() ⇒ <code>Sharp</code>\n\nKeep all EXIF metadata from the input image in the output image.\n\nEXIF metadata is unsupported for TIFF output.\n\n\n**Since**: 0.33.0  \n**Example**  \n```js\nconst outputWithExif = await sharp(inputWithExif)\n  .keepExif()\n  .toBuffer();\n```\n\n\n## withExif\n> withExif(exif) ⇒ <code>Sharp</code>\n\nSet EXIF metadata in the output image, ignoring any EXIF in the input image.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n**Since**: 0.33.0  \n\n| Param | Type | Description |\n| --- | --- | --- |\n| exif | <code>Object.&lt;string, Object.&lt;string, string&gt;&gt;</code> | Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. |\n\n**Example**  \n```js\nconst dataWithExif = await sharp(input)\n  .withExif({\n    IFD0: {\n      Copyright: 'The National Gallery'\n    },\n    IFD3: {\n      GPSLatitudeRef: 'N',\n      GPSLatitude: '51/1 30/1 3230/100',\n      GPSLongitudeRef: 'W',\n      GPSLongitude: '0/1 7/1 4366/100'\n    }\n  })\n  .toBuffer();\n```\n\n\n## withExifMerge\n> withExifMerge(exif) ⇒ <code>Sharp</code>\n\nUpdate EXIF metadata from the input image in the output image.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n**Since**: 0.33.0  \n\n| Param | Type | Description |\n| --- | --- | --- |\n| exif | <code>Object.&lt;string, Object.&lt;string, string&gt;&gt;</code> | Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. |\n\n**Example**  \n```js\nconst dataWithMergedExif = await sharp(inputWithExif)\n  .withExifMerge({\n    IFD0: {\n      Copyright: 'The National Gallery'\n    }\n  })\n  .toBuffer();\n```\n\n\n## keepIccProfile\n> keepIccProfile() ⇒ <code>Sharp</code>\n\nKeep ICC profile from the input image in the output image.\n\nWhen input and output colour spaces differ, use with [toColourspace](/api-colour/#tocolourspace) and optionally [pipelineColourspace](/api-colour/#pipelinecolourspace).\n\n\n**Since**: 0.33.0  \n**Example**  \n```js\nconst outputWithIccProfile = await sharp(inputWithIccProfile)\n  .keepIccProfile()\n  .toBuffer();\n```\n**Example**  \n```js\nconst cmykOutputWithIccProfile = await sharp(cmykInputWithIccProfile)\n  .pipelineColourspace('cmyk')\n  .toColourspace('cmyk')\n  .keepIccProfile()\n  .toBuffer();\n```\n\n\n## withIccProfile\n> withIccProfile(icc, [options]) ⇒ <code>Sharp</code>\n\nTransform using an ICC profile and attach to the output image.\n\nThis can either be an absolute filesystem path or\nbuilt-in profile name (`srgb`, `p3`, `cmyk`).\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n**Since**: 0.33.0  \n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| icc | <code>string</code> |  | Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk). |\n| [options] | <code>Object</code> |  |  |\n| [options.attach] | <code>number</code> | <code>true</code> | Should the ICC profile be included in the output image metadata? |\n\n**Example**  \n```js\nconst outputWithP3 = await sharp(input)\n  .withIccProfile('p3')\n  .toBuffer();\n```\n\n\n## keepXmp\n> keepXmp() ⇒ <code>Sharp</code>\n\nKeep XMP metadata from the input image in the output image.\n\n\n**Since**: 0.34.3  \n**Example**  \n```js\nconst outputWithXmp = await sharp(inputWithXmp)\n  .keepXmp()\n  .toBuffer();\n```\n\n\n## withXmp\n> withXmp(xmp) ⇒ <code>Sharp</code>\n\nSet XMP metadata in the output image.\n\nSupported by PNG, JPEG, WebP, and TIFF output.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n**Since**: 0.34.3  \n\n| Param | Type | Description |\n| --- | --- | --- |\n| xmp | <code>string</code> | String containing XMP metadata to be embedded in the output image. |\n\n**Example**  \n```js\nconst xmpString = `\n  <?xml version=\"1.0\"?>\n  <x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n    <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n      <rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n        <dc:creator><rdf:Seq><rdf:li>John Doe</rdf:li></rdf:Seq></dc:creator>\n      </rdf:Description>\n    </rdf:RDF>\n  </x:xmpmeta>`;\n\nconst data = await sharp(input)\n  .withXmp(xmpString)\n  .toBuffer();\n```\n\n\n## keepMetadata\n> keepMetadata() ⇒ <code>Sharp</code>\n\nKeep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.\n\nThe default behaviour, when `keepMetadata` is not used, is to convert to the device-independent\nsRGB colour space and strip all metadata, including the removal of any ICC profile.\n\n\n**Since**: 0.33.0  \n**Example**  \n```js\nconst outputWithMetadata = await sharp(inputWithMetadata)\n  .keepMetadata()\n  .toBuffer();\n```\n\n\n## withMetadata\n> withMetadata([options]) ⇒ <code>Sharp</code>\n\nKeep most metadata (EXIF, XMP, IPTC) from the input image in the output image.\n\nThis will also convert to and add a web-friendly sRGB ICC profile if appropriate.\n\nAllows orientation and density to be set or updated.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| [options] | <code>Object</code> |  |\n| [options.orientation] | <code>number</code> | Used to update the EXIF `Orientation` tag, integer between 1 and 8. |\n| [options.density] | <code>number</code> | Number of pixels per inch (DPI). |\n\n**Example**  \n```js\nconst outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)\n  .withMetadata()\n  .toBuffer();\n```\n**Example**  \n```js\n// Set output metadata to 96 DPI\nconst data = await sharp(input)\n  .withMetadata({ density: 96 })\n  .toBuffer();\n```\n\n\n## toFormat\n> toFormat(format, options) ⇒ <code>Sharp</code>\n\nForce output to a given format.\n\n\n**Throws**:\n\n- <code>Error</code> unsupported format or options\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| format | <code>string</code> \\| <code>Object</code> | as a string or an Object with an 'id' attribute |\n| options | <code>Object</code> | output options |\n\n**Example**  \n```js\n// Convert any input to PNG output\nconst data = await sharp(input)\n  .toFormat('png')\n  .toBuffer();\n```\n\n\n## jpeg\n> jpeg([options]) ⇒ <code>Sharp</code>\n\nUse these JPEG options for output image.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid options\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  | output options |\n| [options.quality] | <code>number</code> | <code>80</code> | quality, integer 1-100 |\n| [options.progressive] | <code>boolean</code> | <code>false</code> | use progressive (interlace) scan |\n| [options.chromaSubsampling] | <code>string</code> | <code>&quot;&#x27;4:2:0&#x27;&quot;</code> | set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling |\n| [options.optimiseCoding] | <code>boolean</code> | <code>true</code> | optimise Huffman coding tables |\n| [options.optimizeCoding] | <code>boolean</code> | <code>true</code> | alternative spelling of optimiseCoding |\n| [options.mozjpeg] | <code>boolean</code> | <code>false</code> | use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }` |\n| [options.trellisQuantisation] | <code>boolean</code> | <code>false</code> | apply trellis quantisation |\n| [options.overshootDeringing] | <code>boolean</code> | <code>false</code> | apply overshoot deringing |\n| [options.optimiseScans] | <code>boolean</code> | <code>false</code> | optimise progressive scans, forces progressive |\n| [options.optimizeScans] | <code>boolean</code> | <code>false</code> | alternative spelling of optimiseScans |\n| [options.quantisationTable] | <code>number</code> | <code>0</code> | quantization table to use, integer 0-8 |\n| [options.quantizationTable] | <code>number</code> | <code>0</code> | alternative spelling of quantisationTable |\n| [options.force] | <code>boolean</code> | <code>true</code> | force JPEG output, otherwise attempt to use input format |\n\n**Example**  \n```js\n// Convert any input to very high quality JPEG output\nconst data = await sharp(input)\n  .jpeg({\n    quality: 100,\n    chromaSubsampling: '4:4:4'\n  })\n  .toBuffer();\n```\n**Example**  \n```js\n// Use mozjpeg to reduce output JPEG file size (slower)\nconst data = await sharp(input)\n  .jpeg({ mozjpeg: true })\n  .toBuffer();\n```\n\n\n## png\n> png([options]) ⇒ <code>Sharp</code>\n\nUse these PNG options for output image.\n\nBy default, PNG output is full colour at 8 bits per pixel.\n\nIndexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.\nSet `palette` to `true` for slower, indexed PNG output.\n\nFor 16 bits per pixel output, convert to `rgb16` via\n[toColourspace](/api-colour/#tocolourspace).\n\n\n**Throws**:\n\n- <code>Error</code> Invalid options\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  |  |\n| [options.progressive] | <code>boolean</code> | <code>false</code> | use progressive (interlace) scan |\n| [options.compressionLevel] | <code>number</code> | <code>6</code> | zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) |\n| [options.adaptiveFiltering] | <code>boolean</code> | <code>false</code> | use adaptive row filtering |\n| [options.palette] | <code>boolean</code> | <code>false</code> | quantise to a palette-based image with alpha transparency support |\n| [options.quality] | <code>number</code> | <code>100</code> | use the lowest number of colours needed to achieve given quality, sets `palette` to `true` |\n| [options.effort] | <code>number</code> | <code>7</code> | CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true` |\n| [options.colours] | <code>number</code> | <code>256</code> | maximum number of palette entries, sets `palette` to `true` |\n| [options.colors] | <code>number</code> | <code>256</code> | alternative spelling of `options.colours`, sets `palette` to `true` |\n| [options.dither] | <code>number</code> | <code>1.0</code> | level of Floyd-Steinberg error diffusion, sets `palette` to `true` |\n| [options.force] | <code>boolean</code> | <code>true</code> | force PNG output, otherwise attempt to use input format |\n\n**Example**  \n```js\n// Convert any input to full colour PNG output\nconst data = await sharp(input)\n  .png()\n  .toBuffer();\n```\n**Example**  \n```js\n// Convert any input to indexed PNG output (slower)\nconst data = await sharp(input)\n  .png({ palette: true })\n  .toBuffer();\n```\n**Example**  \n```js\n// Output 16 bits per pixel RGB(A)\nconst data = await sharp(input)\n .toColourspace('rgb16')\n .png()\n .toBuffer();\n```\n\n\n## webp\n> webp([options]) ⇒ <code>Sharp</code>\n\nUse these WebP options for output image.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid options\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  | output options |\n| [options.quality] | <code>number</code> | <code>80</code> | quality, integer 1-100 |\n| [options.alphaQuality] | <code>number</code> | <code>100</code> | quality of alpha layer, integer 0-100 |\n| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression mode |\n| [options.nearLossless] | <code>boolean</code> | <code>false</code> | use near_lossless compression mode |\n| [options.smartSubsample] | <code>boolean</code> | <code>false</code> | use high quality chroma subsampling |\n| [options.smartDeblock] | <code>boolean</code> | <code>false</code> | auto-adjust the deblocking filter, can improve low contrast edges (slow) |\n| [options.preset] | <code>string</code> | <code>&quot;&#x27;default&#x27;&quot;</code> | named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text |\n| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 6 (slowest) |\n| [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation |\n| [options.delay] | <code>number</code> \\| <code>Array.&lt;number&gt;</code> |  | delay(s) between animation frames (in milliseconds) |\n| [options.minSize] | <code>boolean</code> | <code>false</code> | prevent use of animation key frames to minimise file size (slow) |\n| [options.mixed] | <code>boolean</code> | <code>false</code> | allow mixture of lossy and lossless animation frames (slow) |\n| [options.force] | <code>boolean</code> | <code>true</code> | force WebP output, otherwise attempt to use input format |\n\n**Example**  \n```js\n// Convert any input to lossless WebP output\nconst data = await sharp(input)\n  .webp({ lossless: true })\n  .toBuffer();\n```\n**Example**  \n```js\n// Optimise the file size of an animated WebP\nconst outputWebp = await sharp(inputWebp, { animated: true })\n  .webp({ effort: 6 })\n  .toBuffer();\n```\n\n\n## gif\n> gif([options]) ⇒ <code>Sharp</code>\n\nUse these GIF options for the output image.\n\nThe first entry in the palette is reserved for transparency.\n\nThe palette of the input image will be re-used if possible.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid options\n\n**Since**: 0.30.0  \n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  | output options |\n| [options.reuse] | <code>boolean</code> | <code>true</code> | re-use existing palette, otherwise generate new (slow) |\n| [options.progressive] | <code>boolean</code> | <code>false</code> | use progressive (interlace) scan |\n| [options.colours] | <code>number</code> | <code>256</code> | maximum number of palette entries, including transparency, between 2 and 256 |\n| [options.colors] | <code>number</code> | <code>256</code> | alternative spelling of `options.colours` |\n| [options.effort] | <code>number</code> | <code>7</code> | CPU effort, between 1 (fastest) and 10 (slowest) |\n| [options.dither] | <code>number</code> | <code>1.0</code> | level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) |\n| [options.interFrameMaxError] | <code>number</code> | <code>0</code> | maximum inter-frame error for transparency, between 0 (lossless) and 32 |\n| [options.interPaletteMaxError] | <code>number</code> | <code>3</code> | maximum inter-palette error for palette reuse, between 0 and 256 |\n| [options.keepDuplicateFrames] | <code>boolean</code> | <code>false</code> | keep duplicate frames in the output instead of combining them |\n| [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation |\n| [options.delay] | <code>number</code> \\| <code>Array.&lt;number&gt;</code> |  | delay(s) between animation frames (in milliseconds) |\n| [options.force] | <code>boolean</code> | <code>true</code> | force GIF output, otherwise attempt to use input format |\n\n**Example**  \n```js\n// Convert PNG to GIF\nawait sharp(pngBuffer)\n  .gif()\n  .toBuffer();\n```\n**Example**  \n```js\n// Convert animated WebP to animated GIF\nawait sharp('animated.webp', { animated: true })\n  .toFile('animated.gif');\n```\n**Example**  \n```js\n// Create a 128x128, cropped, non-dithered, animated thumbnail of an animated GIF\nconst out = await sharp('in.gif', { animated: true })\n  .resize({ width: 128, height: 128 })\n  .gif({ dither: 0 })\n  .toBuffer();\n```\n**Example**  \n```js\n// Lossy file size reduction of animated GIF\nawait sharp('in.gif', { animated: true })\n  .gif({ interFrameMaxError: 8 })\n  .toFile('optim.gif');\n```\n\n\n## jp2\n> jp2([options]) ⇒ <code>Sharp</code>\n\nUse these JP2 options for output image.\n\nRequires libvips compiled with support for OpenJPEG.\nThe prebuilt binaries do not include this - see\n[installing a custom libvips](/install#custom-libvips).\n\n\n**Throws**:\n\n- <code>Error</code> Invalid options\n\n**Since**: 0.29.1  \n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  | output options |\n| [options.quality] | <code>number</code> | <code>80</code> | quality, integer 1-100 |\n| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression mode |\n| [options.tileWidth] | <code>number</code> | <code>512</code> | horizontal tile size |\n| [options.tileHeight] | <code>number</code> | <code>512</code> | vertical tile size |\n| [options.chromaSubsampling] | <code>string</code> | <code>&quot;&#x27;4:4:4&#x27;&quot;</code> | set to '4:2:0' to use chroma subsampling |\n\n**Example**  \n```js\n// Convert any input to lossless JP2 output\nconst data = await sharp(input)\n  .jp2({ lossless: true })\n  .toBuffer();\n```\n**Example**  \n```js\n// Convert any input to very high quality JP2 output\nconst data = await sharp(input)\n  .jp2({\n    quality: 100,\n    chromaSubsampling: '4:4:4'\n  })\n  .toBuffer();\n```\n\n\n## tiff\n> tiff([options]) ⇒ <code>Sharp</code>\n\nUse these TIFF options for output image.\n\nThe `density` can be set in pixels/inch via [withMetadata](#withmetadata)\ninstead of providing `xres` and `yres` in pixels/mm.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid options\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  | output options |\n| [options.quality] | <code>number</code> | <code>80</code> | quality, integer 1-100 |\n| [options.force] | <code>boolean</code> | <code>true</code> | force TIFF output, otherwise attempt to use input format |\n| [options.compression] | <code>string</code> | <code>&quot;&#x27;jpeg&#x27;&quot;</code> | compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k |\n| [options.bigtiff] | <code>boolean</code> | <code>false</code> | use BigTIFF variant (has no effect when compression is none) |\n| [options.predictor] | <code>string</code> | <code>&quot;&#x27;horizontal&#x27;&quot;</code> | compression predictor options: none, horizontal, float |\n| [options.pyramid] | <code>boolean</code> | <code>false</code> | write an image pyramid |\n| [options.tile] | <code>boolean</code> | <code>false</code> | write a tiled tiff |\n| [options.tileWidth] | <code>number</code> | <code>256</code> | horizontal tile size |\n| [options.tileHeight] | <code>number</code> | <code>256</code> | vertical tile size |\n| [options.xres] | <code>number</code> | <code>1.0</code> | horizontal resolution in pixels/mm |\n| [options.yres] | <code>number</code> | <code>1.0</code> | vertical resolution in pixels/mm |\n| [options.resolutionUnit] | <code>string</code> | <code>&quot;&#x27;inch&#x27;&quot;</code> | resolution unit options: inch, cm |\n| [options.bitdepth] | <code>number</code> | <code>8</code> | reduce bitdepth to 1, 2 or 4 bit |\n| [options.miniswhite] | <code>boolean</code> | <code>false</code> | write 1-bit images as miniswhite |\n\n**Example**  \n```js\n// Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output\nsharp('input.svg')\n  .tiff({\n    compression: 'lzw',\n    bitdepth: 1\n  })\n  .toFile('1-bpp-output.tiff')\n  .then(info => { ... });\n```\n\n\n## avif\n> avif([options]) ⇒ <code>Sharp</code>\n\nUse these AVIF options for output image.\n\nAVIF image sequences are not supported.\nPrebuilt binaries support a bitdepth of 8 only.\n\nThis feature is experimental on the Windows ARM64 platform\nand requires a CPU with ARM64v8.4 or later.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid options\n\n**Since**: 0.27.0  \n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  | output options |\n| [options.quality] | <code>number</code> | <code>50</code> | quality, integer 1-100 |\n| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |\n| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 9 (slowest) |\n| [options.chromaSubsampling] | <code>string</code> | <code>&quot;&#x27;4:4:4&#x27;&quot;</code> | set to '4:2:0' to use chroma subsampling |\n| [options.bitdepth] | <code>number</code> | <code>8</code> | set bitdepth to 8, 10 or 12 bit |\n\n**Example**  \n```js\nconst data = await sharp(input)\n  .avif({ effort: 2 })\n  .toBuffer();\n```\n**Example**  \n```js\nconst data = await sharp(input)\n  .avif({ lossless: true })\n  .toBuffer();\n```\n\n\n## heif\n> heif(options) ⇒ <code>Sharp</code>\n\nUse these HEIF options for output image.\n\nSupport for patent-encumbered HEIC images using `hevc` compression requires the use of a\nglobally-installed libvips compiled with support for libheif, libde265 and x265.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid options\n\n**Since**: 0.23.0  \n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| options | <code>Object</code> |  | output options |\n| options.compression | <code>string</code> |  | compression format: av1, hevc |\n| [options.quality] | <code>number</code> | <code>50</code> | quality, integer 1-100 |\n| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |\n| [options.effort] | <code>number</code> | <code>4</code> | CPU effort, between 0 (fastest) and 9 (slowest) |\n| [options.chromaSubsampling] | <code>string</code> | <code>&quot;&#x27;4:4:4&#x27;&quot;</code> | set to '4:2:0' to use chroma subsampling |\n| [options.bitdepth] | <code>number</code> | <code>8</code> | set bitdepth to 8, 10 or 12 bit |\n\n**Example**  \n```js\nconst data = await sharp(input)\n  .heif({ compression: 'hevc' })\n  .toBuffer();\n```\n\n\n## jxl\n> jxl([options]) ⇒ <code>Sharp</code>\n\nUse these JPEG-XL (JXL) options for output image.\n\nThis feature is experimental, please do not use in production systems.\n\nRequires libvips compiled with support for libjxl.\nThe prebuilt binaries do not include this - see\n[installing a custom libvips](/install/#custom-libvips).\n\n\n**Throws**:\n\n- <code>Error</code> Invalid options\n\n**Since**: 0.31.3  \n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  | output options |\n| [options.distance] | <code>number</code> | <code>1.0</code> | maximum encoding error, between 0 (highest quality) and 15 (lowest quality) |\n| [options.quality] | <code>number</code> |  | calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified |\n| [options.decodingTier] | <code>number</code> | <code>0</code> | target decode speed tier, between 0 (highest quality) and 4 (lowest quality) |\n| [options.lossless] | <code>boolean</code> | <code>false</code> | use lossless compression |\n| [options.effort] | <code>number</code> | <code>7</code> | CPU effort, between 1 (fastest) and 9 (slowest) |\n| [options.loop] | <code>number</code> | <code>0</code> | number of animation iterations, use 0 for infinite animation |\n| [options.delay] | <code>number</code> \\| <code>Array.&lt;number&gt;</code> |  | delay(s) between animation frames (in milliseconds) |\n\n\n\n## raw\n> raw([options]) ⇒ <code>Sharp</code>\n\nForce output to be raw, uncompressed pixel data.\nPixel ordering is left-to-right, top-to-bottom, without padding.\nChannel ordering will be RGB or RGBA for non-greyscale colourspaces.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid options\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  | output options |\n| [options.depth] | <code>string</code> | <code>&quot;&#x27;uchar&#x27;&quot;</code> | bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex |\n\n**Example**  \n```js\n// Extract raw, unsigned 8-bit RGB pixel data from JPEG input\nconst { data, info } = await sharp('input.jpg')\n  .raw()\n  .toBuffer({ resolveWithObject: true });\n```\n**Example**  \n```js\n// Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input\nconst data = await sharp('input.png')\n  .ensureAlpha()\n  .extractChannel(3)\n  .toColourspace('b-w')\n  .raw({ depth: 'ushort' })\n  .toBuffer();\n```\n\n\n## tile\n> tile([options]) ⇒ <code>Sharp</code>\n\nUse tile-based deep zoom (image pyramid) output.\n\nSet the format and options for tile images via the `toFormat`, `jpeg`, `png` or `webp` functions.\nUse a `.zip` or `.szi` file extension with `toFile` to write to a compressed archive file format.\n\nThe container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  |  |\n| [options.size] | <code>number</code> | <code>256</code> | tile size in pixels, a value between 1 and 8192. |\n| [options.overlap] | <code>number</code> | <code>0</code> | tile overlap in pixels, a value between 0 and 8192. |\n| [options.angle] | <code>number</code> | <code>0</code> | tile angle of rotation, must be a multiple of 90. |\n| [options.background] | <code>string</code> \\| <code>Object</code> | <code>&quot;{r: 255, g: 255, b: 255, alpha: 1}&quot;</code> | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency. |\n| [options.depth] | <code>string</code> |  | how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout. |\n| [options.skipBlanks] | <code>number</code> | <code>-1</code> | Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise. |\n| [options.container] | <code>string</code> | <code>&quot;&#x27;fs&#x27;&quot;</code> | tile container, with value `fs` (filesystem) or `zip` (compressed file). |\n| [options.layout] | <code>string</code> | <code>&quot;&#x27;dz&#x27;&quot;</code> | filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. |\n| [options.centre] | <code>boolean</code> | <code>false</code> | centre image in tile. |\n| [options.center] | <code>boolean</code> | <code>false</code> | alternative spelling of centre. |\n| [options.id] | <code>string</code> | <code>&quot;&#x27;https://example.com/iiif&#x27;&quot;</code> | when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json` |\n| [options.basename] | <code>string</code> |  | the name of the directory within the zip file when container is `zip`. |\n\n**Example**  \n```js\nsharp('input.tiff')\n  .png()\n  .tile({\n    size: 512\n  })\n  .toFile('output.dz', function(err, info) {\n    // output.dzi is the Deep Zoom XML definition\n    // output_files contains 512x512 tiles grouped by zoom level\n  });\n```\n**Example**  \n```js\nconst zipFileWithTiles = await sharp(input)\n  .tile({ basename: \"tiles\" })\n  .toBuffer();\n```\n**Example**  \n```js\nconst iiififier = sharp().tile({ layout: \"iiif\" });\nreadableStream\n  .pipe(iiififier)\n  .pipe(writeableStream);\n```\n\n\n## timeout\n> timeout(options) ⇒ <code>Sharp</code>\n\nSet a timeout for processing, in seconds.\nUse a value of zero to continue processing indefinitely, the default behaviour.\n\nThe clock starts when libvips opens an input image for processing.\nTime spent waiting for a libuv thread to become available is not included.\n\n\n**Since**: 0.29.2  \n\n| Param | Type | Description |\n| --- | --- | --- |\n| options | <code>Object</code> |  |\n| options.seconds | <code>number</code> | Number of seconds after which processing will be stopped |\n\n**Example**  \n```js\n// Ensure processing takes no longer than 3 seconds\ntry {\n  const data = await sharp(input)\n    .blur(1000)\n    .timeout({ seconds: 3 })\n    .toBuffer();\n} catch (err) {\n  if (err.message.includes('timeout')) { ... }\n}\n```"
  },
  {
    "path": "docs/src/content/docs/api-resize.md",
    "content": "---\n# This file was auto-generated from JSDoc in lib/resize.js\ntitle: Resizing images\n---\n\n## resize\n> resize([width], [height], [options]) ⇒ <code>Sharp</code>\n\nResize image to `width`, `height` or `width x height`.\n\nWhen both a `width` and `height` are provided, the possible methods by which the image should **fit** these are:\n- `cover`: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit.\n- `contain`: Preserving aspect ratio, contain within both provided dimensions using \"letterboxing\" where necessary.\n- `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions.\n- `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.\n- `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.\n\nSome of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.\n\n<img alt=\"Examples of various values for the fit property when resizing\" width=\"100%\" style=\"aspect-ratio: 998/243\" src=\"/api-resize-fit.svg\">\n\nWhen using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are:\n- `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.\n- `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.\n- `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.\n\nSome of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.\n\nThe strategy-based approach initially resizes so one dimension is at its target length\nthen repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.\n- `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).\n- `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.\n\nPossible downsizing kernels are:\n- `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).\n- `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function).\n- `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).\n- `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).\n- `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.\n- `lanczos3`: Use a Lanczos kernel with `a=3` (the default).\n- `mks2013`: Use a [Magic Kernel Sharp](https://johncostella.com/magic/mks.pdf) 2013 kernel, as adopted by Facebook.\n- `mks2021`: Use a Magic Kernel Sharp 2021 kernel, with more accurate (reduced) sharpening than the 2013 version.\n\nWhen upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.\nDownsampling kernels without a matching upsampling interpolator map to `cubic`.\n\nOnly one resize can occur per pipeline.\nPrevious calls to `resize` in the same pipeline will be ignored.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [width] | <code>number</code> |  | How many pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height. |\n| [height] | <code>number</code> |  | How many pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. |\n| [options] | <code>Object</code> |  |  |\n| [options.width] | <code>number</code> |  | An alternative means of specifying `width`. If both are present this takes priority. |\n| [options.height] | <code>number</code> |  | An alternative means of specifying `height`. If both are present this takes priority. |\n| [options.fit] | <code>String</code> | <code>&#x27;cover&#x27;</code> | How the image should be resized/cropped to fit the target dimension(s), one of `cover`, `contain`, `fill`, `inside` or `outside`. |\n| [options.position] | <code>String</code> | <code>&#x27;centre&#x27;</code> | A position, gravity or strategy to use when `fit` is `cover` or `contain`. |\n| [options.background] | <code>String</code> \\| <code>Object</code> | <code>{r: 0, g: 0, b: 0, alpha: 1}</code> | background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. |\n| [options.kernel] | <code>String</code> | <code>&#x27;lanczos3&#x27;</code> | The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load. |\n| [options.withoutEnlargement] | <code>Boolean</code> | <code>false</code> | Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions. |\n| [options.withoutReduction] | <code>Boolean</code> | <code>false</code> | Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions. |\n| [options.fastShrinkOnLoad] | <code>Boolean</code> | <code>true</code> | Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension. |\n\n**Example**  \n```js\nsharp(input)\n  .resize({ width: 100 })\n  .toBuffer()\n  .then(data => {\n    // 100 pixels wide, auto-scaled height\n  });\n```\n**Example**  \n```js\nsharp(input)\n  .resize({ height: 100 })\n  .toBuffer()\n  .then(data => {\n    // 100 pixels high, auto-scaled width\n  });\n```\n**Example**  \n```js\nsharp(input)\n  .resize(200, 300, {\n    kernel: sharp.kernel.nearest,\n    fit: 'contain',\n    position: 'right top',\n    background: { r: 255, g: 255, b: 255, alpha: 0.5 }\n  })\n  .toFile('output.png')\n  .then(() => {\n    // output.png is a 200 pixels wide and 300 pixels high image\n    // containing a nearest-neighbour scaled version\n    // contained within the north-east corner of a semi-transparent white canvas\n  });\n```\n**Example**  \n```js\nconst transformer = sharp()\n  .resize({\n    width: 200,\n    height: 200,\n    fit: sharp.fit.cover,\n    position: sharp.strategy.entropy\n  });\n// Read image data from readableStream\n// Write 200px square auto-cropped image data to writableStream\nreadableStream\n  .pipe(transformer)\n  .pipe(writableStream);\n```\n**Example**  \n```js\nsharp(input)\n  .resize(200, 200, {\n    fit: sharp.fit.inside,\n    withoutEnlargement: true\n  })\n  .toFormat('jpeg')\n  .toBuffer()\n  .then(function(outputBuffer) {\n    // outputBuffer contains JPEG image data\n    // no wider and no higher than 200 pixels\n    // and no larger than the input image\n  });\n```\n**Example**  \n```js\nsharp(input)\n  .resize(200, 200, {\n    fit: sharp.fit.outside,\n    withoutReduction: true\n  })\n  .toFormat('jpeg')\n  .toBuffer()\n  .then(function(outputBuffer) {\n    // outputBuffer contains JPEG image data\n    // of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio\n    // and no smaller than the input image\n  });\n```\n**Example**  \n```js\nconst scaleByHalf = await sharp(input)\n  .metadata()\n  .then(({ width }) => sharp(input)\n    .resize(Math.round(width * 0.5))\n    .toBuffer()\n  );\n```\n\n\n## extend\n> extend(extend) ⇒ <code>Sharp</code>\n\nExtend / pad / extrude one or more edges of the image with either\nthe provided background colour or pixels derived from the image.\nThis operation will always occur after resizing and extraction, if any.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| extend | <code>number</code> \\| <code>Object</code> |  | single pixel count to add to all edges or an Object with per-edge counts |\n| [extend.top] | <code>number</code> | <code>0</code> |  |\n| [extend.left] | <code>number</code> | <code>0</code> |  |\n| [extend.bottom] | <code>number</code> | <code>0</code> |  |\n| [extend.right] | <code>number</code> | <code>0</code> |  |\n| [extend.extendWith] | <code>String</code> | <code>&#x27;background&#x27;</code> | populate new pixels using this method, one of: background, copy, repeat, mirror. |\n| [extend.background] | <code>String</code> \\| <code>Object</code> | <code>{r: 0, g: 0, b: 0, alpha: 1}</code> | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. |\n\n**Example**  \n```js\n// Resize to 140 pixels wide, then add 10 transparent pixels\n// to the top, left and right edges and 20 to the bottom edge\nsharp(input)\n  .resize(140)\n  .extend({\n    top: 10,\n    bottom: 20,\n    left: 10,\n    right: 10,\n    background: { r: 0, g: 0, b: 0, alpha: 0 }\n  })\n  ...\n```\n**Example**  \n```js\n// Add a row of 10 red pixels to the bottom\nsharp(input)\n  .extend({\n    bottom: 10,\n    background: 'red'\n  })\n  ...\n```\n**Example**  \n```js\n// Extrude image by 8 pixels to the right, mirroring existing right hand edge\nsharp(input)\n  .extend({\n    right: 8,\n    background: 'mirror'\n  })\n  ...\n```\n\n\n## extract\n> extract(options) ⇒ <code>Sharp</code>\n\nExtract/crop a region of the image.\n\n- Use `extract` before `resize` for pre-resize extraction.\n- Use `extract` after `resize` for post-resize extraction.\n- Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| options | <code>Object</code> | describes the region to extract using integral pixel values |\n| options.left | <code>number</code> | zero-indexed offset from left edge |\n| options.top | <code>number</code> | zero-indexed offset from top edge |\n| options.width | <code>number</code> | width of region to extract |\n| options.height | <code>number</code> | height of region to extract |\n\n**Example**  \n```js\nsharp(input)\n  .extract({ left: left, top: top, width: width, height: height })\n  .toFile(output, function(err) {\n    // Extract a region of the input image, saving in the same format.\n  });\n```\n**Example**  \n```js\nsharp(input)\n  .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre })\n  .resize(width, height)\n  .extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost })\n  .toFile(output, function(err) {\n    // Extract a region, resize, then extract from the resized image\n  });\n```\n\n\n## trim\n> trim([options]) ⇒ <code>Sharp</code>\n\nTrim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.\n\nImages with an alpha channel will use the combined bounding box of alpha and non-alpha channels.\n\nIf the result of this operation would trim an image to nothing then no change is made.\n\nThe `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties.\n\n\n**Throws**:\n\n- <code>Error</code> Invalid parameters\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> |  |  |\n| [options.background] | <code>string</code> \\| <code>Object</code> | <code>&quot;&#x27;top-left pixel&#x27;&quot;</code> | Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel. |\n| [options.threshold] | <code>number</code> | <code>10</code> | Allowed difference from the above colour, a positive number. |\n| [options.lineArt] | <code>boolean</code> | <code>false</code> | Does the input more closely resemble line art (e.g. vector) rather than being photographic? |\n\n**Example**  \n```js\n// Trim pixels with a colour similar to that of the top-left pixel.\nawait sharp(input)\n  .trim()\n  .toFile(output);\n```\n**Example**  \n```js\n// Trim pixels with the exact same colour as that of the top-left pixel.\nawait sharp(input)\n  .trim({\n    threshold: 0\n  })\n  .toFile(output);\n```\n**Example**  \n```js\n// Assume input is line art and trim only pixels with a similar colour to red.\nconst output = await sharp(input)\n  .trim({\n    background: \"#FF0000\",\n    lineArt: true\n  })\n  .toBuffer();\n```\n**Example**  \n```js\n// Trim all \"yellow-ish\" pixels, being more lenient with the higher threshold.\nconst output = await sharp(input)\n  .trim({\n    background: \"yellow\",\n    threshold: 42,\n  })\n  .toBuffer();\n```"
  },
  {
    "path": "docs/src/content/docs/api-utility.md",
    "content": "---\n# This file was auto-generated from JSDoc in lib/utility.js\ntitle: Global properties\n---\n\n## versions\n> versions\n\nAn Object containing the version numbers of sharp, libvips\nand (when using prebuilt binaries) its dependencies.\n\n\n**Example**  \n```js\nconsole.log(sharp.versions);\n```\n\n\n## interpolators\n> interpolators : <code>enum</code>\n\nAn Object containing the available interpolators and their proper values\n\n\n**Read only**: true  \n**Properties**\n\n| Name | Type | Default | Description |\n| --- | --- | --- | --- |\n| nearest | <code>string</code> | <code>&quot;nearest&quot;</code> | [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. |\n| bilinear | <code>string</code> | <code>&quot;bilinear&quot;</code> | [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. |\n| bicubic | <code>string</code> | <code>&quot;bicubic&quot;</code> | [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). |\n| locallyBoundedBicubic | <code>string</code> | <code>&quot;lbb&quot;</code> | [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some \"[acutance](http://en.wikipedia.org/wiki/Acutance)\" but typically reduces performance by a factor of 2. |\n| nohalo | <code>string</code> | <code>&quot;nohalo&quot;</code> | [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. |\n| vertexSplitQuadraticBasisSpline | <code>string</code> | <code>&quot;vsqbs&quot;</code> | [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents \"staircasing\" when enlarging. |\n\n\n\n## format\n> format ⇒ <code>Object</code>\n\nAn Object containing nested boolean values representing the available input and output formats/methods.\n\n\n**Example**  \n```js\nconsole.log(sharp.format);\n```\n\n\n## queue\n> queue\n\nAn EventEmitter that emits a `change` event when a task is either:\n- queued, waiting for _libuv_ to provide a worker thread\n- complete\n\n\n**Example**  \n```js\nsharp.queue.on('change', function(queueLength) {\n  console.log('Queue contains ' + queueLength + ' task(s)');\n});\n```\n\n\n## cache\n> cache([options]) ⇒ <code>Object</code>\n\nGets or, when options are provided, sets the limits of _libvips'_ operation cache.\nExisting entries in the cache will be trimmed after any change in limits.\nThis method always returns cache statistics,\nuseful for determining how much working memory is required for a particular task.\n\n\n\n| Param | Type | Default | Description |\n| --- | --- | --- | --- |\n| [options] | <code>Object</code> \\| <code>boolean</code> | <code>true</code> | Object with the following attributes, or boolean where true uses default cache settings and false removes all caching |\n| [options.memory] | <code>number</code> | <code>50</code> | is the maximum memory in MB to use for this cache |\n| [options.files] | <code>number</code> | <code>20</code> | is the maximum number of files to hold open |\n| [options.items] | <code>number</code> | <code>100</code> | is the maximum number of operations to cache |\n\n**Example**  \n```js\nconst stats = sharp.cache();\n```\n**Example**  \n```js\nsharp.cache( { items: 200 } );\nsharp.cache( { files: 0 } );\nsharp.cache(false);\n```\n\n\n## concurrency\n> concurrency([concurrency]) ⇒ <code>number</code>\n\nGets or, when a concurrency is provided, sets\nthe maximum number of threads _libvips_ should use to process _each image_.\nThese are from a thread pool managed by glib,\nwhich helps avoid the overhead of creating new threads.\n\nThis method always returns the current concurrency.\n\nThe default value is the number of CPU cores,\nexcept when using glibc-based Linux without jemalloc,\nwhere the default is `1` to help reduce memory fragmentation.\n\nA value of `0` will reset this to the number of CPU cores.\n\nSome image format libraries spawn additional threads,\ne.g. libaom manages its own 4 threads when encoding AVIF images,\nand these are independent of the value set here.\n\n:::note\nFurther [control over performance](/performance/) is available.\n:::\n\n\n**Returns**: <code>number</code> - concurrency  \n\n| Param | Type |\n| --- | --- |\n| [concurrency] | <code>number</code> | \n\n**Example**  \n```js\nconst threads = sharp.concurrency(); // 4\nsharp.concurrency(2); // 2\nsharp.concurrency(0); // 4\n```\n\n\n## counters\n> counters() ⇒ <code>Object</code>\n\nProvides access to internal task counters.\n- queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool.\n- process is the number of resize tasks currently being processed.\n\n\n**Example**  \n```js\nconst counters = sharp.counters(); // { queue: 2, process: 4 }\n```\n\n\n## simd\n> simd([simd]) ⇒ <code>boolean</code>\n\nGet and set use of SIMD vector unit instructions.\nRequires libvips to have been compiled with highway support.\n\nImproves the performance of `resize`, `blur` and `sharpen` operations\nby taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.\n\n\n\n| Param | Type | Default |\n| --- | --- | --- |\n| [simd] | <code>boolean</code> | <code>true</code> | \n\n**Example**  \n```js\nconst simd = sharp.simd();\n// simd is `true` if the runtime use of highway is currently enabled\n```\n**Example**  \n```js\nconst simd = sharp.simd(false);\n// prevent libvips from using highway at runtime\n```\n\n\n## block\n> block(options)\n\nBlock libvips operations at runtime.\n\nThis is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable,\nwhich when set will block all \"untrusted\" operations.\n\n\n**Since**: 0.32.4  \n\n| Param | Type | Description |\n| --- | --- | --- |\n| options | <code>Object</code> |  |\n| options.operation | <code>Array.&lt;string&gt;</code> | List of libvips low-level operation names to block. |\n\n**Example** *(Block all TIFF input.)*  \n```js\nsharp.block({\n  operation: ['VipsForeignLoadTiff']\n});\n```\n\n\n## unblock\n> unblock(options)\n\nUnblock libvips operations at runtime.\n\nThis is useful for defining a list of allowed operations.\n\n\n**Since**: 0.32.4  \n\n| Param | Type | Description |\n| --- | --- | --- |\n| options | <code>Object</code> |  |\n| options.operation | <code>Array.&lt;string&gt;</code> | List of libvips low-level operation names to unblock. |\n\n**Example** *(Block all input except WebP from the filesystem.)*  \n```js\nsharp.block({\n  operation: ['VipsForeignLoad']\n});\nsharp.unblock({\n  operation: ['VipsForeignLoadWebpFile']\n});\n```\n**Example** *(Block all input except JPEG and PNG from a Buffer or Stream.)*  \n```js\nsharp.block({\n  operation: ['VipsForeignLoad']\n});\nsharp.unblock({\n  operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer']\n});\n```"
  },
  {
    "path": "docs/src/content/docs/changelog/_meta.yml",
    "content": "sort: reverse-slug\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.10.0.md",
    "content": "---\ntitle: v0.10.0 - 23rd April 2015\nslug: changelog/v0.10.0\n---\n\n* Add support for Windows (x86).\n  [#19](https://github.com/lovell/sharp/issues/19)\n  [@DullReferenceException](https://github.com/DullReferenceException)\n  [@itsananderson](https://github.com/itsananderson)\n\n* Add support for Openslide input and DeepZoom output.\n  [#146](https://github.com/lovell/sharp/issues/146)\n  [@mvictoras](https://github.com/mvictoras)\n\n* Allow arbitrary aspect ratios when resizing images via new `ignoreAspectRatio` method.\n  [#192](https://github.com/lovell/sharp/issues/192)\n  [@skedastik](https://github.com/skedastik)\n\n* Enhance output image contrast by stretching its luminance to cover the full dynamic range via new `normalize` method.\n  [#194](https://github.com/lovell/sharp/issues/194)\n  [@bkw](https://github.com/bkw)\n  [@codingforce](https://github.com/codingforce)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.10.1.md",
    "content": "---\ntitle: v0.10.1 - 1st June 2015\nslug: changelog/v0.10.1\n---\n\n* Allow embed of image with alpha transparency onto non-transparent background.\n  [#204](https://github.com/lovell/sharp/issues/204)\n  [@mikemliu](https://github.com/mikemliu)\n\n* Include C standard library for `atoi` as Xcode 6.3 appears to no longer do this.\n  [#228](https://github.com/lovell/sharp/issues/228)\n  [@doggan](https://github.com/doggan)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.11.0.md",
    "content": "---\ntitle: v0.11.0 - 15th July 2015\nslug: changelog/v0.11.0\n---\n\n* Allow alpha transparency compositing via new `overlayWith` method.\n  [#97](https://github.com/lovell/sharp/issues/97)\n  [@gasi](https://github.com/gasi)\n\n* Expose raw ICC profile data as a Buffer when using `metadata`.\n  [#129](https://github.com/lovell/sharp/issues/129)\n  [@homerjam](https://github.com/homerjam)\n\n* Allow image header updates via a parameter passed to existing `withMetadata` method.\n  Provide initial support for EXIF `Orientation` tag,\n  which if present is now removed when using `rotate`, `flip` or `flop`.\n  [#189](https://github.com/lovell/sharp/issues/189)\n  [@h2non](https://github.com/h2non)\n\n* Tighten constructor parameter checks.\n  [#221](https://github.com/lovell/sharp/issues/221)\n  [@mikemorris](https://github.com/mikemorris)\n\n* Allow one input Stream to be shared with two or more output Streams via new `clone` method.\n  [#235](https://github.com/lovell/sharp/issues/235)\n  [@jaubourg](https://github.com/jaubourg)\n\n* Use `round` instead of `floor` when auto-scaling dimensions to avoid floating-point rounding errors.\n  [#238](https://github.com/lovell/sharp/issues/238)\n  [@richardadjogah](https://github.com/richardadjogah)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.11.1.md",
    "content": "---\ntitle: v0.11.1 - 12th August 2015\nslug: changelog/v0.11.1\n---\n\n* Silence MSVC warning: \"C4530: C++ exception handler used, but unwind semantics are not enabled\".\n  [#244](https://github.com/lovell/sharp/pull/244)\n  [@TheThing](https://github.com/TheThing)\n\n* Suppress gamma correction for input image with alpha transparency.\n  [#249](https://github.com/lovell/sharp/issues/249)\n  [@compeak](https://github.com/compeak)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.11.2.md",
    "content": "---\ntitle: v0.11.2 - 28th August 2015\nslug: changelog/v0.11.2\n---\n\n* Allow crop gravity to be provided as a String.\n  [#255](https://github.com/lovell/sharp/pull/255)\n  [@papandreou](https://github.com/papandreou)\n* Add support for io.js v3 and Node v4.\n  [#246](https://github.com/lovell/sharp/issues/246)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.11.3.md",
    "content": "---\ntitle: v0.11.3 - 8th September 2015\nslug: changelog/v0.11.3\n---\n\n* Intrepret blurSigma, sharpenFlat, and sharpenJagged as double precision.\n  [#263](https://github.com/lovell/sharp/pull/263)\n  [@chrisriley](https://github.com/chrisriley)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.11.4.md",
    "content": "---\ntitle: v0.11.4 - 5th November 2015\nslug: changelog/v0.11.4\n---\n\n* Add corners, e.g. `northeast`, to existing `gravity` option.\n  [#291](https://github.com/lovell/sharp/pull/291)\n  [@brandonaaron](https://github.com/brandonaaron)\n\n* Ensure correct auto-rotation for EXIF Orientation values 2 and 4.\n  [#288](https://github.com/lovell/sharp/pull/288)\n  [@brandonaaron](https://github.com/brandonaaron)\n\n* Make static linking possible via `--runtime_link` install option.\n  [#287](https://github.com/lovell/sharp/pull/287)\n  [@vlapo](https://github.com/vlapo)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.12.0.md",
    "content": "---\ntitle: v0.12.0 - 23rd November 2015\nslug: changelog/v0.12.0\n---\n\n* Bundle pre-compiled libvips and its dependencies for 64-bit Linux and Windows.\n  [#42](https://github.com/lovell/sharp/issues/42)\n\n* Take advantage of libvips v8.1.0+ features.\n  [#152](https://github.com/lovell/sharp/issues/152)\n\n* Add support for 64-bit Windows. Drop support for 32-bit Windows.\n  [#224](https://github.com/lovell/sharp/issues/224)\n  [@sabrehagen](https://github.com/sabrehagen)\n\n* Switch default interpolator to bicubic.\n  [#289](https://github.com/lovell/sharp/issues/289)\n  [@mahnunchik](https://github.com/mahnunchik)\n\n* Pre-extract rotatation should not swap width/height.\n  [#296](https://github.com/lovell/sharp/issues/296)\n  [@asilvas](https://github.com/asilvas)\n\n* Ensure 16-bit+alpha input images are (un)premultiplied correctly.\n  [#301](https://github.com/lovell/sharp/issues/301)\n  [@izaakschroeder](https://github.com/izaakschroeder)\n\n* Add `threshold` operation.\n  [#303](https://github.com/lovell/sharp/pull/303)\n  [@dacarley](https://github.com/dacarley)\n\n* Add `negate` operation.\n  [#306](https://github.com/lovell/sharp/pull/306)\n  [@dacarley](https://github.com/dacarley)\n\n* Support `options` Object with existing `extract` operation.\n  [#309](https://github.com/lovell/sharp/pull/309)\n  [@papandreou](https://github.com/papandreou)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.12.1.md",
    "content": "---\ntitle: v0.12.1 - 12th December 2015\nslug: changelog/v0.12.1\n---\n\n* Allow use of SIMD vector instructions (via liborc) to be toggled on/off.\n  [#172](https://github.com/lovell/sharp/issues/172)\n  [@bkw](https://github.com/bkw)\n  [@puzrin](https://github.com/puzrin)\n\n* Ensure embedded ICC profiles output with perceptual intent.\n  [#321](https://github.com/lovell/sharp/issues/321)\n  [@vlapo](https://github.com/vlapo)\n\n* Use the NPM-configured HTTPS proxy, if any, for binary downloads.\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.12.2.md",
    "content": "---\ntitle: v0.12.2 - 16th January 2016\nslug: changelog/v0.12.2\n---\n\n* Upgrade libvips to v8.2.0 for improved vips_shrink.\n\n* Add pre-compiled libvips for ARMv6+ CPUs.\n\n* Ensure 16-bit input images work with embed option.\n  [#325](https://github.com/lovell/sharp/issues/325)\n  [@janaz](https://github.com/janaz)\n\n* Allow compilation with gmake to provide FreeBSD support.\n  [#326](https://github.com/lovell/sharp/issues/326)\n  [@c0decafe](https://github.com/c0decafe)\n\n* Attempt to remove temporary file after installation.\n  [#331](https://github.com/lovell/sharp/issues/331)\n  [@dtoubelis](https://github.com/dtoubelis)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.13.0.md",
    "content": "---\ntitle: v0.13.0 - 15th February 2016\nslug: changelog/v0.13.0\n---\n\n* Improve vector image support by allowing control of density/DPI.\n  Switch pre-built libs from Imagemagick to Graphicsmagick.\n  [#110](https://github.com/lovell/sharp/issues/110)\n  [@bradisbell](https://github.com/bradisbell)\n\n* Add support for raw, uncompressed pixel Buffer/Stream input.\n  [#220](https://github.com/lovell/sharp/issues/220)\n  [@mikemorris](https://github.com/mikemorris)\n\n* Switch from libvips' C to C++ bindings, requires upgrade to v8.2.2.\n  [#299](https://github.com/lovell/sharp/issues/299)\n\n* Control number of open files in libvips' cache; breaks existing `cache` behaviour.\n  [#315](https://github.com/lovell/sharp/issues/315)\n  [@impomezia](https://github.com/impomezia)\n\n* Ensure 16-bit input images can be normalised and embedded onto transparent backgrounds.\n  [#339](https://github.com/lovell/sharp/issues/339)\n  [#340](https://github.com/lovell/sharp/issues/340)\n  [@janaz](https://github.com/janaz)\n\n* Ensure selected format takes precedence over any unknown output filename extension.\n  [#344](https://github.com/lovell/sharp/issues/344)\n  [@ubaltaci](https://github.com/ubaltaci)\n\n* Add support for libvips' PBM, PGM, PPM and FITS image format loaders.\n  [#347](https://github.com/lovell/sharp/issues/347)\n  [@oaleynik](https://github.com/oaleynik)\n\n* Ensure default crop gravity is center/centre.\n  [#351](https://github.com/lovell/sharp/pull/351)\n  [@joelmukuthu](https://github.com/joelmukuthu)\n\n* Improve support for musl libc systems e.g. Alpine Linux.\n  [#354](https://github.com/lovell/sharp/issues/354)\n  [#359](https://github.com/lovell/sharp/pull/359)\n  [@download13](https://github.com/download13)\n  [@wjordan](https://github.com/wjordan)\n\n* Small optimisation when reducing by an integral factor to favour shrink over affine.\n\n* Add support for gamma correction of images with an alpha channel.\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.13.1.md",
    "content": "---\ntitle: v0.13.1 - 27th February 2016\nslug: changelog/v0.13.1\n---\n\n* Fix embedding onto transparent backgrounds; regression introduced in v0.13.0.\n  [#366](https://github.com/lovell/sharp/issues/366)\n  [@diegocsandrim](https://github.com/diegocsandrim)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.14.0.md",
    "content": "---\ntitle: v0.14.0 - 2nd April 2016\nslug: changelog/v0.14.0\n---\n\n* Add ability to extend (pad) the edges of an image.\n  [#128](https://github.com/lovell/sharp/issues/128)\n  [@blowsie](https://github.com/blowsie)\n\n* Add support for Zoomify and Google tile layouts. Breaks existing tile API.\n  [#223](https://github.com/lovell/sharp/issues/223)\n  [@bdunnette](https://github.com/bdunnette)\n\n* Improvements to overlayWith: differing sizes/formats, gravity, buffer input.\n  [#239](https://github.com/lovell/sharp/issues/239)\n  [@chrisriley](https://github.com/chrisriley)\n\n* Add entropy-based crop strategy to remove least interesting edges.\n  [#295](https://github.com/lovell/sharp/issues/295)\n  [@rightaway](https://github.com/rightaway)\n\n* Expose density metadata; set density of images from vector input.\n  [#338](https://github.com/lovell/sharp/issues/338)\n  [@lookfirst](https://github.com/lookfirst)\n\n* Emit post-processing 'info' event for Stream output.\n  [#367](https://github.com/lovell/sharp/issues/367)\n  [@salzhrani](https://github.com/salzhrani)\n\n* Ensure output image EXIF Orientation values are within 1-8 range.\n  [#385](https://github.com/lovell/sharp/pull/385)\n  [@jtobinisaniceguy](https://github.com/jtobinisaniceguy)\n\n* Ensure ratios are not swapped when rotating 90/270 and ignoring aspect.\n  [#387](https://github.com/lovell/sharp/issues/387)\n  [@kleisauke](https://github.com/kleisauke)\n\n* Remove deprecated style of calling extract API. Breaks calls using positional arguments.\n  [#276](https://github.com/lovell/sharp/issues/276)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.14.1.md",
    "content": "---\ntitle: v0.14.1 - 16th April 2016\nslug: changelog/v0.14.1\n---\n\n* Allow removal of limitation on input pixel count via limitInputPixels. Use with care.\n  [#250](https://github.com/lovell/sharp/issues/250)\n  [#316](https://github.com/lovell/sharp/pull/316)\n  [@anandthakker](https://github.com/anandthakker)\n  [@kentongray](https://github.com/kentongray)\n\n* Use final output image for metadata passed to callback.\n  [#399](https://github.com/lovell/sharp/pull/399)\n  [@salzhrani](https://github.com/salzhrani)\n\n* Add support for writing tiled images to a zip container.\n  [#402](https://github.com/lovell/sharp/pull/402)\n  [@felixbuenemann](https://github.com/felixbuenemann)\n\n* Allow use of embed with 1 and 2 channel images.\n  [#411](https://github.com/lovell/sharp/issues/411)\n  [@janaz](https://github.com/janaz)\n\n* Improve Electron compatibility by allowing node-gyp rebuilds without npm.\n  [#412](https://github.com/lovell/sharp/issues/412)\n  [@nouh](https://github.com/nouh)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.15.0.md",
    "content": "---\ntitle: v0.15.0 - 21st May 2016\nslug: changelog/v0.15.0\n---\n\n* Use libvips' new Lanczos 3 kernel as default for image reduction.\n  Deprecate interpolateWith method, now provided as a resize option.\n  [#310](https://github.com/lovell/sharp/issues/310)\n  [@jcupitt](https://github.com/jcupitt)\n\n* Take advantage of libvips v8.3 features.\n  Add support for libvips' new GIF and SVG loaders.\n  Pre-built binaries now include giflib and librsvg, exclude *magick.\n  Use shrink-on-load for WebP input.\n  Break existing sharpen API to accept sigma and improve precision.\n  [#369](https://github.com/lovell/sharp/issues/369)\n\n* Remove unnecessary (un)premultiply operations when not resizing/compositing.\n  [#413](https://github.com/lovell/sharp/issues/413)\n  [@jardakotesovec](https://github.com/jardakotesovec)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.15.1.md",
    "content": "---\ntitle: v0.15.1 - 12th July 2016\nslug: changelog/v0.15.1\n---\n\n* Concat Stream-based input in single operation for ~+3% perf and less GC.\n  [#429](https://github.com/lovell/sharp/issues/429)\n  [@papandreou](https://github.com/papandreou)\n\n* Add alpha channel, if required, before extend operation.\n  [#439](https://github.com/lovell/sharp/pull/439)\n  [@frulo](https://github.com/frulo)\n\n* Allow overlay image to be repeated across entire image via tile option.\n  [#443](https://github.com/lovell/sharp/pull/443)\n  [@lemnisk8](https://github.com/lemnisk8)\n\n* Add cutout option to overlayWith feature, applies only the alpha channel of the overlay image.\n  [#448](https://github.com/lovell/sharp/pull/448)\n  [@kleisauke](https://github.com/kleisauke)\n\n* Ensure scaling factors are calculated independently to prevent rounding errors.\n  [#452](https://github.com/lovell/sharp/issues/452)\n  [@puzrin](https://github.com/puzrin)\n\n* Add --sharp-cxx11 flag to compile with gcc's new C++11 ABI.\n  [#456](https://github.com/lovell/sharp/pull/456)\n  [@kapouer](https://github.com/kapouer)\n\n* Add top/left offset support to overlayWith operation.\n  [#473](https://github.com/lovell/sharp/pull/473)\n  [@rnanwani](https://github.com/rnanwani)\n\n* Add convolve operation for kernel-based convolution.\n  [#479](https://github.com/lovell/sharp/pull/479)\n  [@mhirsch](https://github.com/mhirsch)\n\n* Add greyscale option to threshold operation for colourspace conversion control.\n  [#480](https://github.com/lovell/sharp/pull/480)\n  [@mhirsch](https://github.com/mhirsch)\n\n* Ensure ICC profiles are licenced for distribution.\n  [#486](https://github.com/lovell/sharp/issues/486)\n  [@kapouer](https://github.com/kapouer)\n\n* Allow images with an alpha channel to work with LAB-colourspace based sharpen.\n  [#490](https://github.com/lovell/sharp/issues/490)\n  [@jwagner](https://github.com/jwagner)\n\n* Add trim operation to remove \"boring\" edges.\n  [#492](https://github.com/lovell/sharp/pull/492)\n  [@kleisauke](https://github.com/kleisauke)\n\n* Add bandbool feature for channel-wise boolean operations.\n  [#496](https://github.com/lovell/sharp/pull/496)\n  [@mhirsch](https://github.com/mhirsch)\n\n* Add extractChannel operation to extract a channel from an image.\n  [#497](https://github.com/lovell/sharp/pull/497)\n  [@mhirsch](https://github.com/mhirsch)\n\n* Add ability to read and write native libvips .v files.\n  [#500](https://github.com/lovell/sharp/pull/500)\n  [@mhirsch](https://github.com/mhirsch)\n\n* Add boolean feature for bitwise image operations.\n  [#501](https://github.com/lovell/sharp/pull/501)\n  [@mhirsch](https://github.com/mhirsch)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.16.0.md",
    "content": "---\ntitle: v0.16.0 - 18th August 2016\nslug: changelog/v0.16.0\n---\n\n* Add pre-compiled libvips for OS X, ARMv7 and ARMv8.\n  [#312](https://github.com/lovell/sharp/issues/312)\n\n* Ensure boolean, bandbool, extractChannel ops occur before sRGB conversion.\n  [#504](https://github.com/lovell/sharp/pull/504)\n  [@mhirsch](https://github.com/mhirsch)\n\n* Recalculate factors after WebP shrink-on-load to avoid round-to-zero errors.\n  [#508](https://github.com/lovell/sharp/issues/508)\n  [@asilvas](https://github.com/asilvas)\n\n* Prevent boolean errors during extract operation.\n  [#511](https://github.com/lovell/sharp/pull/511)\n  [@mhirsch](https://github.com/mhirsch)\n\n* Add joinChannel and toColourspace/toColorspace operations.\n  [#513](https://github.com/lovell/sharp/pull/513)\n  [@mhirsch](https://github.com/mhirsch)\n\n* Add support for raw pixel data with boolean and withOverlay operations.\n  [#516](https://github.com/lovell/sharp/pull/516)\n  [@mhirsch](https://github.com/mhirsch)\n\n* Prevent bandbool creating a single channel sRGB image.\n  [#519](https://github.com/lovell/sharp/pull/519)\n  [@mhirsch](https://github.com/mhirsch)\n\n* Ensure ICC profiles are removed from PNG output unless withMetadata used.\n  [#521](https://github.com/lovell/sharp/issues/521)\n  [@ChrisPinewood](https://github.com/ChrisPinewood)\n\n* Add alpha channels, if missing, to overlayWith images.\n  [#540](https://github.com/lovell/sharp/pull/540)\n  [@cmtt](https://github.com/cmtt)\n\n* Remove deprecated interpolateWith method - use resize(w, h, { interpolator: ... })\n  [#310](https://github.com/lovell/sharp/issues/310)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.16.1.md",
    "content": "---\ntitle: v0.16.1 - 13th October 2016\nslug: changelog/v0.16.1\n---\n\n* C++11 ABI version is now auto-detected, remove sharp-cxx11 installation flag.\n\n* Add experimental 'attention' crop strategy.\n  [#295](https://github.com/lovell/sharp/issues/295)\n\n* Include .node extension for Meteor's require() implementation.\n  [#537](https://github.com/lovell/sharp/issues/537)\n  [@isjackwild](https://github.com/isjackwild)\n\n* Ensure convolution kernel scale is clamped to a minimum value of 1.\n  [#561](https://github.com/lovell/sharp/issues/561)\n  [@abagshaw](https://github.com/abagshaw)\n\n* Correct calculation of y-axis placement when overlaying image at a fixed point.\n  [#566](https://github.com/lovell/sharp/issues/566)\n  [@Nateowami](https://github.com/Nateowami)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.16.2.md",
    "content": "---\ntitle: v0.16.2 - 22nd October 2016\nslug: changelog/v0.16.2\n---\n\n* Restrict readelf usage to Linux only when detecting global libvips version.\n  [#602](https://github.com/lovell/sharp/issues/602)\n  [@caoko](https://github.com/caoko)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.17.0.md",
    "content": "---\ntitle: v0.17.0 - 11th December 2016\nslug: changelog/v0.17.0\n---\n\n* Drop support for versions of Node prior to v4.\n\n* Deprecate the following output format \"option\" functions:\n    quality, progressive, compressionLevel, withoutAdaptiveFiltering,\n    withoutChromaSubsampling, trellisQuantisation, trellisQuantization,\n    overshootDeringing, optimiseScans and optimizeScans.\n  Access to these is now via output format functions, for example `quality(n)`\n    is now `jpeg({quality: n})` and/or `webp({quality: n})`.\n\n* Autoconvert GIF and SVG input to PNG output if no other format is specified.\n\n* Expose libvips' \"centre\" resize option to mimic \\*magick's +0.5px convention.\n  [#568](https://github.com/lovell/sharp/issues/568)\n\n* Ensure support for embedded base64 PNG and JPEG images within an SVG.\n  [#601](https://github.com/lovell/sharp/issues/601)\n  [@dynamite-ready](https://github.com/dynamite-ready)\n\n* Ensure premultiply operation occurs before box filter shrink.\n  [#605](https://github.com/lovell/sharp/issues/605)\n  [@CmdrShepardsPie](https://github.com/CmdrShepardsPie)\n  [@teroparvinen](https://github.com/teroparvinen)\n\n* Add support for PNG and WebP tile-based output formats (in addition to JPEG).\n  [#622](https://github.com/lovell/sharp/pull/622)\n  [@ppaskaris](https://github.com/ppaskaris)\n\n* Allow use of extend with greyscale input.\n  [#623](https://github.com/lovell/sharp/pull/623)\n  [@ppaskaris](https://github.com/ppaskaris)\n\n* Allow non-RGB input to embed/extend onto background with an alpha channel.\n  [#646](https://github.com/lovell/sharp/issues/646)\n  [@DaGaMs](https://github.com/DaGaMs)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.17.1.md",
    "content": "---\ntitle: v0.17.1 - 15th January 2017\nslug: changelog/v0.17.1\n---\n\n* Improve error messages for invalid parameters.\n  [@spikeon](https://github.com/spikeon)\n  [#644](https://github.com/lovell/sharp/pull/644)\n\n* Simplify expression for finding vips-cpp libdir.\n  [#656](https://github.com/lovell/sharp/pull/656)\n\n* Allow HTTPS-over-HTTP proxy when downloading pre-compiled dependencies.\n  [@wangzhiwei1888](https://github.com/wangzhiwei1888)\n  [#679](https://github.com/lovell/sharp/issues/679)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.17.2.md",
    "content": "---\ntitle: v0.17.2 - 11th February 2017\nslug: changelog/v0.17.2\n---\n\n* Ensure Readable side of Stream can start flowing after Writable side has finished.\n  [#671](https://github.com/lovell/sharp/issues/671)\n  [@danhaller](https://github.com/danhaller)\n\n* Expose WebP alpha quality, lossless and near-lossless output options.\n  [#685](https://github.com/lovell/sharp/pull/685)\n  [@rnanwani](https://github.com/rnanwani)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.17.3.md",
    "content": "---\ntitle: v0.17.3 - 1st April 2017\nslug: changelog/v0.17.3\n---\n\n* Allow toBuffer to optionally resolve a Promise with both info and data.\n  [#143](https://github.com/lovell/sharp/issues/143)\n  [@salzhrani](https://github.com/salzhrani)\n\n* Create blank image of given width, height, channels and background.\n  [#470](https://github.com/lovell/sharp/issues/470)\n  [@pjarts](https://github.com/pjarts)\n\n* Add support for the \"nearest\" kernel for image reductions.\n  [#732](https://github.com/lovell/sharp/pull/732)\n  [@alice0meta](https://github.com/alice0meta)\n\n* Add support for TIFF compression and predictor options.\n  [#738](https://github.com/lovell/sharp/pull/738)\n  [@kristojorg](https://github.com/kristojorg)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.18.0.md",
    "content": "---\ntitle: v0.18.0 - 30th May 2017\nslug: changelog/v0.18.0\n---\n\n* Remove the previously-deprecated output format \"option\" functions:\n    quality, progressive, compressionLevel, withoutAdaptiveFiltering,\n    withoutChromaSubsampling, trellisQuantisation, trellisQuantization,\n    overshootDeringing, optimiseScans and optimizeScans.\n\n* Ensure maximum output dimensions are based on the format to be used.\n  [#176](https://github.com/lovell/sharp/issues/176)\n  [@stephanebachelier](https://github.com/stephanebachelier)\n\n* Avoid costly (un)premultiply when using overlayWith without alpha channel.\n  [#573](https://github.com/lovell/sharp/issues/573)\n  [@strarsis](https://github.com/strarsis)\n\n* Include pixel depth (e.g. \"uchar\") when reading metadata.\n  [#577](https://github.com/lovell/sharp/issues/577)\n  [@moedusa](https://github.com/moedusa)\n\n* Add support for Buffer and Stream-based TIFF output.\n  [#587](https://github.com/lovell/sharp/issues/587)\n  [@strarsis](https://github.com/strarsis)\n\n* Expose warnings from libvips via NODE_DEBUG=sharp environment variable.\n  [#607](https://github.com/lovell/sharp/issues/607)\n  [@puzrin](https://github.com/puzrin)\n\n* Switch to the libvips implementation of \"attention\" and \"entropy\" crop strategies.\n  [#727](https://github.com/lovell/sharp/issues/727)\n\n* Improve performance and accuracy of nearest neighbour integral upsampling.\n  [#752](https://github.com/lovell/sharp/issues/752)\n  [@MrIbby](https://github.com/MrIbby)\n\n* Constructor single argument API: allow plain object, reject null/undefined.\n  [#768](https://github.com/lovell/sharp/issues/768)\n  [@kub1x](https://github.com/kub1x)\n\n* Ensure ARM64 pre-built binaries use correct C++11 ABI version.\n  [#772](https://github.com/lovell/sharp/issues/772)\n  [@ajiratech2](https://github.com/ajiratech2)\n\n* Prevent aliasing by using dynamic values for shrink(-on-load).\n  [#781](https://github.com/lovell/sharp/issues/781)\n  [@kleisauke](https://github.com/kleisauke)\n\n* Expose libvips' \"squash\" parameter to enable 1-bit TIFF output.\n  [#783](https://github.com/lovell/sharp/pull/783)\n  [@YvesBos](https://github.com/YvesBos)\n\n* Add support for rotation using any multiple of +/-90 degrees.\n  [#791](https://github.com/lovell/sharp/pull/791)\n  [@ncoden](https://github.com/ncoden)\n\n* Add \"jpg\" alias to toFormat as shortened form of \"jpeg\".\n  [#814](https://github.com/lovell/sharp/pull/814)\n  [@jingsam](https://github.com/jingsam)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.18.1.md",
    "content": "---\ntitle: v0.18.1 - 30th May 2017\nslug: changelog/v0.18.1\n---\n\n* Remove regression from #781 that could cause incorrect shrink calculation.\n  [#831](https://github.com/lovell/sharp/issues/831)\n  [@suprMax](https://github.com/suprMax)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.18.2.md",
    "content": "---\ntitle: v0.18.2 - 1st July 2017\nslug: changelog/v0.18.2\n---\n\n* Expose libvips' xres and yres properties for TIFF output.\n  [#828](https://github.com/lovell/sharp/pull/828)\n  [@YvesBos](https://github.com/YvesBos)\n\n* Ensure flip and flop operations work with auto-rotate.\n  [#837](https://github.com/lovell/sharp/issues/837)\n  [@rexxars](https://github.com/rexxars)\n\n* Allow binary download URL override via SHARP_DIST_BASE_URL env variable.\n  [#841](https://github.com/lovell/sharp/issues/841)\n\n* Add support for Solus Linux.\n  [#857](https://github.com/lovell/sharp/pull/857)\n  [@ekremkaraca](https://github.com/ekremkaraca)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.18.3.md",
    "content": "---\ntitle: v0.18.3 - 13th September 2017\nslug: changelog/v0.18.3\n---\n\n* Skip shrink-on-load when trimming.\n  [#888](https://github.com/lovell/sharp/pull/888)\n  [@kleisauke](https://github.com/kleisauke)\n\n* Migrate from got to simple-get for basic auth support.\n  [#945](https://github.com/lovell/sharp/pull/945)\n  [@pbomb](https://github.com/pbomb)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.18.4.md",
    "content": "---\ntitle: v0.18.4 - 18th September 2017\nslug: changelog/v0.18.4\n---\n\n* Ensure input Buffer really is marked as Persistent, prevents mark-sweep GC.\n  [#950](https://github.com/lovell/sharp/issues/950)\n  [@lfdoherty](https://github.com/lfdoherty)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.19.0.md",
    "content": "---\ntitle: v0.19.0 - 11th January 2018\nslug: changelog/v0.19.0\n---\n\n* Expose offset coordinates of strategy-based crop.\n  [#868](https://github.com/lovell/sharp/issues/868)\n  [@mirohristov-com](https://github.com/mirohristov-com)\n\n* PNG output now defaults to adaptiveFiltering=false, compressionLevel=9\n  [#872](https://github.com/lovell/sharp/issues/872)\n  [@wmertens](https://github.com/wmertens)\n\n* Add stats feature for pixel-derived image statistics.\n  [#915](https://github.com/lovell/sharp/pull/915)\n  [@rnanwani](https://github.com/rnanwani)\n\n* Add failOnError option to fail-fast on bad input image data.\n  [#976](https://github.com/lovell/sharp/pull/976)\n  [@mceachen](https://github.com/mceachen)\n\n* Resize: switch to libvips' implementation, make fastShrinkOnLoad optional, remove interpolator and centreSampling options.\n  [#977](https://github.com/lovell/sharp/pull/977)\n  [@jardakotesovec](https://github.com/jardakotesovec)\n\n* Attach finish event listener to a clone only for Stream-based input.\n  [#995](https://github.com/lovell/sharp/issues/995)\n  [@whmountains](https://github.com/whmountains)\n\n* Add tilecache before smartcrop to avoid over-computation of previous operations.\n  [#1028](https://github.com/lovell/sharp/issues/1028)\n  [@coffeebite](https://github.com/coffeebite)\n\n* Prevent toFile extension taking precedence over requested format.\n  [#1037](https://github.com/lovell/sharp/issues/1037)\n  [@tomgallagher](https://github.com/tomgallagher)\n\n* Add support for gravity option to existing embed feature.\n  [#1038](https://github.com/lovell/sharp/pull/1038)\n  [@AzureByte](https://github.com/AzureByte)\n\n* Expose IPTC and XMP metadata when available.\n  [#1079](https://github.com/lovell/sharp/pull/1079)\n  [@oaleynik](https://github.com/oaleynik)\n\n* TIFF output: switch default predictor from 'none' to 'horizontal' to match libvips' behaviour.\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.19.1.md",
    "content": "---\ntitle: v0.19.1 - 24th February 2018\nslug: changelog/v0.19.1\n---\n\n* Expose libvips' linear transform feature.\n  [#1024](https://github.com/lovell/sharp/pull/1024)\n  [@3epnm](https://github.com/3epnm)\n\n* Expose angle option for tile-based output.\n  [#1121](https://github.com/lovell/sharp/pull/1121)\n  [@BiancoA](https://github.com/BiancoA)\n\n* Prevent crop operation when image already at or below target dimensions.\n  [#1134](https://github.com/lovell/sharp/issues/1134)\n  [@pieh](https://github.com/pieh)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.20.0.md",
    "content": "---\ntitle: v0.20.0 - 5th March 2018\nslug: changelog/v0.20.0\n---\n\n* Add support for prebuilt sharp binaries on common platforms.\n  [#186](https://github.com/lovell/sharp/issues/186)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.20.1.md",
    "content": "---\ntitle: v0.20.1 - 17th March 2018\nslug: changelog/v0.20.1\n---\n\n* Improve installation experience when a globally-installed libvips below the minimum required version is found.\n  [#1148](https://github.com/lovell/sharp/issues/1148)\n\n* Prevent smartcrop error when cumulative rounding is below target size.\n  [#1154](https://github.com/lovell/sharp/issues/1154)\n  [@ralrom](https://github.com/ralrom)\n\n* Expose libvips' median filter operation.\n  [#1161](https://github.com/lovell/sharp/pull/1161)\n  [@BiancoA](https://github.com/BiancoA)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.20.2.md",
    "content": "---\ntitle: v0.20.2 - 28th April 2018\nslug: changelog/v0.20.2\n---\n\n* Add tint operation to set image chroma.\n  [#825](https://github.com/lovell/sharp/pull/825)\n  [@rikh42](https://github.com/rikh42)\n\n* Add environment variable to ignore globally-installed libvips.\n  [#1165](https://github.com/lovell/sharp/pull/1165)\n  [@oncletom](https://github.com/oncletom)\n\n* Add support for page selection with multi-page input (GIF/TIFF).\n  [#1204](https://github.com/lovell/sharp/pull/1204)\n  [@woolite64](https://github.com/woolite64)\n\n* Add support for Group4 (CCITTFAX4) compression with TIFF output.\n  [#1208](https://github.com/lovell/sharp/pull/1208)\n  [@woolite64](https://github.com/woolite64)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.20.3.md",
    "content": "---\ntitle: v0.20.3 - 29th May 2018\nslug: changelog/v0.20.3\n---\n\n* Fix tint operation by ensuring LAB interpretation and allowing negative values.\n  [#1235](https://github.com/lovell/sharp/issues/1235)\n  [@wezside](https://github.com/wezside)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.20.4.md",
    "content": "---\ntitle: v0.20.4 - 20th June 2018\nslug: changelog/v0.20.4\n---\n\n* Prevent possible rounding error when using shrink-on-load and 90/270 degree rotation.\n  [#1241](https://github.com/lovell/sharp/issues/1241)\n  [@anahit42](https://github.com/anahit42)\n\n* Ensure extractChannel sets correct single-channel colour space interpretation.\n  [#1257](https://github.com/lovell/sharp/issues/1257)\n  [@jeremychone](https://github.com/jeremychone)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.20.5.md",
    "content": "---\ntitle: v0.20.5 - 27th June 2018\nslug: changelog/v0.20.5\n---\n\n* Expose libjpeg optimize_coding flag.\n  [#1265](https://github.com/lovell/sharp/pull/1265)\n  [@tomlokhorst](https://github.com/tomlokhorst)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.20.6.md",
    "content": "---\ntitle: v0.20.6 - 20th August 2018\nslug: changelog/v0.20.6\n---\n\n* Add removeAlpha operation to remove alpha channel, if any.\n  [#1248](https://github.com/lovell/sharp/issues/1248)\n\n* Expose mozjpeg quant_table flag.\n  [#1285](https://github.com/lovell/sharp/pull/1285)\n  [@rexxars](https://github.com/rexxars)\n\n* Allow full WebP alphaQuality range of 0-100.\n  [#1290](https://github.com/lovell/sharp/pull/1290)\n  [@sylvaindumont](https://github.com/sylvaindumont)\n\n* Cache libvips binaries to reduce re-install time.\n  [#1301](https://github.com/lovell/sharp/issues/1301)\n\n* Ensure vendor platform mismatch throws error at install time.\n  [#1303](https://github.com/lovell/sharp/issues/1303)\n\n* Improve install time error messages for FreeBSD users.\n  [#1310](https://github.com/lovell/sharp/issues/1310)\n\n* Ensure extractChannel works with 16-bit images.\n  [#1330](https://github.com/lovell/sharp/issues/1330)\n\n* Expose depth option for tile-based output.\n  [#1342](https://github.com/lovell/sharp/pull/1342)\n  [@alundavies](https://github.com/alundavies)\n\n* Add experimental entropy field to stats response.\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.20.7.md",
    "content": "---\ntitle: v0.20.7 - 21st August 2018\nslug: changelog/v0.20.7\n---\n\n* Use copy+unlink if rename operation fails during installation.\n  [#1345](https://github.com/lovell/sharp/issues/1345)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.20.8.md",
    "content": "---\ntitle: v0.20.8 - 5th September 2018\nslug: changelog/v0.20.8\n---\n\n* Avoid race conditions when creating directories during installation.\n  [#1358](https://github.com/lovell/sharp/pull/1358)\n  [@ajhool](https://github.com/ajhool)\n\n* Accept floating point values for input density parameter.\n  [#1362](https://github.com/lovell/sharp/pull/1362)\n  [@aeirola](https://github.com/aeirola)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.21.0.md",
    "content": "---\ntitle: v0.21.0 - 4th October 2018\nslug: changelog/v0.21.0\n---\n\n* Deprecate the following resize-related functions:\n    `crop`, `embed`, `ignoreAspectRatio`, `max`, `min` and `withoutEnlargement`.\n  Access to these is now via options passed to the `resize` function.\n  For example:\n    `embed('north')` is now `resize(width, height, { fit: 'contain', position: 'north' })`,\n    `crop('attention')` is now `resize(width, height, { fit: 'cover', position: 'attention' })`,\n    `max().withoutEnlargement()` is now `resize(width, height, { fit: 'inside', withoutEnlargement: true })`.\n  [#1135](https://github.com/lovell/sharp/issues/1135)\n\n* Deprecate the `background` function.\n    Per-operation `background` options added to `resize`, `extend` and `flatten` operations.\n  [#1392](https://github.com/lovell/sharp/issues/1392)\n\n* Add `size` to `metadata` response (Stream and Buffer input only).\n  [#695](https://github.com/lovell/sharp/issues/695)\n\n* Switch from custom trim operation to `vips_find_trim`.\n  [#914](https://github.com/lovell/sharp/issues/914)\n\n* Add `chromaSubsampling` and `isProgressive` properties to `metadata` response.\n  [#1186](https://github.com/lovell/sharp/issues/1186)\n\n* Drop Node 4 support.\n  [#1212](https://github.com/lovell/sharp/issues/1212)\n\n* Enable SIMD convolution by default.\n  [#1213](https://github.com/lovell/sharp/issues/1213)\n\n* Add experimental prebuilt binaries for musl-based Linux.\n  [#1379](https://github.com/lovell/sharp/issues/1379)\n\n* Add support for arbitrary rotation angle via vips_rotate.\n  [#1385](https://github.com/lovell/sharp/pull/1385)\n  [@freezy](https://github.com/freezy)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.21.1.md",
    "content": "---\ntitle: v0.21.1 - 7th December 2018\nslug: changelog/v0.21.1\n---\n\n* Install: support `sharp_dist_base_url` npm config, like existing `SHARP_DIST_BASE_URL`.\n  [#1422](https://github.com/lovell/sharp/pull/1422)\n  [@SethWen](https://github.com/SethWen)\n\n* Ensure `channel` metadata is correct for raw, greyscale output.\n  [#1425](https://github.com/lovell/sharp/issues/1425)\n\n* Add support for the \"mitchell\" kernel for image reductions.\n  [#1438](https://github.com/lovell/sharp/pull/1438)\n  [@Daiz](https://github.com/Daiz)\n\n* Allow separate parameters for gamma encoding and decoding.\n  [#1439](https://github.com/lovell/sharp/pull/1439)\n  [@Daiz](https://github.com/Daiz)\n\n* Build prototype with `Object.assign` to allow minification.\n  [#1475](https://github.com/lovell/sharp/pull/1475)\n  [@jaubourg](https://github.com/jaubourg)\n\n* Expose libvips' recombination matrix operation.\n  [#1477](https://github.com/lovell/sharp/pull/1477)\n  [@fromkeith](https://github.com/fromkeith)\n\n* Expose libvips' pyramid/tile options for TIFF output.\n  [#1483](https://github.com/lovell/sharp/pull/1483)\n  [@mbklein](https://github.com/mbklein)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.21.2.md",
    "content": "---\ntitle: v0.21.2 - 13th January 2019\nslug: changelog/v0.21.2\n---\n\n* Ensure all metadata is removed from PNG output unless `withMetadata` used.\n\n* Ensure shortest edge is at least one pixel after resizing.\n  [#1003](https://github.com/lovell/sharp/issues/1003)\n\n* Add `ensureAlpha` operation to add an alpha channel, if missing.\n  [#1153](https://github.com/lovell/sharp/issues/1153)\n\n* Expose `pages` and `pageHeight` metadata for multi-page input images.\n  [#1205](https://github.com/lovell/sharp/issues/1205)\n\n* Expose PNG output options requiring libimagequant.\n  [#1484](https://github.com/lovell/sharp/issues/1484)\n\n* Expose underlying error message for invalid input.\n  [#1505](https://github.com/lovell/sharp/issues/1505)\n\n* Prevent mutatation of options passed to `jpeg`.\n  [#1516](https://github.com/lovell/sharp/issues/1516)\n\n* Ensure forced output format applied correctly when output chaining.\n  [#1528](https://github.com/lovell/sharp/issues/1528)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.21.3.md",
    "content": "---\ntitle: v0.21.3 - 19th January 2019\nslug: changelog/v0.21.3\n---\n\n* Input image decoding now fails fast, set `failOnError` to change this behaviour.\n\n* Failed filesystem-based input now separates missing file and invalid format errors.\n  [#1542](https://github.com/lovell/sharp/issues/1542)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.22.0.md",
    "content": "---\ntitle: v0.22.0 - 18th March 2019\nslug: changelog/v0.22.0\n---\n\n* Remove functions previously deprecated in v0.21.0:\n    `background`, `crop`, `embed`, `ignoreAspectRatio`, `max`, `min` and `withoutEnlargement`.\n\n* Add `composite` operation supporting multiple images and blend modes; deprecate `overlayWith`.\n  [#728](https://github.com/lovell/sharp/issues/728)\n\n* Add support for `pages` input option for multi-page input.\n  [#1566](https://github.com/lovell/sharp/issues/1566)\n\n* Allow Stream-based input of raw pixel data.\n  [#1579](https://github.com/lovell/sharp/issues/1579)\n\n* Add support for `page` input option to GIF and PDF.\n  [#1595](https://github.com/lovell/sharp/pull/1595)\n  [@ramiel](https://github.com/ramiel)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.22.1.md",
    "content": "---\ntitle: v0.22.1 - 25th April 2019\nslug: changelog/v0.22.1\n---\n\n* Add `modulate` operation for brightness, saturation and hue.\n  [#1601](https://github.com/lovell/sharp/pull/1601)\n  [@Goues](https://github.com/Goues)\n\n* Improve help messaging should `require(\"sharp\")` fail.\n  [#1638](https://github.com/lovell/sharp/pull/1638)\n  [@sidharthachatterjee](https://github.com/sidharthachatterjee)\n\n* Add support for Node 12.\n  [#1668](https://github.com/lovell/sharp/issues/1668)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.23.0.md",
    "content": "---\ntitle: v0.23.0 - 29th July 2019\nslug: changelog/v0.23.0\n---\n\n* Remove `overlayWith` previously deprecated in v0.22.0.\n\n* Add experimental support for HEIF images. Requires libvips compiled with libheif.\n  [#1105](https://github.com/lovell/sharp/issues/1105)\n\n* Expose libwebp `smartSubsample` and `reductionEffort` options.\n  [#1545](https://github.com/lovell/sharp/issues/1545)\n\n* Add experimental support for Worker Threads.\n  [#1558](https://github.com/lovell/sharp/issues/1558)\n\n* Use libvips' built-in CMYK and sRGB profiles when required.\n  [#1619](https://github.com/lovell/sharp/issues/1619)\n\n* Drop support for Node.js versions 6 and 11.\n  [#1674](https://github.com/lovell/sharp/issues/1674)\n\n* Expose `skipBlanks` option for tile-based output.\n  [#1687](https://github.com/lovell/sharp/pull/1687)\n  [@RaboliotTheGrey](https://github.com/RaboliotTheGrey)\n\n* Allow use of `failOnError` option with Stream-based input.\n  [#1691](https://github.com/lovell/sharp/issues/1691)\n\n* Fix rotate/extract ordering for non-90 angles.\n  [#1755](https://github.com/lovell/sharp/pull/1755)\n  [@iovdin](https://github.com/iovdin)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.23.1.md",
    "content": "---\ntitle: v0.23.1 - 26th September 2019\nslug: changelog/v0.23.1\n---\n\n* Ensure `sharp.format.vips` is present and correct (filesystem only).\n  [#1813](https://github.com/lovell/sharp/issues/1813)\n\n* Ensure invalid `width` and `height` provided as options to `resize` throw.\n  [#1817](https://github.com/lovell/sharp/issues/1817)\n\n* Allow use of 'heic' and 'heif' identifiers with `toFormat`.\n  [#1834](https://github.com/lovell/sharp/pull/1834)\n  [@jaubourg](https://github.com/jaubourg)\n\n* Add `premultiplied` option to `composite` operation.\n  [#1835](https://github.com/lovell/sharp/pull/1835)\n  [@Andargor](https://github.com/Andargor)\n\n* Allow instance reuse with differing `toBuffer` options.\n  [#1860](https://github.com/lovell/sharp/pull/1860)\n  [@RaboliotTheGrey](https://github.com/RaboliotTheGrey)\n\n* Ensure image is at least 3x3 pixels before attempting trim operation.\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.23.2.md",
    "content": "---\ntitle: v0.23.2 - 28th October 2019\nslug: changelog/v0.23.2\n---\n\n* Add `background` option to tile output operation.\n  [#1924](https://github.com/lovell/sharp/pull/1924)\n  [@neave](https://github.com/neave)\n\n* Add support for Node.js 13.\n  [#1932](https://github.com/lovell/sharp/pull/1932)\n  [@MayhemYDG](https://github.com/MayhemYDG)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.23.3.md",
    "content": "---\ntitle: v0.23.3 - 17th November 2019\nslug: changelog/v0.23.3\n---\n\n* Ensure `trim` operation supports images contained in the alpha channel.\n  [#1597](https://github.com/lovell/sharp/issues/1597)\n\n* Ensure tile `overlap` option works as expected.\n  [#1921](https://github.com/lovell/sharp/pull/1921)\n  [@rustyguts](https://github.com/rustyguts)\n\n* Allow compilation on FreeBSD and variants (broken since v0.23.0)\n  [#1952](https://github.com/lovell/sharp/pull/1952)\n  [@pouya-eghbali](https://github.com/pouya-eghbali)\n\n* Ensure `modulate` and other colour-based operations can co-exist.\n  [#1958](https://github.com/lovell/sharp/issues/1958)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.23.4.md",
    "content": "---\ntitle: v0.23.4 - 5th December 2019\nslug: changelog/v0.23.4\n---\n\n* Handle zero-length Buffer objects when using Node.js v13.2.0+.\n\n* Expose raw TIFFTAG_PHOTOSHOP metadata.\n  [#1600](https://github.com/lovell/sharp/issues/1600)\n\n* Improve thread safety by using copy-on-write when updating metadata.\n  [#1986](https://github.com/lovell/sharp/issues/1986)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.24.0.md",
    "content": "---\ntitle: v0.24.0 - 16th January 2020\nslug: changelog/v0.24.0\n---\n\n* Drop support for Node.js 8.\n  [#1910](https://github.com/lovell/sharp/issues/1910)\n\n* Drop support for undefined input where options also provided.\n  [#1768](https://github.com/lovell/sharp/issues/1768)\n\n* Move `limitInputPixels` and `sequentialRead` to input options, deprecating functions of the same name.\n\n* Expose `delay` and `loop` metadata for animated images.\n  [#1905](https://github.com/lovell/sharp/issues/1905)\n\n* Ensure correct colour output for 16-bit, 2-channel PNG input with ICC profile.\n  [#2013](https://github.com/lovell/sharp/issues/2013)\n\n* Prevent use of sequentialRead for rotate operations.\n  [#2016](https://github.com/lovell/sharp/issues/2016)\n\n* Correctly bind max width and height values when using withoutEnlargement.\n  [#2024](https://github.com/lovell/sharp/pull/2024)\n  [@BrychanOdlum](https://github.com/BrychanOdlum)\n\n* Add support for input with 16-bit RGB profile.\n  [#2037](https://github.com/lovell/sharp/issues/2037)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.24.1.md",
    "content": "---\ntitle: v0.24.1 - 15th February 2020\nslug: changelog/v0.24.1\n---\n\n* Prevent use of sequentialRead for EXIF-based rotate operation.\n  [#2042](https://github.com/lovell/sharp/issues/2042)\n\n* Ensure RGBA LZW TIFF returns correct channel count.\n  [#2064](https://github.com/lovell/sharp/issues/2064)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.25.0.md",
    "content": "---\ntitle: v0.25.0 - 7th March 2020\nslug: changelog/v0.25.0\n---\n\n* Remove `limitInputPixels` and `sequentialRead` previously deprecated in v0.24.0.\n\n* Migrate internals to N-API.\n  [#1282](https://github.com/lovell/sharp/issues/1282)\n\n* Add support for 32-bit Windows.\n  [#2088](https://github.com/lovell/sharp/issues/2088)\n\n* Ensure correct ordering of rotate-then-trim operations.\n  [#2087](https://github.com/lovell/sharp/issues/2087)\n\n* Ensure composite accepts `limitInputPixels` and `sequentialRead` input options.\n  [#2099](https://github.com/lovell/sharp/issues/2099)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.25.1.md",
    "content": "---\ntitle: v0.25.1 - 7th March 2020\nslug: changelog/v0.25.1\n---\n\n* Ensure prebuilt binaries are fetched based on N-API version.\n  [#2117](https://github.com/lovell/sharp/issues/2117)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.25.2.md",
    "content": "---\ntitle: v0.25.2 - 20th March 2020\nslug: changelog/v0.25.2\n---\n\n* Provide prebuilt binaries for Linux ARM64v8.\n\n* Add IIIF layout support to tile-based output.\n  [#2098](https://github.com/lovell/sharp/pull/2098)\n  [@edsilv](https://github.com/edsilv)\n\n* Ensure input options are consistently and correctly detected.\n  [#2118](https://github.com/lovell/sharp/issues/2118)\n\n* Ensure N-API prebuilt binaries work on RHEL7 and its derivatives.\n  [#2119](https://github.com/lovell/sharp/issues/2119)\n\n* Ensure AsyncWorker options are persisted.\n  [#2130](https://github.com/lovell/sharp/issues/2130)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.25.3.md",
    "content": "---\ntitle: v0.25.3 - 17th May 2020\nslug: changelog/v0.25.3\n---\n\n* Ensure libvips is initialised only once, improves worker thread safety.\n  [#2143](https://github.com/lovell/sharp/issues/2143)\n\n* Ensure npm platform flag is respected when copying DLLs.\n  [#2188](https://github.com/lovell/sharp/pull/2188)\n  [@dimadeveatii](https://github.com/dimadeveatii)\n\n* Allow SVG input with large inline images to be parsed.\n  [#2195](https://github.com/lovell/sharp/issues/2195)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.25.4.md",
    "content": "---\ntitle: v0.25.4 - 12th June 2020\nslug: changelog/v0.25.4\n---\n\n* Allow libvips binary location override where version is appended.\n  [#2217](https://github.com/lovell/sharp/pull/2217)\n  [@malice00](https://github.com/malice00)\n\n* Enable PNG palette when setting quality, colours, colors or dither.\n  [#2226](https://github.com/lovell/sharp/pull/2226)\n  [@romaleev](https://github.com/romaleev)\n\n* Add `level` constructor option to use a specific level of a multi-level image.\n  Expose `levels` metadata for multi-level images.\n  [#2222](https://github.com/lovell/sharp/issues/2222)\n\n* Add support for named `alpha` channel to `extractChannel` operation.\n  [#2138](https://github.com/lovell/sharp/issues/2138)\n\n* Add experimental `sharpness` calculation to `stats()` response.\n  [#2251](https://github.com/lovell/sharp/issues/2251)\n\n* Emit `warning` event for non-critical processing problems.\n  [#2032](https://github.com/lovell/sharp/issues/2032)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.26.0.md",
    "content": "---\ntitle: v0.26.0 - 25th August 2020\nslug: changelog/v0.26.0\n---\n\n* Prebuilt libvips binaries are now statically-linked and Brotli-compressed, requiring Node.js 10.16.0+.\n\n* TIFF output `squash` is replaced by `bitdepth` to reduce to 1, 2 or 4 bit.\n\n* JPEG output `quality` >= 90 no longer automatically sets `chromaSubsampling` to `4:4:4`.\n\n* Add most `dominant` colour to image `stats`.\n  [#640](https://github.com/lovell/sharp/issues/640)\n\n* Add support for animated GIF (requires \\*magick) and WebP output.\n  [#2012](https://github.com/lovell/sharp/pull/2012)\n  [@deftomat](https://github.com/deftomat)\n\n* Add support for libvips ImageMagick v7 loaders.\n  [#2258](https://github.com/lovell/sharp/pull/2258)\n  [@vouillon](https://github.com/vouillon)\n\n* Allow multi-page input via \\*magick.\n  [#2259](https://github.com/lovell/sharp/pull/2259)\n  [@vouillon](https://github.com/vouillon)\n\n* Add support to `withMetadata` for custom ICC profile.\n  [#2271](https://github.com/lovell/sharp/pull/2271)\n  [@roborourke](https://github.com/roborourke)\n\n* Ensure prebuilt binaries for ARM default to v7 when using Electron.\n  [#2292](https://github.com/lovell/sharp/pull/2292)\n  [@diegodev3](https://github.com/diegodev3)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.26.1.md",
    "content": "---\ntitle: v0.26.1 - 20th September 2020\nslug: changelog/v0.26.1\n---\n\n* Ensure correct pageHeight when verifying multi-page image dimensions.\n  [#2343](https://github.com/lovell/sharp/pull/2343)\n  [@derom](https://github.com/derom)\n\n* Allow input density range up to 100000 DPI.\n  [#2348](https://github.com/lovell/sharp/pull/2348)\n  [@stefanprobst](https://github.com/stefanprobst)\n\n* Ensure animation-related properties can be set for Stream-based input.\n  [#2369](https://github.com/lovell/sharp/pull/2369)\n  [@AcrylicShrimp](https://github.com/AcrylicShrimp)\n\n* Ensure `stats` can be calculated for 1x1 input.\n  [#2372](https://github.com/lovell/sharp/issues/2372)\n\n* Ensure animated GIF output is optimised.\n  [#2376](https://github.com/lovell/sharp/issues/2376)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.26.2.md",
    "content": "---\ntitle: v0.26.2 - 14th October 2020\nslug: changelog/v0.26.2\n---\n\n* Add support for EXR input. Requires libvips compiled with OpenEXR.\n  [#698](https://github.com/lovell/sharp/issues/698)\n\n* Ensure support for yarn v2.\n  [#2379](https://github.com/lovell/sharp/pull/2379)\n  [@jalovatt](https://github.com/jalovatt)\n\n* Add centre/center option to tile-based output.\n  [#2397](https://github.com/lovell/sharp/pull/2397)\n  [@beig](https://github.com/beig)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.26.3.md",
    "content": "---\ntitle: v0.26.3 - 16th November 2020\nslug: changelog/v0.26.3\n---\n\n* Expose libvips' affine operation.\n  [#2336](https://github.com/lovell/sharp/pull/2336)\n  [@guillevc](https://github.com/guillevc)\n\n* Fallback to tar.gz for prebuilt libvips when Brotli not available.\n  [#2412](https://github.com/lovell/sharp/pull/2412)\n  [@ascorbic](https://github.com/ascorbic)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.27.0.md",
    "content": "---\ntitle: v0.27.0 - 22nd December 2020\nslug: changelog/v0.27.0\n---\n\n* Add support for AVIF to prebuilt binaries.\n\n* Remove experimental status from `heif` output, defaults are now AVIF-centric.\n\n* Allow negative top/left offsets for composite operation.\n  [#2391](https://github.com/lovell/sharp/pull/2391)\n  [@CurosMJ](https://github.com/CurosMJ)\n\n* Ensure all platforms use fontconfig for font rendering.\n  [#2399](https://github.com/lovell/sharp/issues/2399)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.27.1.md",
    "content": "---\ntitle: v0.27.1 - 27th January 2021\nslug: changelog/v0.27.1\n---\n\n* Ensure TIFF is cast when using float predictor.\n  [#2502](https://github.com/lovell/sharp/pull/2502)\n  [@randyridge](https://github.com/randyridge)\n\n* Add support for Uint8Array and Uint8ClampedArray input.\n  [#2511](https://github.com/lovell/sharp/pull/2511)\n  [@leon](https://github.com/leon)\n\n* Revert: ensure all platforms use fontconfig for font rendering.\n  [#2515](https://github.com/lovell/sharp/issues/2515)\n\n* Expose libvips gaussnoise operation to allow creation of Gaussian noise.\n  [#2527](https://github.com/lovell/sharp/pull/2527)\n  [@alza54](https://github.com/alza54)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.27.2.md",
    "content": "---\ntitle: v0.27.2 - 22nd February 2021\nslug: changelog/v0.27.2\n---\n\n* macOS: Prevent use of globally-installed ARM64 libvips with Rosetta x64 emulation.\n  [#2460](https://github.com/lovell/sharp/issues/2460)\n\n* Linux (musl): Prevent use of prebuilt linuxmusl-x64 binaries with musl >= 1.2.0.\n  [#2570](https://github.com/lovell/sharp/issues/2570)\n\n* Improve 16-bit grey+alpha support by using libvips' `has_alpha` detection.\n  [#2569](https://github.com/lovell/sharp/issues/2569)\n\n* Allow the use of non lower case extensions with `toFormat`.\n  [#2581](https://github.com/lovell/sharp/pull/2581)\n  [@florian-busch](https://github.com/florian-busch)\n\n* Allow use of `recomb` operation with single channel input.\n  [#2584](https://github.com/lovell/sharp/issues/2584)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.28.0.md",
    "content": "---\ntitle: v0.28.0 - 29th March 2021\nslug: changelog/v0.28.0\n---\n\n* Prebuilt binaries now include mozjpeg and libimagequant (BSD 2-Clause).\n\n* Prebuilt binaries limit AVIF support to the most common 8-bit depth.\n\n* Add `mozjpeg` option to `jpeg` method, sets mozjpeg defaults.\n\n* Reduce the default PNG `compressionLevel` to the more commonly used 6.\n\n* Reduce concurrency on glibc-based Linux when using the default memory allocator to help prevent fragmentation.\n\n* Default missing edge properties of extend operation to zero.\n  [#2578](https://github.com/lovell/sharp/issues/2578)\n\n* Ensure composite does not clip top and left offsets.\n  [#2594](https://github.com/lovell/sharp/pull/2594)\n  [@SHG42](https://github.com/SHG42)\n\n* Improve error handling of network failure at install time.\n  [#2608](https://github.com/lovell/sharp/pull/2608)\n  [@abradley](https://github.com/abradley)\n\n* Ensure `@id` attribute can be set for IIIF tile-based output.\n  [#2612](https://github.com/lovell/sharp/issues/2612)\n  [@edsilv](https://github.com/edsilv)\n\n* Ensure composite replicates the correct number of tiles for centred gravities.\n  [#2626](https://github.com/lovell/sharp/issues/2626)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.28.1.md",
    "content": "---\ntitle: v0.28.1 - 5th April 2021\nslug: changelog/v0.28.1\n---\n\n* Ensure all installation errors are logged with a more obvious prefix.\n\n* Allow `withMetadata` to set and update EXIF metadata.\n  [#650](https://github.com/lovell/sharp/issues/650)\n\n* Add support for OME-TIFF Sub Image File Directories (subIFD).\n  [#2557](https://github.com/lovell/sharp/issues/2557)\n\n* Allow `ensureAlpha` to set the alpha transparency level.\n  [#2634](https://github.com/lovell/sharp/issues/2634)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.28.2.md",
    "content": "---\ntitle: v0.28.2 - 10th May 2021\nslug: changelog/v0.28.2\n---\n\n* Allow `withMetadata` to set `density`.\n  [#967](https://github.com/lovell/sharp/issues/967)\n\n* Skip shrink-on-load where one dimension <4px.\n  [#2653](https://github.com/lovell/sharp/issues/2653)\n\n* Allow escaped proxy credentials.\n  [#2664](https://github.com/lovell/sharp/pull/2664)\n  [@msalettes](https://github.com/msalettes)\n\n* Add `premultiplied` flag for raw pixel data input.\n  [#2685](https://github.com/lovell/sharp/pull/2685)\n  [@mnutt](https://github.com/mnutt)\n\n* Detect empty input and throw a helpful error.\n  [#2687](https://github.com/lovell/sharp/pull/2687)\n  [@JakobJingleheimer](https://github.com/JakobJingleheimer)\n\n* Add install-time flag to skip version compatibility checks.\n  [#2692](https://github.com/lovell/sharp/pull/2692)\n  [@xemle](https://github.com/xemle)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.28.3.md",
    "content": "---\ntitle: v0.28.3 - 24th May 2021\nslug: changelog/v0.28.3\n---\n\n* Ensure presence of libvips, vendored or global, before invoking node-gyp.\n\n* Skip shrink-on-load for multi-page WebP.\n  [#2714](https://github.com/lovell/sharp/issues/2714)\n\n* Add contrast limiting adaptive histogram equalization (CLAHE) operator.\n  [#2726](https://github.com/lovell/sharp/pull/2726)\n  [@baparham](https://github.com/baparham)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.29.0.md",
    "content": "---\ntitle: v0.29.0 - 17th August 2021\nslug: changelog/v0.29.0\n---\n\n* Drop support for Node.js 10, now requires Node.js >= 12.13.0.\n\n* Add `background` property to PNG and GIF image metadata.\n\n* Add `compression` property to HEIF image metadata.\n  [#2504](https://github.com/lovell/sharp/issues/2504)\n\n* AVIF encoding now defaults to `4:4:4` chroma subsampling.\n  [#2562](https://github.com/lovell/sharp/issues/2562)\n\n* Allow multiple platform-arch binaries in same `node_modules` installation tree.\n  [#2575](https://github.com/lovell/sharp/issues/2575)\n\n* Default to single-channel `b-w` space when `extractChannel` is used.\n  [#2658](https://github.com/lovell/sharp/issues/2658)\n\n* Allow installation directory to contain spaces (regression in v0.26.0).\n  [#2777](https://github.com/lovell/sharp/issues/2777)\n\n* Add `pipelineColourspace` operator to set the processing space.\n  [#2704](https://github.com/lovell/sharp/pull/2704)\n  [@Daiz](https://github.com/Daiz)\n\n* Allow bit depth to be set when using raw input and output.\n  [#2762](https://github.com/lovell/sharp/pull/2762)\n  [@mart-jansink](https://github.com/mart-jansink)\n\n* Allow `negate` to act only on non-alpha channels.\n  [#2808](https://github.com/lovell/sharp/pull/2808)\n  [@rexxars](https://github.com/rexxars)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.29.1.md",
    "content": "---\ntitle: v0.29.1 - 7th September 2021\nslug: changelog/v0.29.1\n---\n\n* Add `lightness` option to `modulate` operation.\n  [#2846](https://github.com/lovell/sharp/pull/2846)\n\n* Ensure correct PNG bitdepth is set based on number of colours.\n  [#2855](https://github.com/lovell/sharp/issues/2855)\n\n* Ensure background is always premultiplied when compositing.\n  [#2858](https://github.com/lovell/sharp/issues/2858)\n\n* Ensure images with P3 profiles retain full gamut.\n  [#2862](https://github.com/lovell/sharp/issues/2862)\n\n* Add support for libvips compiled with OpenJPEG.\n  [#2868](https://github.com/lovell/sharp/pull/2868)\n\n* Remove unsupported animation properties from AVIF output.\n  [#2870](https://github.com/lovell/sharp/issues/2870)\n\n* Resolve paths before comparing input/output filenames.\n  [#2878](https://github.com/lovell/sharp/pull/2878)\n  [@rexxars](https://github.com/rexxars)\n\n* Allow use of speed 9 (fastest) for HEIF encoding.\n  [#2879](https://github.com/lovell/sharp/pull/2879)\n  [@rexxars](https://github.com/rexxars)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.29.2.md",
    "content": "---\ntitle: v0.29.2 - 21st October 2021\nslug: changelog/v0.29.2\n---\n\n* Add `timeout` function to limit processing time.\n\n* Ensure `sharp.versions` is populated from vendored libvips.\n\n* Remove animation properties from single page images.\n  [#2890](https://github.com/lovell/sharp/issues/2890)\n\n* Allow use of 'tif' to select TIFF output.\n  [#2893](https://github.com/lovell/sharp/pull/2893)\n  [@erf](https://github.com/erf)\n\n* Improve error message on Windows for version conflict.\n  [#2918](https://github.com/lovell/sharp/pull/2918)\n  [@dkrnl](https://github.com/dkrnl)\n\n* Throw error rather than exit when invalid binaries detected.\n  [#2931](https://github.com/lovell/sharp/issues/2931)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.29.3.md",
    "content": "---\ntitle: v0.29.3 - 14th November 2021\nslug: changelog/v0.29.3\n---\n\n* Ensure correct dimensions when containing image resized to 1px.\n  [#2951](https://github.com/lovell/sharp/issues/2951)\n\n* Impute TIFF `xres`/`yres` from `density` provided to `withMetadata`.\n  [#2952](https://github.com/lovell/sharp/pull/2952)\n  [@mbklein](https://github.com/mbklein)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.30.0.md",
    "content": "---\ntitle: v0.30.0 - 1st February 2022\nslug: changelog/v0.30.0\n---\n\n* Add support for GIF output to prebuilt binaries.\n\n* Reduce minimum Linux ARM64v8 glibc requirement to 2.17.\n\n* Verify prebuilt binaries with a Subresource Integrity check.\n\n* Standardise WebP `effort` option name, deprecate `reductionEffort`.\n\n* Standardise HEIF `effort` option name, deprecate `speed`.\n\n* Add support for IIIF v3 tile-based output.\n\n* Expose control over CPU effort for palette-based PNG output.\n  [#2541](https://github.com/lovell/sharp/issues/2541)\n\n* Improve animated (multi-page) image resize and extract.\n  [#2789](https://github.com/lovell/sharp/pull/2789)\n  [@kleisauke](https://github.com/kleisauke)\n\n* Expose platform and architecture of vendored binaries as `sharp.vendor`.\n  [#2928](https://github.com/lovell/sharp/issues/2928)\n\n* Ensure 16-bit PNG output uses correct bitdepth.\n  [#2958](https://github.com/lovell/sharp/pull/2958)\n  [@gforge](https://github.com/gforge)\n\n* Properly emit close events for duplex streams.\n  [#2976](https://github.com/lovell/sharp/pull/2976)\n  [@driannaude](https://github.com/driannaude)\n\n* Expose `unlimited` option for SVG and PNG input, switches off safety features.\n  [#2984](https://github.com/lovell/sharp/issues/2984)\n\n* Add `withoutReduction` option to resize operation.\n  [#3006](https://github.com/lovell/sharp/pull/3006)\n  [@christopherbradleybanks](https://github.com/christopherbradleybanks)\n\n* Add `resolutionUnit` as `tiff` option and expose in metadata.\n  [#3023](https://github.com/lovell/sharp/pull/3023)\n  [@ompal-sisodiya](https://github.com/ompal-sisodiya)\n\n* Ensure rotate-then-extract works with EXIF mirroring.\n  [#3024](https://github.com/lovell/sharp/issues/3024)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.30.1.md",
    "content": "---\ntitle: v0.30.1 - 9th February 2022\nslug: changelog/v0.30.1\n---\n\n* Allow use of `toBuffer` and `toFile` on the same instance.\n  [#3044](https://github.com/lovell/sharp/issues/3044)\n\n* Skip shrink-on-load for known libjpeg rounding errors.\n  [#3066](https://github.com/lovell/sharp/issues/3066)\n  [@kleisauke](https://github.com/kleisauke)\n\n* Ensure withoutReduction does not interfere with contain/crop/embed.\n  [#3081](https://github.com/lovell/sharp/pull/3081)\n  [@kleisauke](https://github.com/kleisauke)\n\n* Ensure affine interpolator is correctly finalised.\n  [#3083](https://github.com/lovell/sharp/pull/3083)\n  [@kleisauke](https://github.com/kleisauke)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.30.2.md",
    "content": "---\ntitle: v0.30.2 - 2nd March 2022\nslug: changelog/v0.30.2\n---\n\n* Improve performance and accuracy when compositing multiple images.\n  [#2286](https://github.com/lovell/sharp/issues/2286)\n\n* Expand pkgconfig search path for wider BSD support.\n  [#3106](https://github.com/lovell/sharp/issues/3106)\n\n* Ensure Windows C++ runtime is linked statically (regression in 0.30.0).\n  [#3110](https://github.com/lovell/sharp/pull/3110)\n  [@kleisauke](https://github.com/kleisauke)\n\n* Temporarily ignore greyscale ICC profiles to workaround lcms bug.\n  [#3112](https://github.com/lovell/sharp/issues/3112)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.30.3.md",
    "content": "---\ntitle: v0.30.3 - 14th March 2022\nslug: changelog/v0.30.3\n---\n\n* Allow `sharpen` options to be provided more consistently as an Object.\n  [#2561](https://github.com/lovell/sharp/issues/2561)\n\n* Expose `x1`, `y2` and `y3` parameters of `sharpen` operation.\n  [#2935](https://github.com/lovell/sharp/issues/2935)\n\n* Prevent double unpremultiply with some composite blend modes (regression in 0.30.2).\n  [#3118](https://github.com/lovell/sharp/issues/3118)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.30.4.md",
    "content": "---\ntitle: v0.30.4 - 18th April 2022\nslug: changelog/v0.30.4\n---\n\n* Increase control over sensitivity to invalid images via `failOn`, deprecate `failOnError` (equivalent to `failOn: 'warning'`).\n\n* Ensure `create` input image has correct bit depth and colour space.\n  [#3139](https://github.com/lovell/sharp/issues/3139)\n\n* Add support for `TypedArray` input with `byteOffset` and `length`.\n  [#3146](https://github.com/lovell/sharp/pull/3146)\n  [@codepage949](https://github.com/codepage949)\n\n* Improve error message when attempting to render SVG input greater than 32767x32767.\n  [#3167](https://github.com/lovell/sharp/issues/3167)\n\n* Add missing file name to 'Input file is missing' error message.\n  [#3178](https://github.com/lovell/sharp/pull/3178)\n  [@Brodan](https://github.com/Brodan)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.30.5.md",
    "content": "---\ntitle: v0.30.5 - 23rd May 2022\nslug: changelog/v0.30.5\n---\n\n* Install: pass `PKG_CONFIG_PATH` via env rather than substitution.\n  [@dwisiswant0](https://github.com/dwisiswant0)\n\n* Add support for `--libc` flag to improve cross-platform installation.\n  [#3160](https://github.com/lovell/sharp/pull/3160)\n  [@joonamo](https://github.com/joonamo)\n\n* Allow installation of prebuilt libvips binaries from filesystem.\n  [#3196](https://github.com/lovell/sharp/pull/3196)\n  [@ankurparihar](https://github.com/ankurparihar)\n\n* Fix rotate-then-extract for EXIF orientation 2.\n  [#3218](https://github.com/lovell/sharp/pull/3218)\n  [@jakob0fischl](https://github.com/jakob0fischl)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.30.6.md",
    "content": "---\ntitle: v0.30.6 - 30th May 2022\nslug: changelog/v0.30.6\n---\n\n* Allow values for `limitInputPixels` larger than 32-bit.\n  [#3238](https://github.com/lovell/sharp/issues/3238)\n\n* Ensure brew-installed `vips` can be detected (regression in 0.30.5).\n  [#3239](https://github.com/lovell/sharp/issues/3239)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.30.7.md",
    "content": "---\ntitle: v0.30.7 - 22nd June 2022\nslug: changelog/v0.30.7\n---\n\n* Ensure tiled composition always works with outside resizing.\n  [#3227](https://github.com/lovell/sharp/issues/3227)\n\n* Allow WebP encoding effort of 0.\n  [#3261](https://github.com/lovell/sharp/pull/3261)\n  [@AlexanderTheGrey](https://github.com/AlexanderTheGrey)\n\n* Prevent upsampling via libwebp.\n  [#3267](https://github.com/lovell/sharp/pull/3267)\n  [@blacha](https://github.com/blacha)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.31.0.md",
    "content": "---\ntitle: v0.31.0 - 5th September 2022\nslug: changelog/v0.31.0\n---\n\n* Drop support for Node.js 12, now requires Node.js >= 14.15.0.\n\n* GIF output now re-uses input palette if possible. Use `reoptimise` option to generate a new palette.\n\n* Add WebP `minSize` and `mixed` options for greater control over animation frames.\n\n* Remove previously-deprecated WebP `reductionEffort` and HEIF `speed` options. Use `effort` to control these.\n\n* The `flip` and `flop` operations will now occur before the `rotate` operation.\n\n* Improve `normalise` operation with use of histogram.\n  [#200](https://github.com/lovell/sharp/issues/200)\n\n* Use combined bounding box of alpha and non-alpha channels for `trim` operation.\n  [#2166](https://github.com/lovell/sharp/issues/2166)\n\n* Add Buffer and Stream support to tile-based output.\n  [#2238](https://github.com/lovell/sharp/issues/2238)\n\n* Add input `fileSuffix` and output `alias` to `format` information.\n  [#2642](https://github.com/lovell/sharp/issues/2642)\n\n* Re-introduce support for greyscale ICC profiles (temporarily removed in 0.30.2).\n  [#3114](https://github.com/lovell/sharp/issues/3114)\n\n* Add support for WebP and PackBits `compression` options with TIFF output.\n  [#3198](https://github.com/lovell/sharp/issues/3198)\n\n* Ensure OpenSlide and FITS input works with custom libvips.\n  [#3226](https://github.com/lovell/sharp/issues/3226)\n\n* Ensure `trim` operation is a no-op when it would reduce an image to nothing.\n  [#3223](https://github.com/lovell/sharp/issues/3223)\n\n* Expose `vips_text` to create an image containing rendered text.\n  [#3252](https://github.com/lovell/sharp/pull/3252)\n  [@brahima](https://github.com/brahima)\n\n* Ensure only properties owned by the `withMetadata` EXIF Object are parsed.\n  [#3292](https://github.com/lovell/sharp/issues/3292)\n\n* Expand `linear` operation to allow use of per-channel arrays.\n  [#3303](https://github.com/lovell/sharp/pull/3303)\n  [@antonmarsden](https://github.com/antonmarsden)\n\n* Ensure the order of `rotate`, `resize` and `extend` operations is respected where possible.\n  Emit warnings when previous calls in the same pipeline will be ignored.\n  [#3319](https://github.com/lovell/sharp/issues/3319)\n\n* Ensure PNG bitdepth can be set for non-palette output.\n  [#3322](https://github.com/lovell/sharp/issues/3322)\n\n* Add trim option to provide a specific background colour.\n  [#3332](https://github.com/lovell/sharp/pull/3332)\n  [@mart-jansink](https://github.com/mart-jansink)\n\n* Ensure resized image is unpremultiplied before composite.\n  [#3334](https://github.com/lovell/sharp/issues/3334)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.31.1.md",
    "content": "---\ntitle: v0.31.1 - 29th September 2022\nslug: changelog/v0.31.1\n---\n\n* Upgrade to libvips v8.13.2 for upstream bug fixes.\n\n* Ensure `close` event occurs after `end` event for Stream-based output.\n  [#3313](https://github.com/lovell/sharp/issues/3313)\n\n* Ensure `limitInputPixels` constructor option uses uint64.\n  [#3349](https://github.com/lovell/sharp/pull/3349)\n  [@marcosc90](https://github.com/marcosc90)\n\n* Ensure auto-rotation works with shrink-on-load and extract (regression in 0.31.0).\n  [#3352](https://github.com/lovell/sharp/issues/3352)\n\n* Ensure AVIF output is always 8-bit.\n  [#3358](https://github.com/lovell/sharp/issues/3358)\n\n* Ensure greyscale images can be trimmed (regression in 0.31.0).\n  [#3386](https://github.com/lovell/sharp/issues/3386)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.31.2.md",
    "content": "---\ntitle: v0.31.2 - 4th November 2022\nslug: changelog/v0.31.2\n---\n\n* Upgrade to libvips v8.13.3 for upstream bug fixes.\n\n* Ensure manual flip, rotate, resize operation ordering (regression in 0.31.1)\n  [#3391](https://github.com/lovell/sharp/issues/3391)\n\n* Ensure auto-rotation works without resize (regression in 0.31.1)\n  [#3422](https://github.com/lovell/sharp/issues/3422)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.31.3.md",
    "content": "---\ntitle: v0.31.3 - 21st December 2022\nslug: changelog/v0.31.3\n---\n\n* Add experimental support for JPEG-XL images. Requires libvips compiled with libjxl.\n  [#2731](https://github.com/lovell/sharp/issues/2731)\n\n* Add runtime detection of V8 memory cage, ensures compatibility with Electron 21 onwards.\n  [#3384](https://github.com/lovell/sharp/issues/3384)\n\n* Expose `interFrameMaxError` and `interPaletteMaxError` GIF optimisation properties.\n  [#3401](https://github.com/lovell/sharp/issues/3401)\n\n* Allow installation on Linux with glibc patch versions e.g. Fedora 38.\n  [#3423](https://github.com/lovell/sharp/issues/3423)\n\n* Expand range of existing `sharpen` parameters to match libvips.\n  [#3427](https://github.com/lovell/sharp/issues/3427)\n\n* Prevent possible race condition awaiting metadata of Stream-based input.\n  [#3451](https://github.com/lovell/sharp/issues/3451)\n\n* Improve `extractChannel` support for 16-bit output colourspaces.\n  [#3453](https://github.com/lovell/sharp/issues/3453)\n\n* Ignore `sequentialRead` option when calculating image statistics.\n  [#3462](https://github.com/lovell/sharp/issues/3462)\n\n* Small performance improvement for operations that introduce a non-opaque background.\n  [#3465](https://github.com/lovell/sharp/issues/3465)\n\n* Ensure integral output of `linear` operation.\n  [#3468](https://github.com/lovell/sharp/issues/3468)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.32.0.md",
    "content": "---\ntitle: v0.32.0 - 24th March 2023\nslug: changelog/v0.32.0\n---\n\n* Default to using sequential rather than random access read where possible.\n\n* Replace GIF output `optimise` / `optimize` option with `reuse`.\n\n* Add `progressive` option to GIF output for interlacing.\n\n* Add `wrap` option to text image creation.\n\n* Add `formatMagick` property to metadata of images loaded via *magick.\n\n* Prefer integer (un)premultiply for faster resizing of RGBA images.\n\n* Add `ignoreIcc` input option to ignore embedded ICC profile.\n\n* Allow use of GPS (IFD3) EXIF metadata.\n  [#2767](https://github.com/lovell/sharp/issues/2767)\n\n* TypeScript definitions are now maintained and published directly, deprecating the `@types/sharp` package.\n  [#3369](https://github.com/lovell/sharp/issues/3369)\n\n* Prebuilt binaries: ensure macOS 10.13+ support, as documented.\n  [#3438](https://github.com/lovell/sharp/issues/3438)\n\n* Prebuilt binaries: prevent use of glib slice allocator, improves QEMU support.\n  [#3448](https://github.com/lovell/sharp/issues/3448)\n\n* Add focus point coordinates to output when using attention based crop.\n  [#3470](https://github.com/lovell/sharp/pull/3470)\n  [@ejoebstl](https://github.com/ejoebstl)\n\n* Expose sharp version as `sharp.versions.sharp`.\n  [#3471](https://github.com/lovell/sharp/issues/3471)\n\n* Respect `fastShrinkOnLoad` resize option for WebP input.\n  [#3516](https://github.com/lovell/sharp/issues/3516)\n\n* Reduce sharpen `sigma` maximum from 10000 to 10.\n  [#3521](https://github.com/lovell/sharp/issues/3521)\n\n* Add support for `ArrayBuffer` input.\n  [#3548](https://github.com/lovell/sharp/pull/3548)\n  [@kapouer](https://github.com/kapouer)\n\n* Add support to `extend` operation for `extendWith` to allow copy/mirror/repeat.\n  [#3556](https://github.com/lovell/sharp/pull/3556)\n  [@janaz](https://github.com/janaz)\n\n* Ensure all async JS callbacks are wrapped to help avoid possible race condition.\n  [#3569](https://github.com/lovell/sharp/issues/3569)\n\n* Prebuilt binaries: support for tile-based output temporarily removed due to licensing issue.\n  [#3581](https://github.com/lovell/sharp/issues/3581)\n\n* Add support to `normalise` for `lower` and `upper` percentiles.\n  [#3583](https://github.com/lovell/sharp/pull/3583)\n  [@LachlanNewman](https://github.com/LachlanNewman)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.32.1.md",
    "content": "---\ntitle: v0.32.1 - 27th April 2023\nslug: changelog/v0.32.1\n---\n\n* Add experimental `unflatten` operation.\n  [#3461](https://github.com/lovell/sharp/pull/3461)\n  [@antonmarsden](https://github.com/antonmarsden)\n\n* Ensure use of `flip` operation forces random access read (regression in 0.32.0).\n  [#3600](https://github.com/lovell/sharp/issues/3600)\n\n* Ensure `linear` operation works with 16-bit input (regression in 0.31.3).\n  [#3605](https://github.com/lovell/sharp/issues/3605)\n\n* Install: ensure proxy URLs are logged correctly.\n  [#3615](https://github.com/lovell/sharp/pull/3615)\n  [@TomWis97](https://github.com/TomWis97)\n\n* Ensure profile-less CMYK to CMYK roundtrip skips colourspace conversion.\n  [#3620](https://github.com/lovell/sharp/issues/3620)\n\n* Add support for `modulate` operation when using non-sRGB pipeline colourspace.\n  [#3620](https://github.com/lovell/sharp/issues/3620)\n\n* Ensure `trim` operation works with CMYK images (regression in 0.31.0).\n  [#3636](https://github.com/lovell/sharp/issues/3636)\n\n* Install: coerce libc version to semver.\n  [#3641](https://github.com/lovell/sharp/issues/3641)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.32.2.md",
    "content": "---\ntitle: v0.32.2 - 11th July 2023\nslug: changelog/v0.32.2\n---\n\n* Limit HEIF output dimensions to 16384x16384, matches libvips.\n\n* Ensure exceptions are not thrown when terminating.\n  [#3569](https://github.com/lovell/sharp/issues/3569)\n\n* Ensure the same access method is used for all inputs (regression in 0.32.0).\n  [#3669](https://github.com/lovell/sharp/issues/3669)\n\n* Improve detection of jp2 filename extensions.\n  [#3674](https://github.com/lovell/sharp/pull/3674)\n  [@bianjunjie1981](https://github.com/bianjunjie1981)\n\n* Guard use of smartcrop premultiplied option to prevent warning (regression in 0.32.1).\n  [#3710](https://github.com/lovell/sharp/issues/3710)\n\n* Prevent over-compute in affine-based rotate before resize.\n  [#3722](https://github.com/lovell/sharp/issues/3722)\n\n* Allow sequential read for EXIF-based auto-orientation.\n  [#3725](https://github.com/lovell/sharp/issues/3725)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.32.3.md",
    "content": "---\ntitle: v0.32.3 - 14th July 2023\nslug: changelog/v0.32.3\n---\n\n* Expose `preset` option for WebP output.\n  [#3639](https://github.com/lovell/sharp/issues/3639)\n\n* Ensure decoding remains sequential for all operations (regression in 0.32.2).\n  [#3725](https://github.com/lovell/sharp/issues/3725)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.32.4.md",
    "content": "---\ntitle: v0.32.4 - 21st July 2023\nslug: changelog/v0.32.4\n---\n\n* Upgrade to libvips v8.14.3 for upstream bug fixes.\n\n* Expose ability to (un)block low-level libvips operations by name.\n\n* Prebuilt binaries: restore support for tile-based output.\n  [#3581](https://github.com/lovell/sharp/issues/3581)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.32.5.md",
    "content": "---\ntitle: v0.32.5 - 15th August 2023\nslug: changelog/v0.32.5\n---\n\n* Upgrade to libvips v8.14.4 for upstream bug fixes.\n\n* TypeScript: Add missing `WebpPresetEnum` to definitions.\n  [#3748](https://github.com/lovell/sharp/pull/3748)\n  [@pilotso11](https://github.com/pilotso11)\n\n* Ensure compilation using musl v1.2.4.\n  [#3755](https://github.com/lovell/sharp/pull/3755)\n  [@kleisauke](https://github.com/kleisauke)\n\n* Ensure resize with a `fit` of `inside` respects 90/270 degree rotation.\n  [#3756](https://github.com/lovell/sharp/issues/3756)\n\n* TypeScript: Ensure `minSize` property of `WebpOptions` is boolean.\n  [#3758](https://github.com/lovell/sharp/pull/3758)\n  [@sho-xizz](https://github.com/sho-xizz)\n\n* Ensure `withMetadata` adds default sRGB profile.\n  [#3761](https://github.com/lovell/sharp/issues/3761)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.32.6.md",
    "content": "---\ntitle: v0.32.6 - 18th September 2023\nslug: changelog/v0.32.6\n---\n\n* Upgrade to libvips v8.14.5 for upstream bug fixes.\n\n* Ensure composite tile images are fully decoded (regression in 0.32.0).\n  [#3767](https://github.com/lovell/sharp/issues/3767)\n\n* Ensure `withMetadata` can add ICC profiles to RGB16 output.\n  [#3773](https://github.com/lovell/sharp/issues/3773)\n\n* Ensure `withMetadata` does not reduce 16-bit images to 8-bit (regression in 0.32.5).\n  [#3773](https://github.com/lovell/sharp/issues/3773)\n\n* TypeScript: Add definitions for block and unblock.\n  [#3799](https://github.com/lovell/sharp/pull/3799)\n  [@ldrick](https://github.com/ldrick)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.33.0.md",
    "content": "---\ntitle: v0.33.0 - 29th November 2023\nslug: changelog/v0.33.0\n---\n\n* Drop support for Node.js 14 and 16, now requires Node.js ^18.17.0 or >= 20.3.0\n\n* Prebuilt binaries distributed via npm registry and installed via package manager.\n\n* Building from source requires dependency on `node-addon-api`.\n\n* Remove `sharp.vendor`.\n\n* Partially deprecate `withMetadata()`, use `withExif()` and `withIccProfile()`.\n\n* Add experimental support for WebAssembly-based runtimes.\n  [@RReverser](https://github.com/RReverser)\n\n* Options for `trim` operation must be an Object, add new `lineArt` option.\n  [#2363](https://github.com/lovell/sharp/issues/2363)\n\n* Improve luminance of `tint` operation with weighting function.\n  [#3338](https://github.com/lovell/sharp/issues/3338)\n  [@jcupitt](https://github.com/jcupitt)\n\n* Ensure all `Error` objects contain a `stack` property.\n  [#3653](https://github.com/lovell/sharp/issues/3653)\n\n* Make `compression` option of `heif` mandatory to help reduce HEIF vs HEIC confusion.\n  [#3740](https://github.com/lovell/sharp/issues/3740)\n\n* Ensure correct interpretation of 16-bit raw input.\n  [#3808](https://github.com/lovell/sharp/issues/3808)\n\n* Add support for `miniswhite` when using TIFF output.\n  [#3812](https://github.com/lovell/sharp/pull/3812)\n  [@dnsbty](https://github.com/dnsbty)\n\n* TypeScript: add missing definition for `withMetadata` boolean.\n  [#3823](https://github.com/lovell/sharp/pull/3823)\n  [@uhthomas](https://github.com/uhthomas)\n\n* Add more fine-grained control over output metadata.\n  [#3824](https://github.com/lovell/sharp/issues/3824)\n\n* Ensure multi-page extract remains sequential.\n  [#3837](https://github.com/lovell/sharp/issues/3837)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.33.1.md",
    "content": "---\ntitle: v0.33.1 - 17th December 2023\nslug: changelog/v0.33.1\n---\n\n* Add support for Yarn Plug'n'Play filesystem layout.\n  [#3888](https://github.com/lovell/sharp/issues/3888)\n\n* Emit warning when attempting to use invalid ICC profiles.\n  [#3895](https://github.com/lovell/sharp/issues/3895)\n\n* Ensure `VIPS_NOVECTOR` environment variable is respected.\n  [#3897](https://github.com/lovell/sharp/pull/3897)\n  [@icetee](https://github.com/icetee)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.33.2.md",
    "content": "---\ntitle: v0.33.2 - 12th January 2024\nslug: changelog/v0.33.2\n---\n\n* Upgrade to libvips v8.15.1 for upstream bug fixes.\n\n* TypeScript: add definition for `keepMetadata`.\n  [#3914](https://github.com/lovell/sharp/pull/3914)\n  [@abhi0498](https://github.com/abhi0498)\n\n* Ensure `extend` operation stays sequential when copying (regression in 0.32.0).\n  [#3928](https://github.com/lovell/sharp/issues/3928)\n\n* Improve error handling for unsupported multi-page rotation.\n  [#3940](https://github.com/lovell/sharp/issues/3940)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.33.3.md",
    "content": "---\ntitle: v0.33.3 - 23rd March 2024\nslug: changelog/v0.33.3\n---\n\n* Upgrade to libvips v8.15.2 for upstream bug fixes.\n\n* Ensure `keepIccProfile` retains P3 and CMYK input profiles.\n  [#3906](https://github.com/lovell/sharp/issues/3906)\n  [#4008](https://github.com/lovell/sharp/issues/4008)\n\n* Ensure `text.wrap` property can accept `word-char` as value.\n  [#4028](https://github.com/lovell/sharp/pull/4028)\n  [@yolopunk](https://github.com/yolopunk)\n\n* Ensure `clone` takes a deep copy of existing options.\n  [#4029](https://github.com/lovell/sharp/issues/4029)\n\n* Add `bitdepth` option to `heif` output (prebuilt binaries support 8-bit only).\n  [#4036](https://github.com/lovell/sharp/pull/4036)\n  [@mertalev](https://github.com/mertalev)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.33.4.md",
    "content": "---\ntitle: v0.33.4 - 16th May 2024\nslug: changelog/v0.33.4\n---\n\n* Remove experimental status from `pipelineColourspace`.\n\n* Reduce default concurrency when musl thread over-subscription detected.\n\n* TypeScript: add missing definitions for `OverlayOptions`.\n  [#4048](https://github.com/lovell/sharp/pull/4048)\n  [@ike-gg](https://github.com/ike-gg)\n\n* Install: add advanced option to force use of a globally-installed libvips.\n  [#4060](https://github.com/lovell/sharp/issues/4060)\n\n* Expose `bilinear` resizing kernel (and interpolator).\n  [#4061](https://github.com/lovell/sharp/issues/4061)\n\n* Ensure `extend` operation stays sequential for multi-page TIFF (regression in 0.32.0).\n  [#4069](https://github.com/lovell/sharp/issues/4069)\n\n* Tighten validation of constructor `text` integer properties.\n  [#4071](https://github.com/lovell/sharp/issues/4071)\n\n* Simplify internal StaySequential logic.\n  [#4074](https://github.com/lovell/sharp/pull/4074)\n  [@kleisauke](https://github.com/kleisauke)\n\n* Ensure negate operation occurs after profile conversion.\n  [#4096](https://github.com/lovell/sharp/pull/4096)\n  [@adriaanmeuris](https://github.com/adriaanmeuris)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.33.5.md",
    "content": "---\ntitle: v0.33.5 - 16th August 2024\nslug: changelog/v0.33.5\n---\n\n* Upgrade to libvips v8.15.3 for upstream bug fixes.\n\n* Add `pageHeight` and `pages` to response of multi-page output.\n  [#3411](https://github.com/lovell/sharp/issues/3411)\n\n* Ensure option to force use of a globally-installed libvips works correctly.\n  [#4111](https://github.com/lovell/sharp/pull/4111)\n  [@project0](https://github.com/project0)\n\n* Minimise use of `engines` property to improve yarn v1 support.\n  [#4130](https://github.com/lovell/sharp/issues/4130)\n\n* Ensure `sharp.format.heif` includes only AVIF when using prebuilt binaries.\n  [#4132](https://github.com/lovell/sharp/issues/4132)\n\n* Add support to recomb operation for 4x4 matrices.\n  [#4147](https://github.com/lovell/sharp/pull/4147)\n  [@ton11797](https://github.com/ton11797)\n\n* Expose PNG text chunks as `comments` metadata.\n  [#4157](https://github.com/lovell/sharp/pull/4157)\n  [@nkeynes](https://github.com/nkeynes)\n\n* Expose optional `precision` and `minAmplitude` parameters of `blur` operation.\n  [#4168](https://github.com/lovell/sharp/pull/4168)\n  [#4172](https://github.com/lovell/sharp/pull/4172)\n  [@marcosc90](https://github.com/marcosc90)\n\n* Ensure `keepIccProfile` avoids colour transformation where possible.\n  [#4186](https://github.com/lovell/sharp/issues/4186)\n\n* TypeScript: `chromaSubsampling` metadata is optional.\n  [#4191](https://github.com/lovell/sharp/pull/4191)\n  [@DavidVaness](https://github.com/DavidVaness)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.34.0.md",
    "content": "---\ntitle: v0.34.0 - 4th April 2025\nslug: changelog/v0.34.0\n---\n\n* Breaking: Support array of input images to be joined or animated.\n  [#1580](https://github.com/lovell/sharp/issues/1580)\n\n* Breaking: Ensure `removeAlpha` removes all alpha channels.\n  [#2266](https://github.com/lovell/sharp/issues/2266)\n\n* Breaking: Non-animated GIF output defaults to no-loop instead of loop-forever.\n  [#3394](https://github.com/lovell/sharp/issues/3394)\n\n* Breaking: Support `info.size` on wide-character systems via upgrade to C++17.\n  [#3943](https://github.com/lovell/sharp/issues/3943)\n\n* Breaking: Ensure `background` metadata can be parsed by `color` package.\n  [#4090](https://github.com/lovell/sharp/issues/4090)\n\n* Add `isPalette` and `bitsPerSample` to metadata, deprecate `paletteBitDepth`.\n\n* Expose WebP `smartDeblock` output option.\n\n* Prevent use of linux-x64 binaries with v1 microarchitecture.\n\n* Add `autoOrient` operation and constructor option.\n  [#4151](https://github.com/lovell/sharp/pull/4151)\n  [@happycollision](https://github.com/happycollision)\n\n* TypeScript: Ensure channel counts use the correct range.\n  [#4197](https://github.com/lovell/sharp/pull/4197)\n  [@DavidVaness](https://github.com/DavidVaness)\n\n* Improve support for ppc64le architecture.\n  [#4203](https://github.com/lovell/sharp/pull/4203)\n  [@sumitd2](https://github.com/sumitd2)\n\n* Add `pdfBackground` constructor property.\n  [#4207](https://github.com/lovell/sharp/pull/4207)\n  [@calebmer](https://github.com/calebmer)\n\n* Expose erode and dilate operations.\n  [#4243](https://github.com/lovell/sharp/pull/4243)\n  [@qpincon](https://github.com/qpincon)\n\n* Add support for RGBE images. Requires libvips compiled with radiance support.\n  [#4316](https://github.com/lovell/sharp/pull/4316)\n  [@florentzabera](https://github.com/florentzabera)\n\n* Allow wide-gamut HEIF output at higher bitdepths.\n  [#4344](https://github.com/lovell/sharp/issues/4344)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.34.1.md",
    "content": "---\ntitle: v0.34.1 - 7th April 2025\nslug: changelog/v0.34.1\n---\n\n* TypeScript: Ensure new `autoOrient` property is optional.\n  [#4362](https://github.com/lovell/sharp/pull/4362)\n  [@styfle](https://github.com/styfle)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.34.2.md",
    "content": "---\ntitle: v0.34.2 - 20th May 2025\nslug: changelog/v0.34.2\n---\n\n* Ensure animated GIF to WebP conversion retains loop (regression in 0.34.0).\n  [#3394](https://github.com/lovell/sharp/issues/3394)\n\n* Ensure `pdfBackground` constructor property is used.\n  [#4207](https://github.com/lovell/sharp/pull/4207)\n  [#4398](https://github.com/lovell/sharp/issues/4398)\n\n* Add experimental support for prebuilt Windows ARM64 binaries.\n  [#4375](https://github.com/lovell/sharp/pull/4375)\n  [@hans00](https://github.com/hans00)\n\n* Ensure resizing with a `fit` of `contain` supports multiple alpha channels.\n  [#4382](https://github.com/lovell/sharp/issues/4382)\n\n* TypeScript: Ensure `metadata` response more closely matches reality.\n  [#4383](https://github.com/lovell/sharp/issues/4383)\n\n* TypeScript: Ensure `smartDeblock` property is included in WebP definition.\n  [#4387](https://github.com/lovell/sharp/pull/4387)\n  [@Stephen-X](https://github.com/Stephen-X)\n\n* Ensure support for wide-character filenames on Windows (regression in 0.34.0).\n  [#4391](https://github.com/lovell/sharp/issues/4391)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.34.3.md",
    "content": "---\ntitle: v0.34.3 - 10th July 2025\nslug: changelog/v0.34.3\n---\n\n* Upgrade to libvips v8.17.1 for upstream bug fixes.\n\n* Add \"Magic Kernel Sharp\" (no relation) to resizing kernels.\n\n* Deprecate top-level, format-specific constructor parameters, e.g. `subifd` becomes `tiff.subifd`.\n\n* Expose `stylesheet` and `highBitdepth` SVG input parameters.\n\n* Expose `keepDuplicateFrames` GIF output parameter.\n\n* Add support for RAW digital camera image input. Requires libvips compiled with libraw support.\n\n* Provide XMP metadata as a string, as well as a Buffer, where possible.\n\n* Add `pageHeight` option to `create` and `raw` input for animated images.\n  [#3236](https://github.com/lovell/sharp/issues/3236)\n\n* Expose JPEG 2000 `oneshot` decoder option.\n  [#4262](https://github.com/lovell/sharp/pull/4262)\n  [@mbklein](https://github.com/mbklein)\n\n* Support composite operation with non-sRGB pipeline colourspace.\n  [#4412](https://github.com/lovell/sharp/pull/4412)\n  [@kleisauke](https://github.com/kleisauke)\n\n* Add `keepXmp` and `withXmp` for control over output XMP metadata.\n  [#4416](https://github.com/lovell/sharp/pull/4416)\n  [@tpatel](https://github.com/tpatel)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.34.4.md",
    "content": "---\ntitle: v0.34.4 - 17th September 2025\nslug: changelog/v0.34.4\n---\n\n* Upgrade to libvips v8.17.2 for upstream bug fixes.\n\n* Ensure TIFF `subifd` and OpenSlide `level` input options are respected (regression in 0.34.3).\n\n* Ensure `autoOrient` occurs before non-90 angle rotation.\n  [#4425](https://github.com/lovell/sharp/issues/4425)\n\n* Ensure `autoOrient` removes existing metadata after shrink-on-load.\n  [#4431](https://github.com/lovell/sharp/issues/4431)\n\n* TypeScript: Ensure `KernelEnum` includes `linear`.\n  [#4441](https://github.com/lovell/sharp/pull/4441)\n  [@BayanBennett](https://github.com/BayanBennett)\n\n* Ensure `unlimited` flag is passed upstream when reading TIFF images.\n  [#4446](https://github.com/lovell/sharp/issues/4446)\n\n* Support Electron memory cage when reading XMP metadata (regression in 0.34.3).\n  [#4451](https://github.com/lovell/sharp/issues/4451)\n\n* Add sharp-libvips rpath for yarn v5 support.\n  [#4452](https://github.com/lovell/sharp/pull/4452)\n  [@arcanis](https://github.com/arcanis)\n"
  },
  {
    "path": "docs/src/content/docs/changelog/v0.34.5.md",
    "content": "---\ntitle: v0.34.5 - 6th November 2025\nslug: changelog/v0.34.5\n---\n\n* Upgrade to libvips v8.17.3 for upstream bug fixes.\n\n* Add experimental support for prebuilt Linux RISC-V 64-bit binaries.\n\n* Support building from source with npm v12+, deprecate `--build-from-source` flag.\n  [#4458](https://github.com/lovell/sharp/issues/4458)\n\n* Add support for BigTIFF output.\n  [#4459](https://github.com/lovell/sharp/pull/4459)\n  [@throwbi](https://github.com/throwbi)\n\n* Improve error messaging when only warnings issued.\n  [#4465](https://github.com/lovell/sharp/issues/4465)\n\n* Simplify ICC processing when retaining input profiles.\n  [#4468](https://github.com/lovell/sharp/issues/4468)\n"
  },
  {
    "path": "docs/src/content/docs/index.md",
    "content": "---\ntitle: \"High performance Node.js image processing\"\n---\n\n<img src=\"/sharp-logo.svg\" width=\"160\" height=\"160\" alt=\"sharp logo\" align=\"right\">\n\nThe typical use case for this high speed Node-API module\nis to convert large images in common formats to\nsmaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.\n\nIt can be used with all JavaScript runtimes\nthat provide support for Node-API v9, including\nNode.js >= 18.17.0, Deno and Bun.\n\nResizing an image is typically 4x-5x faster than using the\nquickest ImageMagick and GraphicsMagick settings\ndue to its use of [libvips](https://github.com/libvips/libvips).\n\nColour spaces, embedded ICC profiles and alpha transparency channels are all handled correctly.\nLanczos resampling ensures quality is not sacrificed for speed.\n\nAs well as image resizing, operations such as\nrotation, extraction, compositing and gamma correction are available.\n\nMost modern macOS, Windows and Linux systems\ndo not require any additional install or runtime dependencies.\n\n```sh frame=\"none\"\nnpm install sharp\n```\n\n## Formats\n\nThis module supports reading JPEG, PNG, WebP, GIF, AVIF, TIFF and SVG images.\n\nOutput images can be in JPEG, PNG, WebP, GIF, AVIF and TIFF formats as well as uncompressed raw pixel data.\n\nStreams, Buffer objects and the filesystem can be used for input and output.\n\nA single input Stream can be split into multiple processing pipelines and output Streams.\n\nDeep Zoom image pyramids can be generated,\nsuitable for use with \"slippy map\" tile viewers like\n[OpenSeadragon](https://github.com/openseadragon/openseadragon).\n\n## Fast\n\nThis module is powered by the blazingly fast\n[libvips](https://github.com/libvips/libvips) image processing library,\noriginally created in 1989 at Birkbeck College\nand currently maintained by a small team led by\n[John Cupitt](https://github.com/jcupitt).\n\nOnly small regions of uncompressed image data\nare held in memory and processed at a time,\ntaking full advantage of multiple CPU cores and L1/L2/L3 cache.\n\nEverything remains non-blocking thanks to _libuv_,\nno child processes are spawned and Promises/async/await are supported.\n\n## Optimal\n\nThe features of `mozjpeg` and `pngquant` can be used\nto optimise the file size of JPEG and PNG images respectively,\nwithout having to invoke separate `imagemin` processes.\n\nHuffman tables are optimised when generating JPEG output images\nwithout having to use separate command line tools like\n[jpegoptim](https://github.com/tjko/jpegoptim) and\n[jpegtran](http://jpegclub.org/jpegtran/).\n\nPNG filtering is disabled by default,\nwhich for diagrams and line art often produces the same result\nas [pngcrush](https://pmt.sourceforge.io/pngcrush/).\n\nThe file size of animated GIF output is optimised\nwithout having to use separate command line tools such as\n[gifsicle](https://www.lcdf.org/gifsicle/).\n\n## Contributing\n\nA [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md)\ncovers reporting bugs, requesting features and submitting code changes.\n\n## Licensing\n\nCopyright 2013 Lovell Fuller and others.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n"
  },
  {
    "path": "docs/src/content/docs/install.md",
    "content": "---\ntitle: Installation\n---\n\nWorks with your choice of JavaScript package manager.\n\n:::caution\nPlease ensure your package manager is configured to install optional dependencies\n:::\n\nIf a package manager lockfile must support multiple platforms,\nplease see the [cross-platform](#cross-platform) section\nto help decide which package manager is appropriate.\n\n```sh frame=\"none\"\nnpm install sharp\n```\n\n```sh frame=\"none\"\npnpm add sharp\n```\n\nWhen using `pnpm`, add `sharp` to\n[ignoredBuiltDependencies](https://pnpm.io/settings#ignoredbuiltdependencies)\nto silence warnings.\n\n```sh frame=\"none\"\nyarn add sharp\n```\n\n```sh frame=\"none\"\nbun add sharp\n```\n\n```sh frame=\"none\"\ndeno add --quiet npm:sharp\ndeno run --allow-env --allow-ffi --allow-read --allow-sys ...\n```\n\n## Prerequisites\n\n* Node-API v9 compatible runtime e.g. Node.js ^18.17.0 or >=20.3.0.\n\n## Prebuilt binaries\n\nReady-compiled sharp and libvips binaries are provided for use on the most common platforms:\n\n* macOS x64 (>= 10.15)\n* macOS ARM64\n* Linux ARM (glibc >= 2.31)\n* Linux ARM64 (glibc >= 2.26, musl >= 1.2.2)\n* Linux RISC-V 64-bit (glibc >= 2.41)\n* Linux ppc64 (glibc >= 2.36)\n* Linux s390x (glibc >= 2.36)\n* Linux x64 (glibc >= 2.26, musl >= 1.2.2, CPU with SSE4.2)\n* Windows x64\n* Windows x86\n* Windows ARM64 (experimental, CPU with ARMv8.4 required for all features)\n\nThis provides support for the\nJPEG, PNG, WebP, AVIF (limited to 8-bit depth), TIFF, GIF and SVG (input) image formats.\n\n## Cross-platform\n\nAt install time, package managers will automatically select prebuilt binaries\nfor the current OS platform and CPU architecture, where available.\n\nSome package managers support multiple platforms and architectures\nwithin the same installation tree and/or using the same lockfile.\n\n### npm v10+\n\n:::caution\nnpm `package-lock.json` files shared by multiple platforms can cause installation problems due to [npm bug #4828](https://github.com/npm/cli/issues/4828)\n:::\n\nProvides limited support via `--os`, `--cpu` and `--libc` flags.\n\nTo support macOS with Intel x64 and ARM64 CPUs:\n```sh frame=\"none\"\nnpm install --cpu=x64 --os=darwin sharp\nnpm install --cpu=arm64 --os=darwin sharp\n```\n\nWhen the cross-target is Linux, the C standard library must be specified.\n\nTo support glibc (e.g. Debian) and musl (e.g. Alpine) Linux with Intel x64 CPUs:\n```sh frame=\"none\"\nnpm install --cpu=x64 --os=linux --libc=glibc sharp\nnpm install --cpu=x64 --os=linux --libc=musl sharp\n```\n\n### yarn v3+\n\nUse the [supportedArchitectures](https://yarnpkg.com/configuration/yarnrc#supportedArchitectures) configuration.\n\n### pnpm v8+\n\nUse the [supportedArchitectures](https://pnpm.io/settings#supportedarchitectures) configuration.\n\n## Custom libvips\n\nTo use a custom, globally-installed version of libvips instead of the provided binaries,\nmake sure it is at least the version listed under `config.libvips` in the `package.json` file\nand that it can be located using `pkg-config --modversion vips-cpp`.\n\nFor help compiling libvips and its dependencies, please see\n[building libvips from source](https://www.libvips.org/install.html#building-libvips-from-source).\n\nThe use of a globally-installed libvips is unsupported on Windows\nand on macOS when running Node.js under Rosetta.\n\n## Building from source\n\nThis module will be compiled from source when:\n\n* a globally-installed libvips is detected, or\n* using `npm explore sharp -- npm run build`, or\n* using the deprecated `npm run --build-from-source` at `npm install` time.\n\nThe logic to detect a globally-installed libvips can be skipped by setting the\n`SHARP_IGNORE_GLOBAL_LIBVIPS` (never try to use it) or\n`SHARP_FORCE_GLOBAL_LIBVIPS` (always try to use it, even when missing or outdated)\nenvironment variables.\n\nBuilding from source requires:\n\n* C++17 compiler\n* [node-addon-api](https://www.npmjs.com/package/node-addon-api) version 7+\n* [node-gyp](https://github.com/nodejs/node-gyp#installation) version 9+ and its dependencies\n\nThere is an install-time check for these dependencies.\nIf `node-addon-api` or `node-gyp` cannot be found, try adding them via:\n\n```sh frame=\"none\"\nnpm install --save node-addon-api node-gyp\n```\n\nWhen using `pnpm`, you may need to add `sharp` to\n[onlyBuiltDependencies](https://pnpm.io/settings#onlybuiltdependencies)\nto ensure the installation script can be run.\n\nFor cross-compiling, the `--platform`, `--arch` and `--libc` npm flags\n(or the `npm_config_platform`, `npm_config_arch` and `npm_config_libc` environment variables)\ncan be used to configure the target environment.\n\n## WebAssembly\n\nExperimental support is provided for runtime environments that provide\nmulti-threaded Wasm via Workers.\n\nUse in web browsers is unsupported.\n\nNative text rendering is unsupported.\n\n[Tile-based output](/api-output#tile) is unsupported.\n\n```sh frame=\"none\"\nnpm install --cpu=wasm32 sharp\n```\n\n## FreeBSD\n\nThe `vips` package must be installed before `npm install` is run,\nas well as the additional [building from source](#building-from-source) dependencies.\n\n```sh frame=\"none\"\npkg install -y pkgconf vips\n```\n\n```sh frame=\"none\"\ncd /usr/ports/graphics/vips/ && make install clean\n```\n\n## Linux memory allocator\n\nThe default memory allocator on most glibc-based Linux systems\n(e.g. Debian, Red Hat) is unsuitable for long-running, multi-threaded\nprocesses that involve lots of small memory allocations.\n\nFor this reason, by default, sharp will limit the use of thread-based\n[concurrency](/api-utility#concurrency) when the glibc allocator is\ndetected at runtime.\n\nTo help avoid fragmentation and improve performance on these systems,\nthe use of an alternative memory allocator such as\n[jemalloc](https://github.com/jemalloc/jemalloc) is recommended.\n\nThose using musl-based Linux (e.g. Alpine) and non-Linux systems are\nunaffected.\n\n## AWS Lambda\n\nThe `node_modules` directory of the\n[deployment package](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html)\nmust include binaries for either the linux-x64 or linux-arm64 platforms\ndepending on the chosen architecture.\n\nWhen building your deployment package on a machine that differs from the target architecture,\nsee the [cross-platform](#cross-platform) section to help decide which package manager is appropriate\nand how to configure it.\n\nSome package managers use symbolic links\nbut AWS Lambda does not support these within deployment packages.\n\nTo get the best performance select the largest memory available.\nA 1536 MB function provides ~12x more CPU time than a 128 MB function.\n\nWhen integrating with AWS API Gateway, ensure it is configured with the relevant\n[binary media types](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html).\n\n## Bundlers\n\n### webpack\n\nEnsure sharp is excluded from bundling via the\n[externals](https://webpack.js.org/configuration/externals/)\nconfiguration.\n\n```js frame=\"none\"\nexternals: {\n  'sharp': 'commonjs sharp'\n}\n```\n\n### esbuild\n\nEnsure sharp is excluded from bundling via the\n[external](https://esbuild.github.io/api/#external)\nconfiguration.\n\n```js frame=\"none\"\nbuildSync({\n  entryPoints: ['app.js'],\n  bundle: true,\n  platform: 'node',\n  external: ['sharp'],\n})\n```\n\n```sh frame=\"none\"\nesbuild app.js --bundle --platform=node --external:sharp\n```\n\nFor `serverless-esbuild`, ensure platform-specific binaries are installed\nvia the `serverless.yml` configuration.\n\n```yaml frame=\"none\"\ncustom:\n  esbuild:\n    external:\n      - sharp\n    packagerOptions:\n      scripts:\n        - npm install --os=linux --cpu=x64 sharp\n```\n\n### electron\n\n#### electron-builder\n\nEnsure `sharp` is unpacked from the ASAR archive file using the\n[asarUnpack](https://www.electron.build/app-builder-lib.interface.platformspecificbuildoptions#asarunpack)\noption.\n\n```json frame=\"none\"\n{\n  \"build\": {\n    \"asar\": true,\n    \"asarUnpack\": [\n      \"**/node_modules/sharp/**/*\",\n      \"**/node_modules/@img/**/*\"\n    ]\n  }\n}\n```\n\n#### electron-forge\n\nEnsure `sharp` is unpacked from the ASAR archive file using the\n[unpack](https://js.electronforge.io/interfaces/_electron_forge_maker_squirrel.InternalOptions.Options.html#asar)\noption.\n\n```json frame=\"none\"\n{\n  \"packagerConfig\": {\n    \"asar\": {\n      \"unpack\": \"**/node_modules/{sharp,@img}/**/*\"\n    }\n  }\n}\n```\n\nWhen using `electron-forge` with [Webpack](#webpack),\nyou may also need to add\n[forge-externals-plugin](https://www.npmjs.com/package/@timfish/forge-externals-plugin).\n\n### vite\n\nEnsure `sharp` is excluded from bundling via the\n[build.rollupOptions](https://vitejs.dev/config/build-options.html)\nconfiguration.\n\n```js frame=\"none\"\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n  build: {\n    rollupOptions: {\n      external: [\n        \"sharp\"\n      ]\n    }\n  }\n});\n```\n\n## TypeScript\n\nTypeScript definitions are published as part of\nthe `sharp` package from v0.32.0.\n\nPreviously these were available via the `@types/sharp` package,\nwhich is now deprecated.\n\nWhen using Typescript, please ensure `devDependencies` includes\nthe `@types/node` package.\n\n## Fonts\n\nWhen creating text images or rendering SVG images that contain text elements,\n`fontconfig` is used to find the relevant fonts.\n\nOn Windows and macOS systems, all system fonts are available for use.\n\nOn macOS systems using Homebrew, you may need to set the\n`PANGOCAIRO_BACKEND` environment variable to a value of `fontconfig`\nto ensure it is used for font discovery instead of Core Text.\n\nOn Linux systems, fonts that include the relevant\n[`fontconfig` configuration](https://www.freedesktop.org/software/fontconfig/fontconfig-user.html)\nwhen installed via package manager are available for use.\n\nIf `fontconfig` configuration is not found, the following error will occur:\n```\nFontconfig error: Cannot load default config file\n```\n\nIn serverless environments where there is no control over font packages,\nuse the `FONTCONFIG_PATH` environment variable to point to a custom location.\n\nEmbedded SVG fonts are unsupported.\n\n## Known conflicts\n\n### Canvas and Windows\n\nIf both `canvas` and `sharp` modules are used in the same Windows process, the following error may occur:\n```\nThe specified procedure could not be found.\n```\n"
  },
  {
    "path": "docs/src/content/docs/performance.md",
    "content": "---\ntitle: Performance\n---\n\n## Parallelism and concurrency\n\nNode.js uses a libuv-managed thread pool when processing asynchronous calls to native modules such as sharp.\n\nThe maximum number of images that sharp can process in parallel is controlled by libuv's\n[`UV_THREADPOOL_SIZE`](https://nodejs.org/api/cli.html#uv_threadpool_sizesize)\nenvironment variable, which defaults to 4.\n\nWhen using more than 4 physical CPU cores, set this environment variable\nbefore the Node.js process starts to increase the thread pool size.\n\n```sh frame=\"none\"\nexport UV_THREADPOOL_SIZE=\"$(lscpu -p | egrep -v \"^#\" | sort -u -t, -k 2,4 | wc -l)\"\n```\n\nlibvips uses a shared thread pool to avoid the overhead of spawning new threads.\nThe size of this thread pool will grow on demand and shrink when idle.\n\nThe default number of threads used to concurrently process each image is the same as the number of CPU cores,\nexcept when using glibc-based Linux without jemalloc, where the default is `1` to help reduce memory fragmentation.\n\nUse [`sharp.concurrency()`](/api-utility/#concurrency) to manage the number of threads per image.\n\nTo reduce memory fragmentation when using the default Linux glibc memory allocator, set the\n[`MALLOC_ARENA_MAX`](https://sourceware.org/glibc/manual/latest/html_node/Memory-Allocation-Tunables.html)\nenvironment variable before the Node.js process starts to reduce the number of memory pools.\n\n```sh frame=\"none\"\nexport MALLOC_ARENA_MAX=\"2\"\n```\n\n## Benchmark\n\nA test to benchmark the performance of this module relative to alternatives.\n\nGreater libvips performance can be expected with caching enabled (default)\nand using 8+ core machines, especially those with larger L1/L2 CPU caches.\n\nThe I/O limits of the relevant (de)compression library will generally determine maximum throughput.\n\n### Contenders\n\n- [jimp](https://www.npmjs.com/package/jimp) v1.6.0 - Image processing in pure JavaScript.\n- [imagemagick](https://www.npmjs.com/package/imagemagick) v0.1.3 - Supports filesystem only and \"_has been unmaintained for a long time_\".\n- [gm](https://www.npmjs.com/package/gm) v1.25.1 - Fully featured wrapper around GraphicsMagick's `gm` command line utility, but \"_has been sunset_\".\n- sharp v0.34.3 / libvips v8.17.0 - Caching within libvips disabled to ensure a fair comparison.\n\n### Environment\n\n#### AMD64\n\n- AWS EC2 us-west-2 [c7a.xlarge](https://aws.amazon.com/ec2/instance-types/c7a/) (4x AMD EPYC 9R14)\n- Ubuntu 25.04\n- Node.js 24.3.0\n\n#### ARM64\n\n- AWS EC2 us-west-2 [c8g.xlarge](https://aws.amazon.com/ec2/instance-types/c8g/) (4x ARM Graviton4)\n- Ubuntu 25.04\n- Node.js 24.3.0\n\n### Task: JPEG\n\nDecompress a 2725x2225 JPEG image,\nresize to 720x588 using Lanczos 3 resampling (where available),\nthen compress to JPEG at a \"quality\" setting of 80.\n\nNote: jimp does not support Lanczos 3, bicubic resampling used instead.\n\n#### Results: JPEG (AMD64)\n\n| Package     | I/O    | Ops/sec | Speed-up |\n| :---------- | :----- | ------: | -------: |\n| jimp        | buffer |    2.40 |      1.0 |\n| jimp        | file   |    2.60 |      1.1 |\n| imagemagick | file   |    9.70 |      4.0 |\n| gm          | buffer |   11.60 |      4.8 |\n| gm          | file   |   11.72 |      4.9 |\n| sharp       | stream |   59.40 |     24.8 |\n| sharp       | file   |   62.67 |     26.1 |\n| sharp       | buffer |   64.42 |     26.8 |\n\n#### Results: JPEG (ARM64)\n\n| Package     | I/O    | Ops/sec | Speed-up |\n| :---------- | :----- | ------: | -------: |\n| jimp        | buffer |    2.24 |      1.0 |\n| jimp        | file   |    2.47 |      1.1 |\n| imagemagick | file   |   10.42 |      4.7 |\n| gm          | buffer |   12.80 |      5.7 |\n| gm          | file   |   12.88 |      5.7 |\n| sharp       | stream |   45.58 |     20.3 |\n| sharp       | file   |   47.99 |     21.4 |\n| sharp       | buffer |   49.20 |     22.0 |\n\n### Task: PNG\n\nDecompress a 2048x1536 RGBA PNG image,\npremultiply the alpha channel,\nresize to 720x540 using Lanczos 3 resampling (where available),\nunpremultiply then compress as PNG with a \"default\" zlib compression level of 6\nand without adaptive filtering.\n\nNote: jimp does not support premultiply/unpremultiply.\n\n#### Results: PNG (AMD64)\n\n| Package     | I/O    | Ops/sec | Speed-up |\n| :---------- | :----- | ------: | -------: |\n| imagemagick | file   |    6.06 |      1.0 |\n| gm          | file   |    8.44 |      1.4 |\n| jimp        | buffer |   10.98 |      1.8 |\n| sharp       | file   |   28.26 |      4.7 |\n| sharp       | buffer |   28.70 |      4.7 |\n\n#### Results: PNG (ARM64)\n\n| Package     | I/O    | Ops/sec | Speed-up |\n| :---------- | :----- | ------: | -------: |\n| imagemagick | file   |    7.09 |      1.0 |\n| gm          | file   |    8.93 |      1.3 |\n| jimp        | buffer |   10.28 |      1.5 |\n| sharp       | file   |   23.81 |      3.4 |\n| sharp       | buffer |   24.19 |      3.4 |\n\n## Running the benchmark test\n\nRequires Docker.\n\n```sh frame=\"none\"\ngit clone https://github.com/lovell/sharp.git\ncd sharp/test/bench\n./run-with-docker.sh\n```\n"
  },
  {
    "path": "docs/src/content.config.ts",
    "content": "import { defineCollection } from 'astro:content';\nimport { docsLoader } from '@astrojs/starlight/loaders';\nimport { docsSchema } from '@astrojs/starlight/schema';\nimport { autoSidebarLoader } from 'starlight-auto-sidebar/loader'\nimport { autoSidebarSchema } from 'starlight-auto-sidebar/schema'\n\nexport const collections = {\n\tdocs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),\n\tautoSidebar: defineCollection({ loader: autoSidebarLoader(), schema: autoSidebarSchema() })\n};\n"
  },
  {
    "path": "docs/src/styles/custom.css",
    "content": "@view-transition {\n  navigation: auto;\n}\n\n:root {\n  --sl-content-width: 60rem;\n  --sl-color-accent-low: #072d00;\n  --sl-color-accent: #247f00;\n  --sl-color-accent-high: #aad7a0;\n  --sl-color-white: #ffffff;\n  --sl-color-gray-1: #eaf0e8;\n  --sl-color-gray-2: #c5cdc3;\n  --sl-color-gray-3: #99a796;\n  --sl-color-gray-4: #4f5c4d;\n  --sl-color-gray-5: #303c2d;\n  --sl-color-gray-6: #1f2a1c;\n  --sl-color-black: #151a13;\n}\n\n:root[data-theme=\"light\"] {\n  --sl-color-accent-low: #c0e2b8;\n  --sl-color-accent: #165800;\n  --sl-color-accent-high: #0d3e00;\n  --sl-color-white: #151a13;\n  --sl-color-gray-1: #1f2a1c;\n  --sl-color-gray-2: #303c2d;\n  --sl-color-gray-3: #4f5c4d;\n  --sl-color-gray-4: #82907f;\n  --sl-color-gray-5: #bdc4bb;\n  --sl-color-gray-6: #eaf0e8;\n  --sl-color-gray-7: #f4f7f3;\n  --sl-color-black: #ffffff;\n}\n\nblockquote {\n  background-color: var(--sl-color-gray-6);\n  padding: 1rem;\n}\n\n.site-title::after {\n  content: \"High performance Node.js image processing\";\n  color: var(--sl-color-text);\n  font-size: var(--sl-text-sm);\n  padding-top: 0.3rem;\n}\n"
  },
  {
    "path": "docs/tsconfig.json",
    "content": "{\n  \"extends\": \"astro/tsconfigs/strict\",\n  \"include\": [\".astro/types.d.ts\", \"**/*\"],\n  \"exclude\": [\"dist\"]\n}\n"
  },
  {
    "path": "install/build.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst {\n  useGlobalLibvips,\n  globalLibvipsVersion,\n  log,\n  spawnRebuild,\n} = require('../lib/libvips');\n\nlog('Attempting to build from source via node-gyp');\nlog('See https://sharp.pixelplumbing.com/install#building-from-source');\n\ntry {\n  const addonApi = require('node-addon-api');\n  log(`Found node-addon-api ${addonApi.version || ''}`);\n} catch (_err) {\n  log('Please add node-addon-api to your dependencies');\n  process.exit(1);\n}\ntry {\n  const gyp = require('node-gyp');\n  log(`Found node-gyp ${gyp().version}`);\n} catch (_err) {\n  log('Please add node-gyp to your dependencies');\n  process.exit(1);\n}\n\nif (useGlobalLibvips(log)) {\n  log(`Detected globally-installed libvips v${globalLibvipsVersion()}`);\n}\n\nconst status = spawnRebuild();\nif (status !== 0) {\n  process.exit(status);\n}\n"
  },
  {
    "path": "install/check.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\ntry {\n  const { useGlobalLibvips } = require('../lib/libvips');\n  if (useGlobalLibvips() || process.env.npm_config_build_from_source) {\n    process.exit(1);\n  }\n} catch (err) {\n  const summary = err.message.split(/\\n/).slice(0, 1);\n  console.log(`sharp: skipping install check: ${summary}`);\n}\n"
  },
  {
    "path": "lib/channel.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst is = require('./is');\n\n/**\n * Boolean operations for bandbool.\n * @private\n */\nconst bool = {\n  and: 'and',\n  or: 'or',\n  eor: 'eor'\n};\n\n/**\n * Remove alpha channels, if any. This is a no-op if the image does not have an alpha channel.\n *\n * See also {@link /api-operation/#flatten flatten}.\n *\n * @example\n * sharp('rgba.png')\n *   .removeAlpha()\n *   .toFile('rgb.png', function(err, info) {\n *     // rgb.png is a 3 channel image without an alpha channel\n *   });\n *\n * @returns {Sharp}\n */\nfunction removeAlpha () {\n  this.options.removeAlpha = true;\n  return this;\n}\n\n/**\n * Ensure the output image has an alpha transparency channel.\n * If missing, the added alpha channel will have the specified\n * transparency level, defaulting to fully-opaque (1).\n * This is a no-op if the image already has an alpha channel.\n *\n * @since 0.21.2\n *\n * @example\n * // rgba.png will be a 4 channel image with a fully-opaque alpha channel\n * await sharp('rgb.jpg')\n *   .ensureAlpha()\n *   .toFile('rgba.png')\n *\n * @example\n * // rgba is a 4 channel image with a fully-transparent alpha channel\n * const rgba = await sharp(rgb)\n *   .ensureAlpha(0)\n *   .toBuffer();\n *\n * @param {number} [alpha=1] - alpha transparency level (0=fully-transparent, 1=fully-opaque)\n * @returns {Sharp}\n * @throws {Error} Invalid alpha transparency level\n */\nfunction ensureAlpha (alpha) {\n  if (is.defined(alpha)) {\n    if (is.number(alpha) && is.inRange(alpha, 0, 1)) {\n      this.options.ensureAlpha = alpha;\n    } else {\n      throw is.invalidParameterError('alpha', 'number between 0 and 1', alpha);\n    }\n  } else {\n    this.options.ensureAlpha = 1;\n  }\n  return this;\n}\n\n/**\n * Extract a single channel from a multi-channel image.\n *\n * The output colourspace will be either `b-w` (8-bit) or `grey16` (16-bit).\n *\n * @example\n * // green.jpg is a greyscale image containing the green channel of the input\n * await sharp(input)\n *   .extractChannel('green')\n *   .toFile('green.jpg');\n *\n * @example\n * // red1 is the red value of the first pixel, red2 the second pixel etc.\n * const [red1, red2, ...] = await sharp(input)\n *   .extractChannel(0)\n *   .raw()\n *   .toBuffer();\n *\n * @param {number|string} channel - zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`.\n * @returns {Sharp}\n * @throws {Error} Invalid channel\n */\nfunction extractChannel (channel) {\n  const channelMap = { red: 0, green: 1, blue: 2, alpha: 3 };\n  if (Object.keys(channelMap).includes(channel)) {\n    channel = channelMap[channel];\n  }\n  if (is.integer(channel) && is.inRange(channel, 0, 4)) {\n    this.options.extractChannel = channel;\n  } else {\n    throw is.invalidParameterError('channel', 'integer or one of: red, green, blue, alpha', channel);\n  }\n  return this;\n}\n\n/**\n * Join one or more channels to the image.\n * The meaning of the added channels depends on the output colourspace, set with `toColourspace()`.\n * By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.\n * Channel ordering follows vips convention:\n * - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.\n * - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.\n *\n * Buffers may be any of the image formats supported by sharp.\n * For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor.\n *\n * @param {Array<string|Buffer>|string|Buffer} images - one or more images (file paths, Buffers).\n * @param {Object} options - image options, see `sharp()` constructor.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction joinChannel (images, options) {\n  if (Array.isArray(images)) {\n    images.forEach(function (image) {\n      this.options.joinChannelIn.push(this._createInputDescriptor(image, options));\n    }, this);\n  } else {\n    this.options.joinChannelIn.push(this._createInputDescriptor(images, options));\n  }\n  return this;\n}\n\n/**\n * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.\n *\n * @example\n * sharp('3-channel-rgb-input.png')\n *   .bandbool(sharp.bool.and)\n *   .toFile('1-channel-output.png', function (err, info) {\n *     // The output will be a single channel image where each pixel `P = R & G & B`.\n *     // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]`\n *     // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`.\n *   });\n *\n * @param {string} boolOp - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction bandbool (boolOp) {\n  if (is.string(boolOp) && is.inArray(boolOp, ['and', 'or', 'eor'])) {\n    this.options.bandBoolOp = boolOp;\n  } else {\n    throw is.invalidParameterError('boolOp', 'one of: and, or, eor', boolOp);\n  }\n  return this;\n}\n\n/**\n * Decorate the Sharp prototype with channel-related functions.\n * @module Sharp\n * @private\n */\nmodule.exports = (Sharp) => {\n  Object.assign(Sharp.prototype, {\n    // Public instance functions\n    removeAlpha,\n    ensureAlpha,\n    extractChannel,\n    joinChannel,\n    bandbool\n  });\n  // Class attributes\n  Sharp.bool = bool;\n};\n"
  },
  {
    "path": "lib/colour.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst color = require('@img/colour');\nconst is = require('./is');\n\n/**\n * Colourspaces.\n * @private\n */\nconst colourspace = {\n  multiband: 'multiband',\n  'b-w': 'b-w',\n  bw: 'b-w',\n  cmyk: 'cmyk',\n  srgb: 'srgb'\n};\n\n/**\n * Tint the image using the provided colour.\n * An alpha channel may be present and will be unchanged by the operation.\n *\n * @example\n * const output = await sharp(input)\n *   .tint({ r: 255, g: 240, b: 16 })\n *   .toBuffer();\n *\n * @param {string|Object} tint - Parsed by the [color](https://www.npmjs.org/package/color) module.\n * @returns {Sharp}\n * @throws {Error} Invalid parameter\n */\nfunction tint (tint) {\n  this._setBackgroundColourOption('tint', tint);\n  return this;\n}\n\n/**\n * Convert to 8-bit greyscale; 256 shades of grey.\n * This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.\n * By default the output image will be web-friendly sRGB and contain three (identical) colour channels.\n * This may be overridden by other sharp operations such as `toColourspace('b-w')`,\n * which will produce an output image containing one colour channel.\n * An alpha channel may be present, and will be unchanged by the operation.\n *\n * @example\n * const output = await sharp(input).greyscale().toBuffer();\n *\n * @param {Boolean} [greyscale=true]\n * @returns {Sharp}\n */\nfunction greyscale (greyscale) {\n  this.options.greyscale = is.bool(greyscale) ? greyscale : true;\n  return this;\n}\n\n/**\n * Alternative spelling of `greyscale`.\n * @param {Boolean} [grayscale=true]\n * @returns {Sharp}\n */\nfunction grayscale (grayscale) {\n  return this.greyscale(grayscale);\n}\n\n/**\n * Set the pipeline colourspace.\n *\n * The input image will be converted to the provided colourspace at the start of the pipeline.\n * All operations will use this colourspace before converting to the output colourspace,\n * as defined by {@link #tocolourspace toColourspace}.\n *\n * @since 0.29.0\n *\n * @example\n * // Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB.\n * await sharp(input)\n *  .pipelineColourspace('rgb16')\n *  .toColourspace('srgb')\n *  .toFile('16bpc-pipeline-to-8bpc-output.png')\n *\n * @param {string} [colourspace] - pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://www.libvips.org/API/current/enum.Interpretation.html)\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction pipelineColourspace (colourspace) {\n  if (!is.string(colourspace)) {\n    throw is.invalidParameterError('colourspace', 'string', colourspace);\n  }\n  this.options.colourspacePipeline = colourspace;\n  return this;\n}\n\n/**\n * Alternative spelling of `pipelineColourspace`.\n * @param {string} [colorspace] - pipeline colorspace.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction pipelineColorspace (colorspace) {\n  return this.pipelineColourspace(colorspace);\n}\n\n/**\n * Set the output colourspace.\n * By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.\n *\n * @example\n * // Output 16 bits per pixel RGB\n * await sharp(input)\n *  .toColourspace('rgb16')\n *  .toFile('16-bpp.png')\n *\n * @param {string} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/enum.Interpretation.html)\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction toColourspace (colourspace) {\n  if (!is.string(colourspace)) {\n    throw is.invalidParameterError('colourspace', 'string', colourspace);\n  }\n  this.options.colourspace = colourspace;\n  return this;\n}\n\n/**\n * Alternative spelling of `toColourspace`.\n * @param {string} [colorspace] - output colorspace.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction toColorspace (colorspace) {\n  return this.toColourspace(colorspace);\n}\n\n/**\n * Create a RGBA colour array from a given value.\n * @private\n * @param {string|Object} value\n * @throws {Error} Invalid value\n */\nfunction _getBackgroundColourOption (value) {\n  if (\n    is.object(value) ||\n    (is.string(value) && value.length >= 3 && value.length <= 200)\n  ) {\n    const colour = color(value);\n    return [\n      colour.red(),\n      colour.green(),\n      colour.blue(),\n      Math.round(colour.alpha() * 255)\n    ];\n  } else {\n    throw is.invalidParameterError('background', 'object or string', value);\n  }\n}\n\n/**\n * Update a colour attribute of the this.options Object.\n * @private\n * @param {string} key\n * @param {string|Object} value\n * @throws {Error} Invalid value\n */\nfunction _setBackgroundColourOption (key, value) {\n  if (is.defined(value)) {\n    this.options[key] = _getBackgroundColourOption(value);\n  }\n}\n\n/**\n * Decorate the Sharp prototype with colour-related functions.\n * @module Sharp\n * @private\n */\nmodule.exports = (Sharp) => {\n  Object.assign(Sharp.prototype, {\n    // Public\n    tint,\n    greyscale,\n    grayscale,\n    pipelineColourspace,\n    pipelineColorspace,\n    toColourspace,\n    toColorspace,\n    // Private\n    _getBackgroundColourOption,\n    _setBackgroundColourOption\n  });\n  // Class attributes\n  Sharp.colourspace = colourspace;\n  Sharp.colorspace = colourspace;\n};\n"
  },
  {
    "path": "lib/composite.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst is = require('./is');\n\n/**\n * Blend modes.\n * @member\n * @private\n */\nconst blend = {\n  clear: 'clear',\n  source: 'source',\n  over: 'over',\n  in: 'in',\n  out: 'out',\n  atop: 'atop',\n  dest: 'dest',\n  'dest-over': 'dest-over',\n  'dest-in': 'dest-in',\n  'dest-out': 'dest-out',\n  'dest-atop': 'dest-atop',\n  xor: 'xor',\n  add: 'add',\n  saturate: 'saturate',\n  multiply: 'multiply',\n  screen: 'screen',\n  overlay: 'overlay',\n  darken: 'darken',\n  lighten: 'lighten',\n  'colour-dodge': 'colour-dodge',\n  'color-dodge': 'colour-dodge',\n  'colour-burn': 'colour-burn',\n  'color-burn': 'colour-burn',\n  'hard-light': 'hard-light',\n  'soft-light': 'soft-light',\n  difference: 'difference',\n  exclusion: 'exclusion'\n};\n\n/**\n * Composite image(s) over the processed (resized, extracted etc.) image.\n *\n * The images to composite must be the same size or smaller than the processed image.\n * If both `top` and `left` options are provided, they take precedence over `gravity`.\n *\n * Other operations in the same processing pipeline (e.g. resize, rotate, flip,\n * flop, extract) will always be applied to the input image before composition.\n *\n * The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,\n * `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`,\n * `xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`,\n * `colour-dodge`, `color-dodge`, `colour-burn`,`color-burn`,\n * `hard-light`, `soft-light`, `difference`, `exclusion`.\n *\n * More information about blend modes can be found at\n * https://www.libvips.org/API/current/enum.BlendMode.html\n * and https://www.cairographics.org/operators/\n *\n * @since 0.22.0\n *\n * @example\n * await sharp(background)\n *   .composite([\n *     { input: layer1, gravity: 'northwest' },\n *     { input: layer2, gravity: 'southeast' },\n *   ])\n *   .toFile('combined.png');\n *\n * @example\n * const output = await sharp('input.gif', { animated: true })\n *   .composite([\n *     { input: 'overlay.png', tile: true, blend: 'saturate' }\n *   ])\n *   .toBuffer();\n *\n * @example\n * sharp('input.png')\n *   .rotate(180)\n *   .resize(300)\n *   .flatten( { background: '#ff6600' } )\n *   .composite([{ input: 'overlay.png', gravity: 'southeast' }])\n *   .sharpen()\n *   .withMetadata()\n *   .webp( { quality: 90 } )\n *   .toBuffer()\n *   .then(function(outputBuffer) {\n *     // outputBuffer contains upside down, 300px wide, alpha channel flattened\n *     // onto orange background, composited with overlay.png with SE gravity,\n *     // sharpened, with metadata, 90% quality WebP image data. Phew!\n *   });\n *\n * @param {Object[]} images - Ordered list of images to composite\n * @param {Buffer|String} [images[].input] - Buffer containing image data, String containing the path to an image file, or Create object (see below)\n * @param {Object} [images[].input.create] - describes a blank overlay to be created.\n * @param {Number} [images[].input.create.width]\n * @param {Number} [images[].input.create.height]\n * @param {Number} [images[].input.create.channels] - 3-4\n * @param {String|Object} [images[].input.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @param {Object} [images[].input.text] - describes a new text image to be created.\n * @param {string} [images[].input.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.\n * @param {string} [images[].input.text.font] - font name to render with.\n * @param {string} [images[].input.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.\n * @param {number} [images[].input.text.width=0] - integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.\n * @param {number} [images[].input.text.height=0] - integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.\n * @param {string} [images[].input.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`).\n * @param {boolean} [images[].input.text.justify=false] - set this to true to apply justification to the text.\n * @param {number} [images[].input.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.\n * @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground=\"red\">Red!</span>`.\n * @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified.\n * @param {Boolean} [images[].autoOrient=false] - set to true to use EXIF orientation data, if present, to orient the image.\n * @param {String} [images[].blend='over'] - how to blend this image with the image below.\n * @param {String} [images[].gravity='centre'] - gravity at which to place the overlay.\n * @param {Number} [images[].top] - the pixel offset from the top edge.\n * @param {Number} [images[].left] - the pixel offset from the left edge.\n * @param {Boolean} [images[].tile=false] - set to true to repeat the overlay image across the entire image with the given `gravity`.\n * @param {Boolean} [images[].premultiplied=false] - set to true to avoid premultiplying the image below. Equivalent to the `--premultiplied` vips option.\n * @param {Number} [images[].density=72] - number representing the DPI for vector overlay image.\n * @param {Object} [images[].raw] - describes overlay when using raw pixel data.\n * @param {Number} [images[].raw.width]\n * @param {Number} [images[].raw.height]\n * @param {Number} [images[].raw.channels]\n * @param {boolean} [images[].animated=false] - Set to `true` to read all frames/pages of an animated image.\n * @param {string} [images[].failOn='warning'] - @see {@link /api-constructor/ constructor parameters}\n * @param {number|boolean} [images[].limitInputPixels=268402689] - @see {@link /api-constructor/ constructor parameters}\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction composite (images) {\n  if (!Array.isArray(images)) {\n    throw is.invalidParameterError('images to composite', 'array', images);\n  }\n  this.options.composite = images.map(image => {\n    if (!is.object(image)) {\n      throw is.invalidParameterError('image to composite', 'object', image);\n    }\n    const inputOptions = this._inputOptionsFromObject(image);\n    const composite = {\n      input: this._createInputDescriptor(image.input, inputOptions, { allowStream: false }),\n      blend: 'over',\n      tile: false,\n      left: 0,\n      top: 0,\n      hasOffset: false,\n      gravity: 0,\n      premultiplied: false\n    };\n    if (is.defined(image.blend)) {\n      if (is.string(blend[image.blend])) {\n        composite.blend = blend[image.blend];\n      } else {\n        throw is.invalidParameterError('blend', 'valid blend name', image.blend);\n      }\n    }\n    if (is.defined(image.tile)) {\n      if (is.bool(image.tile)) {\n        composite.tile = image.tile;\n      } else {\n        throw is.invalidParameterError('tile', 'boolean', image.tile);\n      }\n    }\n    if (is.defined(image.left)) {\n      if (is.integer(image.left)) {\n        composite.left = image.left;\n      } else {\n        throw is.invalidParameterError('left', 'integer', image.left);\n      }\n    }\n    if (is.defined(image.top)) {\n      if (is.integer(image.top)) {\n        composite.top = image.top;\n      } else {\n        throw is.invalidParameterError('top', 'integer', image.top);\n      }\n    }\n    if (is.defined(image.top) !== is.defined(image.left)) {\n      throw new Error('Expected both left and top to be set');\n    } else {\n      composite.hasOffset = is.integer(image.top) && is.integer(image.left);\n    }\n    if (is.defined(image.gravity)) {\n      if (is.integer(image.gravity) && is.inRange(image.gravity, 0, 8)) {\n        composite.gravity = image.gravity;\n      } else if (is.string(image.gravity) && is.integer(this.constructor.gravity[image.gravity])) {\n        composite.gravity = this.constructor.gravity[image.gravity];\n      } else {\n        throw is.invalidParameterError('gravity', 'valid gravity', image.gravity);\n      }\n    }\n    if (is.defined(image.premultiplied)) {\n      if (is.bool(image.premultiplied)) {\n        composite.premultiplied = image.premultiplied;\n      } else {\n        throw is.invalidParameterError('premultiplied', 'boolean', image.premultiplied);\n      }\n    }\n    return composite;\n  });\n  return this;\n}\n\n/**\n * Decorate the Sharp prototype with composite-related functions.\n * @module Sharp\n * @private\n */\nmodule.exports = (Sharp) => {\n  Sharp.prototype.composite = composite;\n  Sharp.blend = blend;\n};\n"
  },
  {
    "path": "lib/constructor.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst util = require('node:util');\nconst stream = require('node:stream');\nconst is = require('./is');\n\nrequire('./sharp');\n\n// Use NODE_DEBUG=sharp to enable libvips warnings\nconst debuglog = util.debuglog('sharp');\n\nconst queueListener = (queueLength) => {\n  Sharp.queue.emit('change', queueLength);\n};\n\n/**\n * Constructor factory to create an instance of `sharp`, to which further methods are chained.\n *\n * JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object.\n * When using Stream based output, derived attributes are available from the `info` event.\n *\n * Non-critical problems encountered during processing are emitted as `warning` events.\n *\n * Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.\n *\n * When loading more than one page/frame of an animated image,\n * these are combined as a vertically-stacked \"toilet roll\" image\n * where the overall height is the `pageHeight` multiplied by the number of `pages`.\n *\n * @constructs Sharp\n *\n * @emits Sharp#info\n * @emits Sharp#warning\n *\n * @example\n * sharp('input.jpg')\n *   .resize(300, 200)\n *   .toFile('output.jpg', function(err) {\n *     // output.jpg is a 300 pixels wide and 200 pixels high image\n *     // containing a scaled and cropped version of input.jpg\n *   });\n *\n * @example\n * // Read image data from remote URL,\n * // resize to 300 pixels wide,\n * // emit an 'info' event with calculated dimensions\n * // and finally write image data to writableStream\n * const { body } = fetch('https://...');\n * const readableStream = Readable.fromWeb(body);\n * const transformer = sharp()\n *   .resize(300)\n *   .on('info', ({ height }) => {\n *     console.log(`Image height is ${height}`);\n *   });\n * readableStream.pipe(transformer).pipe(writableStream);\n *\n * @example\n * // Create a blank 300x200 PNG image of semi-translucent red pixels\n * sharp({\n *   create: {\n *     width: 300,\n *     height: 200,\n *     channels: 4,\n *     background: { r: 255, g: 0, b: 0, alpha: 0.5 }\n *   }\n * })\n * .png()\n * .toBuffer()\n * .then( ... );\n *\n * @example\n * // Convert an animated GIF to an animated WebP\n * await sharp('in.gif', { animated: true }).toFile('out.webp');\n *\n * @example\n * // Read a raw array of pixels and save it to a png\n * const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray\n * const image = sharp(input, {\n *   // because the input does not contain its dimensions or how many channels it has\n *   // we need to specify it in the constructor options\n *   raw: {\n *     width: 2,\n *     height: 1,\n *     channels: 3\n *   }\n * });\n * await image.toFile('my-two-pixels.png');\n *\n * @example\n * // Generate RGB Gaussian noise\n * await sharp({\n *   create: {\n *     width: 300,\n *     height: 200,\n *     channels: 3,\n *     noise: {\n *       type: 'gaussian',\n *       mean: 128,\n *       sigma: 30\n *     }\n *  }\n * }).toFile('noise.png');\n *\n * @example\n * // Generate an image from text\n * await sharp({\n *   text: {\n *     text: 'Hello, world!',\n *     width: 400, // max width\n *     height: 300 // max height\n *   }\n * }).toFile('text_bw.png');\n *\n * @example\n * // Generate an rgba image from text using pango markup and font\n * await sharp({\n *   text: {\n *     text: '<span foreground=\"red\">Red!</span><span background=\"cyan\">blue</span>',\n *     font: 'sans',\n *     rgba: true,\n *     dpi: 300\n *   }\n * }).toFile('text_rgba.png');\n *\n * @example\n * // Join four input images as a 2x2 grid with a 4 pixel gutter\n * const data = await sharp(\n *  [image1, image2, image3, image4],\n *  { join: { across: 2, shim: 4 } }\n * ).toBuffer();\n *\n * @example\n * // Generate a two-frame animated image from emoji\n * const images = ['😀', '😛'].map(text => ({\n *   text: { text, width: 64, height: 64, channels: 4, rgba: true }\n * }));\n * await sharp(images, { join: { animated: true } }).toFile('out.gif');\n *\n * @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string|Array)} [input] - if present, can be\n *  a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or\n *  a TypedArray containing raw pixel image data, or\n *  a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.\n *  An array of inputs can be provided, and these will be joined together.\n *  JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.\n * @param {Object} [options] - if present, is an Object with optional attributes.\n * @param {string} [options.failOn='warning'] - When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort.\n * @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels\n *  (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.\n *  An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF).\n * @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF).\n * @param {boolean} [options.autoOrient=false] - Set this to `true` to rotate/flip the image to match EXIF `Orientation`, if any.\n * @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically.\n * @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000.\n * @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored.\n * @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages.\n * @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based.\n * @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`.\n * @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering.\n * @param {number} [options.raw.width] - integral number of pixels wide.\n * @param {number} [options.raw.height] - integral number of pixels high.\n * @param {number} [options.raw.channels] - integral number of channels, between 1 and 4.\n * @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true`\n *  to avoid sharp premultiplying the image. (optional, default `false`)\n * @param {number} [options.raw.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`.\n * @param {Object} [options.create] - describes a new image to be created.\n * @param {number} [options.create.width] - integral number of pixels wide.\n * @param {number} [options.create.height] - integral number of pixels high.\n * @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA).\n * @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @param {number} [options.create.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `create.height`.\n * @param {Object} [options.create.noise] - describes a noise to be created.\n * @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported.\n * @param {number} [options.create.noise.mean=128] - Mean value of pixels in the generated noise.\n * @param {number} [options.create.noise.sigma=30] - Standard deviation of pixel values in the generated noise.\n * @param {Object} [options.text] - describes a new text image to be created.\n * @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.\n * @param {string} [options.text.font] - font name to render with.\n * @param {string} [options.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.\n * @param {number} [options.text.width=0] - Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.\n * @param {number} [options.text.height=0] - Maximum integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.\n * @param {string} [options.text.align='left'] - Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`).\n * @param {boolean} [options.text.justify=false] - set this to true to apply justification to the text.\n * @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.\n * @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground=\"red\">Red!</span>`.\n * @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified.\n * @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'.\n * @param {Object} [options.join] - describes how an array of input images should be joined.\n * @param {number} [options.join.across=1] - number of images to join horizontally.\n * @param {boolean} [options.join.animated=false] - set this to `true` to join the images as an animated image.\n * @param {number} [options.join.shim=0] - number of pixels to insert between joined images.\n * @param {string|Object} [options.join.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @param {string} [options.join.halign='left'] - horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`).\n * @param {string} [options.join.valign='top'] - vertical alignment style for images joined vertically (`'top'`, `'centre'`, `'center'`, `'bottom'`).\n * @param {Object} [options.tiff] - Describes TIFF specific options.\n * @param {number} [options.tiff.subifd=-1] - Sub Image File Directory to extract for OME-TIFF, defaults to main image.\n * @param {Object} [options.svg] - Describes SVG specific options.\n * @param {string} [options.svg.stylesheet] - Custom CSS for SVG input, applied with a User Origin during the CSS cascade.\n * @param {boolean} [options.svg.highBitdepth=false] - Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA.\n * @param {Object} [options.pdf] - Describes PDF specific options. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick.\n * @param {string|Object} [options.pdf.background] - Background colour to use when PDF is partially transparent. Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @param {Object} [options.openSlide] - Describes OpenSlide specific options. Requires the use of a globally-installed libvips compiled with support for OpenSlide.\n * @param {number} [options.openSlide.level=0] - Level to extract from a multi-level input, zero based.\n * @param {Object} [options.jp2] - Describes JPEG 2000 specific options. Requires the use of a globally-installed libvips compiled with support for OpenJPEG.\n * @param {boolean} [options.jp2.oneshot=false] - Set to `true` to decode tiled JPEG 2000 images in a single operation, improving compatibility.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nconst Sharp = function (input, options) {\n  // biome-ignore lint/complexity/noArguments: constructor factory\n  if (arguments.length === 1 && !is.defined(input)) {\n    throw new Error('Invalid input');\n  }\n  if (!(this instanceof Sharp)) {\n    return new Sharp(input, options);\n  }\n  stream.Duplex.call(this);\n  this.options = {\n    // resize options\n    topOffsetPre: -1,\n    leftOffsetPre: -1,\n    widthPre: -1,\n    heightPre: -1,\n    topOffsetPost: -1,\n    leftOffsetPost: -1,\n    widthPost: -1,\n    heightPost: -1,\n    width: -1,\n    height: -1,\n    canvas: 'crop',\n    position: 0,\n    resizeBackground: [0, 0, 0, 255],\n    angle: 0,\n    rotationAngle: 0,\n    rotationBackground: [0, 0, 0, 255],\n    rotateBefore: false,\n    orientBefore: false,\n    flip: false,\n    flop: false,\n    extendTop: 0,\n    extendBottom: 0,\n    extendLeft: 0,\n    extendRight: 0,\n    extendBackground: [0, 0, 0, 255],\n    extendWith: 'background',\n    withoutEnlargement: false,\n    withoutReduction: false,\n    affineMatrix: [],\n    affineBackground: [0, 0, 0, 255],\n    affineIdx: 0,\n    affineIdy: 0,\n    affineOdx: 0,\n    affineOdy: 0,\n    affineInterpolator: this.constructor.interpolators.bilinear,\n    kernel: 'lanczos3',\n    fastShrinkOnLoad: true,\n    // operations\n    tint: [-1, 0, 0, 0],\n    flatten: false,\n    flattenBackground: [0, 0, 0],\n    unflatten: false,\n    negate: false,\n    negateAlpha: true,\n    medianSize: 0,\n    blurSigma: 0,\n    precision: 'integer',\n    minAmpl: 0.2,\n    sharpenSigma: 0,\n    sharpenM1: 1,\n    sharpenM2: 2,\n    sharpenX1: 2,\n    sharpenY2: 10,\n    sharpenY3: 20,\n    threshold: 0,\n    thresholdGrayscale: true,\n    trimBackground: [],\n    trimThreshold: -1,\n    trimLineArt: false,\n    dilateWidth: 0,\n    erodeWidth: 0,\n    gamma: 0,\n    gammaOut: 0,\n    greyscale: false,\n    normalise: false,\n    normaliseLower: 1,\n    normaliseUpper: 99,\n    claheWidth: 0,\n    claheHeight: 0,\n    claheMaxSlope: 3,\n    brightness: 1,\n    saturation: 1,\n    hue: 0,\n    lightness: 0,\n    booleanBufferIn: null,\n    booleanFileIn: '',\n    joinChannelIn: [],\n    extractChannel: -1,\n    removeAlpha: false,\n    ensureAlpha: -1,\n    colourspace: 'srgb',\n    colourspacePipeline: 'last',\n    composite: [],\n    // output\n    fileOut: '',\n    formatOut: 'input',\n    streamOut: false,\n    keepMetadata: 0,\n    withMetadataOrientation: -1,\n    withMetadataDensity: 0,\n    withIccProfile: '',\n    withExif: {},\n    withExifMerge: true,\n    withXmp: '',\n    resolveWithObject: false,\n    loop: -1,\n    delay: [],\n    // output format\n    jpegQuality: 80,\n    jpegProgressive: false,\n    jpegChromaSubsampling: '4:2:0',\n    jpegTrellisQuantisation: false,\n    jpegOvershootDeringing: false,\n    jpegOptimiseScans: false,\n    jpegOptimiseCoding: true,\n    jpegQuantisationTable: 0,\n    pngProgressive: false,\n    pngCompressionLevel: 6,\n    pngAdaptiveFiltering: false,\n    pngPalette: false,\n    pngQuality: 100,\n    pngEffort: 7,\n    pngBitdepth: 8,\n    pngDither: 1,\n    jp2Quality: 80,\n    jp2TileHeight: 512,\n    jp2TileWidth: 512,\n    jp2Lossless: false,\n    jp2ChromaSubsampling: '4:4:4',\n    webpQuality: 80,\n    webpAlphaQuality: 100,\n    webpLossless: false,\n    webpNearLossless: false,\n    webpSmartSubsample: false,\n    webpSmartDeblock: false,\n    webpPreset: 'default',\n    webpEffort: 4,\n    webpMinSize: false,\n    webpMixed: false,\n    gifBitdepth: 8,\n    gifEffort: 7,\n    gifDither: 1,\n    gifInterFrameMaxError: 0,\n    gifInterPaletteMaxError: 3,\n    gifKeepDuplicateFrames: false,\n    gifReuse: true,\n    gifProgressive: false,\n    tiffQuality: 80,\n    tiffCompression: 'jpeg',\n    tiffBigtiff: false,\n    tiffPredictor: 'horizontal',\n    tiffPyramid: false,\n    tiffMiniswhite: false,\n    tiffBitdepth: 8,\n    tiffTile: false,\n    tiffTileHeight: 256,\n    tiffTileWidth: 256,\n    tiffXres: 1.0,\n    tiffYres: 1.0,\n    tiffResolutionUnit: 'inch',\n    heifQuality: 50,\n    heifLossless: false,\n    heifCompression: 'av1',\n    heifEffort: 4,\n    heifChromaSubsampling: '4:4:4',\n    heifBitdepth: 8,\n    jxlDistance: 1,\n    jxlDecodingTier: 0,\n    jxlEffort: 7,\n    jxlLossless: false,\n    rawDepth: 'uchar',\n    tileSize: 256,\n    tileOverlap: 0,\n    tileContainer: 'fs',\n    tileLayout: 'dz',\n    tileFormat: 'last',\n    tileDepth: 'last',\n    tileAngle: 0,\n    tileSkipBlanks: -1,\n    tileBackground: [255, 255, 255, 255],\n    tileCentre: false,\n    tileId: 'https://example.com/iiif',\n    tileBasename: '',\n    timeoutSeconds: 0,\n    linearA: [],\n    linearB: [],\n    pdfBackground: [255, 255, 255, 255],\n    // Function to notify of libvips warnings\n    debuglog: warning => {\n      this.emit('warning', warning);\n      debuglog(warning);\n    },\n    // Function to notify of queue length changes\n    queueListener\n  };\n  this.options.input = this._createInputDescriptor(input, options, { allowStream: true });\n  return this;\n};\nObject.setPrototypeOf(Sharp.prototype, stream.Duplex.prototype);\nObject.setPrototypeOf(Sharp, stream.Duplex);\n\n/**\n * Take a \"snapshot\" of the Sharp instance, returning a new instance.\n * Cloned instances inherit the input of their parent instance.\n * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.\n *\n * @example\n * const pipeline = sharp().rotate();\n * pipeline.clone().resize(800, 600).pipe(firstWritableStream);\n * pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream);\n * readableStream.pipe(pipeline);\n * // firstWritableStream receives auto-rotated, resized readableStream\n * // secondWritableStream receives auto-rotated, extracted region of readableStream\n *\n * @example\n * // Create a pipeline that will download an image, resize it and format it to different files\n * // Using Promises to know when the pipeline is complete\n * const fs = require(\"fs\");\n * const got = require(\"got\");\n * const sharpStream = sharp({ failOn: 'none' });\n *\n * const promises = [];\n *\n * promises.push(\n *   sharpStream\n *     .clone()\n *     .jpeg({ quality: 100 })\n *     .toFile(\"originalFile.jpg\")\n * );\n *\n * promises.push(\n *   sharpStream\n *     .clone()\n *     .resize({ width: 500 })\n *     .jpeg({ quality: 80 })\n *     .toFile(\"optimized-500.jpg\")\n * );\n *\n * promises.push(\n *   sharpStream\n *     .clone()\n *     .resize({ width: 500 })\n *     .webp({ quality: 80 })\n *     .toFile(\"optimized-500.webp\")\n * );\n *\n * // https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md\n * got.stream(\"https://www.example.com/some-file.jpg\").pipe(sharpStream);\n *\n * Promise.all(promises)\n *   .then(res => { console.log(\"Done!\", res); })\n *   .catch(err => {\n *     console.error(\"Error processing files, let's clean it up\", err);\n *     try {\n *       fs.unlinkSync(\"originalFile.jpg\");\n *       fs.unlinkSync(\"optimized-500.jpg\");\n *       fs.unlinkSync(\"optimized-500.webp\");\n *     } catch (e) {}\n *   });\n *\n * @returns {Sharp}\n */\nfunction clone () {\n  // Clone existing options\n  const clone = this.constructor.call();\n  const { debuglog, queueListener, ...options } = this.options;\n  clone.options = structuredClone(options);\n  clone.options.debuglog = debuglog;\n  clone.options.queueListener = queueListener;\n  // Pass 'finish' event to clone for Stream-based input\n  if (this._isStreamInput()) {\n    this.on('finish', () => {\n      // Clone inherits input data\n      this._flattenBufferIn();\n      clone.options.input.buffer = this.options.input.buffer;\n      clone.emit('finish');\n    });\n  }\n  return clone;\n}\nObject.assign(Sharp.prototype, { clone });\n\n/**\n * Export constructor.\n * @module Sharp\n * @private\n */\nmodule.exports = Sharp;\n"
  },
  {
    "path": "lib/index.d.ts",
    "content": "/**\n * Copyright 2017 François Nguyen and others.\n *\n * Billy Kwok <https://github.com/billykwok>\n * Bradley Odell <https://github.com/BTOdell>\n * Espen Hovlandsdal <https://github.com/rexxars>\n * Floris de Bijl <https://github.com/Fdebijl>\n * François Nguyen <https://github.com/phurytw>\n * Jamie Woodbury <https://github.com/JamieWoodbury>\n * Wooseop Kim <https://github.com/wooseopkim>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n * documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of\n * the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n// SPDX-License-Identifier: MIT\n\n/// <reference types=\"node\" />\n\nimport type { Duplex } from 'node:stream';\n\n//#region Constructor functions\n\n/**\n * Creates a sharp instance from an image\n * @param input Buffer containing JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data, or String containing the path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.\n * @param options Object with optional attributes.\n * @throws {Error} Invalid parameters\n * @returns A sharp instance that can be used to chain operations\n */\ndeclare function sharp(options?: sharp.SharpOptions): sharp.Sharp;\ndeclare function sharp(\n    input?: sharp.SharpInput | Array<sharp.SharpInput>,\n    options?: sharp.SharpOptions,\n): sharp.Sharp;\n\ndeclare namespace sharp {\n    /** Object containing nested boolean values representing the available input and output formats/methods. */\n    const format: FormatEnum;\n\n    /** An Object containing the version numbers of sharp, libvips and its dependencies. */\n    const versions: {\n        aom?: string | undefined;\n        archive?: string | undefined;\n        cairo?: string | undefined;\n        cgif?: string | undefined;\n        exif?: string | undefined;\n        expat?: string | undefined;\n        ffi?: string | undefined;\n        fontconfig?: string | undefined;\n        freetype?: string | undefined;\n        fribidi?: string | undefined;\n        glib?: string | undefined;\n        harfbuzz?: string | undefined;\n        heif?: string | undefined;\n        highway?: string | undefined;\n        imagequant?: string | undefined;\n        lcms?: string | undefined;\n        mozjpeg?: string | undefined;\n        pango?: string | undefined;\n        pixman?: string | undefined;\n        png?: string | undefined;\n        \"proxy-libintl\"?: string | undefined;\n        rsvg?: string | undefined;\n        sharp: string;\n        spng?: string | undefined;\n        tiff?: string | undefined;\n        vips: string;\n        webp?: string | undefined;\n        xml?: string | undefined;\n        \"zlib-ng\"?: string | undefined;\n    };\n\n    /** An Object containing the available interpolators and their proper values */\n    const interpolators: Interpolators;\n\n    /** An EventEmitter that emits a change event when a task is either queued, waiting for libuv to provide a worker thread, complete */\n    const queue: NodeJS.EventEmitter;\n\n    //#endregion\n\n    //#region Utility functions\n\n    /**\n     * Gets or, when options are provided, sets the limits of libvips' operation cache.\n     * Existing entries in the cache will be trimmed after any change in limits.\n     * This method always returns cache statistics, useful for determining how much working memory is required for a particular task.\n     * @param options Object with the following attributes, or Boolean where true uses default cache settings and false removes all caching (optional, default true)\n     * @returns The cache results.\n     */\n    function cache(options?: boolean | CacheOptions): CacheResult;\n\n    /**\n     * Gets or sets the number of threads libvips' should create to process each image.\n     * The default value is the number of CPU cores. A value of 0 will reset to this default.\n     * The maximum number of images that can be processed in parallel is limited by libuv's UV_THREADPOOL_SIZE environment variable.\n     * @param concurrency The new concurrency value.\n     * @returns The current concurrency value.\n     */\n    function concurrency(concurrency?: number): number;\n\n    /**\n     * Provides access to internal task counters.\n     * @returns Object containing task counters\n     */\n    function counters(): SharpCounters;\n\n    /**\n     * Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with highway support.\n     * Improves the performance of resize, blur and sharpen operations by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.\n     * @param enable enable or disable use of SIMD vector unit instructions\n     * @returns true if usage of SIMD vector unit instructions is enabled\n     */\n    function simd(enable?: boolean): boolean;\n\n    /**\n     * Block libvips operations at runtime.\n     *\n     * This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable,\n     * which when set will block all \"untrusted\" operations.\n     *\n     * @since 0.32.4\n     *\n     * @example <caption>Block all TIFF input.</caption>\n     * sharp.block({\n     *   operation: ['VipsForeignLoadTiff']\n     * });\n     *\n     * @param {Object} options\n     * @param {Array<string>} options.operation - List of libvips low-level operation names to block.\n     */\n    function block(options: { operation: string[] }): void;\n\n    /**\n     * Unblock libvips operations at runtime.\n     *\n     * This is useful for defining a list of allowed operations.\n     *\n     * @since 0.32.4\n     *\n     * @example <caption>Block all input except WebP from the filesystem.</caption>\n     * sharp.block({\n     *   operation: ['VipsForeignLoad']\n     * });\n     * sharp.unblock({\n     *   operation: ['VipsForeignLoadWebpFile']\n     * });\n     *\n     * @example <caption>Block all input except JPEG and PNG from a Buffer or Stream.</caption>\n     * sharp.block({\n     *   operation: ['VipsForeignLoad']\n     * });\n     * sharp.unblock({\n     *   operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer']\n     * });\n     *\n     * @param {Object} options\n     * @param {Array<string>} options.operation - List of libvips low-level operation names to unblock.\n     */\n    function unblock(options: { operation: string[] }): void;\n\n    //#endregion\n\n    const gravity: GravityEnum;\n    const strategy: StrategyEnum;\n    const kernel: KernelEnum;\n    const fit: FitEnum;\n    const bool: BoolEnum;\n\n    interface Sharp extends Duplex {\n        //#region Channel functions\n\n        /**\n         * Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.\n         * @returns A sharp instance that can be used to chain operations\n         */\n        removeAlpha(): Sharp;\n\n        /**\n         * Ensure alpha channel, if missing. The added alpha channel will be fully opaque. This is a no-op if the image already has an alpha channel.\n         * @param alpha transparency level (0=fully-transparent, 1=fully-opaque) (optional, default 1).\n         * @returns A sharp instance that can be used to chain operations\n         */\n        ensureAlpha(alpha?: number): Sharp;\n\n        /**\n         * Extract a single channel from a multi-channel image.\n         * @param channel zero-indexed channel/band number to extract, or red, green, blue or alpha.\n         * @throws {Error} Invalid channel\n         * @returns A sharp instance that can be used to chain operations\n         */\n        extractChannel(channel: 0 | 1 | 2 | 3 | 'red' | 'green' | 'blue' | 'alpha'): Sharp;\n\n        /**\n         * Join one or more channels to the image. The meaning of the added channels depends on the output colourspace, set with toColourspace().\n         * By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. Channel ordering follows vips convention:\n         *  - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.\n         *  - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.\n         *\n         * Buffers may be any of the image formats supported by sharp.\n         * For raw pixel input, the options object should contain a raw attribute, which follows the format of the attribute of the same name in the sharp() constructor.\n         * @param images one or more images (file paths, Buffers).\n         * @param options image options, see sharp() constructor.\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        joinChannel(images: string | Buffer | ArrayLike<string | Buffer>, options?: SharpOptions): Sharp;\n\n        /**\n         * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.\n         * @param boolOp one of \"and\", \"or\" or \"eor\" to perform that bitwise operation, like the C logic operators &, | and ^ respectively.\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        bandbool(boolOp: keyof BoolEnum): Sharp;\n\n        //#endregion\n\n        //#region Color functions\n\n        /**\n         * Tint the image using the provided colour.\n         * An alpha channel may be present and will be unchanged by the operation.\n         * @param tint Parsed by the color module.\n         * @returns A sharp instance that can be used to chain operations\n         */\n        tint(tint: Colour | Color): Sharp;\n\n        /**\n         * Convert to 8-bit greyscale; 256 shades of grey.\n         * This is a linear operation.\n         * If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results.\n         * By default the output image will be web-friendly sRGB and contain three (identical) colour channels.\n         * This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one colour channel.\n         * An alpha channel may be present, and will be unchanged by the operation.\n         * @param greyscale true to enable and false to disable (defaults to true)\n         * @returns A sharp instance that can be used to chain operations\n         */\n        greyscale(greyscale?: boolean): Sharp;\n\n        /**\n         * Alternative spelling of greyscale().\n         * @param grayscale true to enable and false to disable (defaults to true)\n         * @returns A sharp instance that can be used to chain operations\n         */\n        grayscale(grayscale?: boolean): Sharp;\n\n        /**\n         * Set the pipeline colourspace.\n         * The input image will be converted to the provided colourspace at the start of the pipeline.\n         * All operations will use this colourspace before converting to the output colourspace, as defined by toColourspace.\n         * This feature is experimental and has not yet been fully-tested with all operations.\n         *\n         * @param colourspace pipeline colourspace e.g. rgb16, scrgb, lab, grey16 ...\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        pipelineColourspace(colourspace?: string): Sharp;\n\n        /**\n         * Alternative spelling of pipelineColourspace\n         * @param colorspace pipeline colourspace e.g. rgb16, scrgb, lab, grey16 ...\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        pipelineColorspace(colorspace?: string): Sharp;\n\n        /**\n         * Set the output colourspace.\n         * By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.\n         * @param colourspace output colourspace e.g. srgb, rgb, cmyk, lab, b-w ...\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        toColourspace(colourspace?: string): Sharp;\n\n        /**\n         * Alternative spelling of toColourspace().\n         * @param colorspace output colorspace e.g. srgb, rgb, cmyk, lab, b-w ...\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        toColorspace(colorspace: string): Sharp;\n\n        //#endregion\n\n        //#region Composite functions\n\n        /**\n         * Composite image(s) over the processed (resized, extracted etc.) image.\n         *\n         * The images to composite must be the same size or smaller than the processed image.\n         * If both `top` and `left` options are provided, they take precedence over `gravity`.\n         * @param images - Ordered list of images to composite\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        composite(images: OverlayOptions[]): Sharp;\n\n        //#endregion\n\n        //#region Input functions\n\n        /**\n         * Take a \"snapshot\" of the Sharp instance, returning a new instance.\n         * Cloned instances inherit the input of their parent instance.\n         * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.\n         * @returns A sharp instance that can be used to chain operations\n         */\n        clone(): Sharp;\n\n        /**\n         * Fast access to (uncached) image metadata without decoding any compressed image data.\n         * @returns A sharp instance that can be used to chain operations\n         */\n        metadata(callback: (err: Error, metadata: Metadata) => void): Sharp;\n\n        /**\n         * Fast access to (uncached) image metadata without decoding any compressed image data.\n         * @returns A promise that resolves with a metadata object\n         */\n        metadata(): Promise<Metadata>;\n\n        /**\n         * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.\n         * @returns A sharp instance that can be used to chain operations\n         */\n        keepMetadata(): Sharp;\n\n        /**\n         * Access to pixel-derived image statistics for every channel in the image.\n         * @returns A sharp instance that can be used to chain operations\n         */\n        stats(callback: (err: Error, stats: Stats) => void): Sharp;\n\n        /**\n         * Access to pixel-derived image statistics for every channel in the image.\n         * @returns A promise that resolves with a stats object\n         */\n        stats(): Promise<Stats>;\n\n        //#endregion\n\n        //#region Operation functions\n\n        /**\n         * Rotate the output image by either an explicit angle\n         * or auto-orient based on the EXIF `Orientation` tag.\n         *\n         * If an angle is provided, it is converted to a valid positive degree rotation.\n         * For example, `-450` will produce a 270 degree rotation.\n         *\n         * When rotating by an angle other than a multiple of 90,\n         * the background colour can be provided with the `background` option.\n         *\n         * If no angle is provided, it is determined from the EXIF data.\n         * Mirroring is supported and may infer the use of a flip operation.\n         *\n         * The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any.\n         *\n         * Only one rotation can occur per pipeline (aside from an initial call without\n         * arguments to orient via EXIF data). Previous calls to `rotate` in the same\n         * pipeline will be ignored.\n         *\n         * Multi-page images can only be rotated by 180 degrees.\n         *\n         * Method order is important when rotating, resizing and/or extracting regions,\n         * for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.\n         *\n         * @example\n         * const pipeline = sharp()\n         *   .rotate()\n         *   .resize(null, 200)\n         *   .toBuffer(function (err, outputBuffer, info) {\n         *     // outputBuffer contains 200px high JPEG image data,\n         *     // auto-rotated using EXIF Orientation tag\n         *     // info.width and info.height contain the dimensions of the resized image\n         *   });\n         * readableStream.pipe(pipeline);\n         *\n         * @example\n         * const rotateThenResize = await sharp(input)\n         *   .rotate(90)\n         *   .resize({ width: 16, height: 8, fit: 'fill' })\n         *   .toBuffer();\n         * const resizeThenRotate = await sharp(input)\n         *   .resize({ width: 16, height: 8, fit: 'fill' })\n         *   .rotate(90)\n         *   .toBuffer();\n         *\n         * @param {number} [angle=auto] angle of rotation.\n         * @param {Object} [options] - if present, is an Object with optional attributes.\n         * @param {string|Object} [options.background=\"#000000\"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n         * @returns {Sharp}\n         * @throws {Error} Invalid parameters\n         */\n        rotate(angle?: number, options?: RotateOptions): Sharp;\n\n        /**\n         * Alias for calling `rotate()` with no arguments, which orients the image based\n         * on EXIF orientsion.\n         *\n         * This operation is aliased to emphasize its purpose, helping to remove any\n         * confusion between rotation and orientation.\n         *\n         * @example\n         * const output = await sharp(input).autoOrient().toBuffer();\n         *\n         * @returns {Sharp}\n         */\n        autoOrient(): Sharp\n\n        /**\n         * Flip the image about the vertical Y axis. This always occurs after rotation, if any.\n         * The use of flip implies the removal of the EXIF Orientation tag, if any.\n         * @param flip true to enable and false to disable (defaults to true)\n         * @returns A sharp instance that can be used to chain operations\n         */\n        flip(flip?: boolean): Sharp;\n\n        /**\n         * Flop the image about the horizontal X axis. This always occurs after rotation, if any.\n         * The use of flop implies the removal of the EXIF Orientation tag, if any.\n         * @param flop true to enable and false to disable (defaults to true)\n         * @returns A sharp instance that can be used to chain operations\n         */\n        flop(flop?: boolean): Sharp;\n\n        /**\n         * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.\n         * You must provide an array of length 4 or a 2x2 affine transformation matrix.\n         * By default, new pixels are filled with a black background. You can provide a background colour with the `background` option.\n         * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.\n         *\n         * In the case of a 2x2 matrix, the transform is:\n         * X = matrix[0, 0] * (x + idx) + matrix[0, 1] * (y + idy) + odx\n         * Y = matrix[1, 0] * (x + idx) + matrix[1, 1] * (y + idy) + ody\n         *\n         * where:\n         *\n         * x and y are the coordinates in input image.\n         * X and Y are the coordinates in output image.\n         * (0,0) is the upper left corner.\n         *\n         * @param matrix Affine transformation matrix, may either by a array of length four or a 2x2 matrix array\n         * @param options if present, is an Object with optional attributes.\n         *\n         * @returns A sharp instance that can be used to chain operations\n         */\n        affine(matrix: [number, number, number, number] | Matrix2x2, options?: AffineOptions): Sharp;\n\n        /**\n         * Sharpen the image.\n         * When used without parameters, performs a fast, mild sharpen of the output image.\n         * When a sigma is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.\n         * Fine-grained control over the level of sharpening in \"flat\" (m1) and \"jagged\" (m2) areas is available.\n         * @param options if present, is an Object with optional attributes\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        sharpen(options?: SharpenOptions): Sharp;\n\n        /**\n         * Sharpen the image.\n         * When used without parameters, performs a fast, mild sharpen of the output image.\n         * When a sigma is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.\n         * Fine-grained control over the level of sharpening in \"flat\" (m1) and \"jagged\" (m2) areas is available.\n         * @param sigma the sigma of the Gaussian mask, where sigma = 1 + radius / 2.\n         * @param flat the level of sharpening to apply to \"flat\" areas. (optional, default 1.0)\n         * @param jagged the level of sharpening to apply to \"jagged\" areas. (optional, default 2.0)\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         *\n         * @deprecated Use the object parameter `sharpen({sigma, m1, m2, x1, y2, y3})` instead\n         */\n        sharpen(sigma?: number, flat?: number, jagged?: number): Sharp;\n\n        /**\n         * Apply median filter. When used without parameters the default window is 3x3.\n         * @param size square mask size: size x size (optional, default 3)\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        median(size?: number): Sharp;\n\n        /**\n         * Blur the image.\n         * When used without parameters, performs a fast, mild blur of the output image.\n         * When a sigma is provided, performs a slower, more accurate Gaussian blur.\n         * When a boolean sigma is provided, ether blur mild or disable blur\n         * @param sigma a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where sigma = 1 + radius / 2.\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        blur(sigma?: number | boolean | BlurOptions): Sharp;\n\n        /**\n         * Expand foreground objects using the dilate morphological operator.\n         * @param {Number} [width=1] dilation width in pixels.\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        dilate(width?: number): Sharp;\n\n        /**\n         * Shrink foreground objects using the erode morphological operator.\n         * @param {Number} [width=1] erosion width in pixels.\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        erode(width?: number): Sharp;\n\n        /**\n         * Merge alpha transparency channel, if any, with background.\n         * @param flatten true to enable and false to disable (defaults to true)\n         * @returns A sharp instance that can be used to chain operations\n         */\n        flatten(flatten?: boolean | FlattenOptions): Sharp;\n\n        /**\n         * Ensure the image has an alpha channel with all white pixel values made fully transparent.\n         * Existing alpha channel values for non-white pixels remain unchanged.\n         * @returns A sharp instance that can be used to chain operations\n         */\n        unflatten(): Sharp;\n\n        /**\n         * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of 1/gamma then increasing the encoding (brighten) post-resize at a factor of gamma.\n         * This can improve the perceived brightness of a resized image in non-linear colour spaces.\n         * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation when applying a gamma correction.\n         * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases.\n         * @param gamma value between 1.0 and 3.0. (optional, default 2.2)\n         * @param gammaOut value between 1.0 and 3.0. (optional, defaults to same as gamma)\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        gamma(gamma?: number, gammaOut?: number): Sharp;\n\n        /**\n         * Produce the \"negative\" of the image.\n         * @param negate true to enable and false to disable, or an object of options (defaults to true)\n         * @returns A sharp instance that can be used to chain operations\n         */\n        negate(negate?: boolean | NegateOptions): Sharp;\n\n        /**\n         * Enhance output image contrast by stretching its luminance to cover a full dynamic range.\n         *\n         * Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes.\n         *\n         * Luminance values below the `lower` percentile will be underexposed by clipping to zero.\n         * Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value.\n         *\n         * @param normalise options\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        normalise(normalise?: NormaliseOptions): Sharp;\n\n        /**\n         * Alternative spelling of normalise.\n         * @param normalize options\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        normalize(normalize?: NormaliseOptions): Sharp;\n\n        /**\n         * Perform contrast limiting adaptive histogram equalization (CLAHE)\n         *\n         * This will, in general, enhance the clarity of the image by bringing out\n         * darker details. Please read more about CLAHE here:\n         * https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE\n         *\n         * @param options clahe options\n         */\n        clahe(options: ClaheOptions): Sharp;\n\n        /**\n         * Convolve the image with the specified kernel.\n         * @param kernel the specified kernel\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        convolve(kernel: Kernel): Sharp;\n\n        /**\n         * Any pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0.\n         * @param threshold a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default 128)\n         * @param options threshold options\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        threshold(threshold?: number, options?: ThresholdOptions): Sharp;\n\n        /**\n         * Perform a bitwise boolean operation with operand image.\n         * This operation creates an output image where each pixel is the result of the selected bitwise boolean operation between the corresponding pixels of the input images.\n         * @param operand Buffer containing image data or String containing the path to an image file.\n         * @param operator one of \"and\", \"or\" or \"eor\" to perform that bitwise operation, like the C logic operators &, | and ^ respectively.\n         * @param options describes operand when using raw pixel data.\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        boolean(operand: string | Buffer, operator: keyof BoolEnum, options?: { raw: Raw }): Sharp;\n\n        /**\n         * Apply the linear formula a * input + b to the image (levels adjustment)\n         * @param a multiplier (optional, default 1.0)\n         * @param b offset (optional, default 0.0)\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        linear(a?: number | number[] | null, b?: number | number[]): Sharp;\n\n        /**\n         * Recomb the image with the specified matrix.\n         * @param inputMatrix 3x3 Recombination matrix or 4x4 Recombination matrix\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        recomb(inputMatrix: Matrix3x3 | Matrix4x4): Sharp;\n\n        /**\n         * Transforms the image using brightness, saturation, hue rotation and lightness.\n         * Brightness and lightness both operate on luminance, with the difference being that brightness is multiplicative whereas lightness is additive.\n         * @param options describes the modulation\n         * @returns A sharp instance that can be used to chain operations\n         */\n        modulate(options?: {\n            brightness?: number | undefined;\n            saturation?: number | undefined;\n            hue?: number | undefined;\n            lightness?: number | undefined;\n        }): Sharp;\n\n        //#endregion\n\n        //#region Output functions\n\n        /**\n         * Write output image data to a file.\n         * If an explicit output format is not selected, it will be inferred from the extension, with JPEG, PNG, WebP, AVIF, TIFF, DZI, and libvips' V format supported.\n         * Note that raw pixel data is only supported for buffer output.\n         * @param fileOut The path to write the image data to.\n         * @param callback Callback function called on completion with two arguments (err, info).  info contains the output image format, size (bytes), width, height and channels.\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        toFile(fileOut: string, callback: (err: Error, info: OutputInfo) => void): Sharp;\n\n        /**\n         * Write output image data to a file.\n         * @param fileOut The path to write the image data to.\n         * @throws {Error} Invalid parameters\n         * @returns A promise that fulfills with an object containing information on the resulting file\n         */\n        toFile(fileOut: string): Promise<OutputInfo>;\n\n        /**\n         * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported.\n         * By default, the format will match the input image, except SVG input which becomes PNG output.\n         * @param callback Callback function called on completion with three arguments (err, buffer, info).\n         * @returns A sharp instance that can be used to chain operations\n         */\n        toBuffer(callback: (err: Error, buffer: Buffer, info: OutputInfo) => void): Sharp;\n\n        /**\n         * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported.\n         * By default, the format will match the input image, except SVG input which becomes PNG output.\n         * @param options resolve options\n         * @param options.resolveWithObject Resolve the Promise with an Object containing data and info properties instead of resolving only with data.\n         * @returns A promise that resolves with the Buffer data.\n         */\n        toBuffer(options?: { resolveWithObject: false }): Promise<Buffer>;\n\n        /**\n         * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported.\n         * By default, the format will match the input image, except SVG input which becomes PNG output.\n         * @param options resolve options\n         * @param options.resolveWithObject Resolve the Promise with an Object containing data and info properties instead of resolving only with data.\n         * @returns A promise that resolves with an object containing the Buffer data and an info object containing the output image format, size (bytes), width, height and channels\n         */\n        toBuffer(options: { resolveWithObject: true }): Promise<{ data: Buffer; info: OutputInfo }>;\n\n        /**\n         * Keep all EXIF metadata from the input image in the output image.\n         * EXIF metadata is unsupported for TIFF output.\n         * @returns A sharp instance that can be used to chain operations\n         */\n        keepExif(): Sharp;\n\n        /**\n         * Set EXIF metadata in the output image, ignoring any EXIF in the input image.\n         * @param {Exif} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.\n         * @returns A sharp instance that can be used to chain operations\n         * @throws {Error} Invalid parameters\n         */\n        withExif(exif: Exif): Sharp;\n\n        /**\n         * Update EXIF metadata from the input image in the output image.\n         * @param {Exif} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.\n         * @returns A sharp instance that can be used to chain operations\n         * @throws {Error} Invalid parameters\n         */\n        withExifMerge(exif: Exif): Sharp;\n\n        /**\n         * Keep ICC profile from the input image in the output image where possible.\n         * @returns A sharp instance that can be used to chain operations\n         */\n        keepIccProfile(): Sharp;\n\n        /**\n         * Transform using an ICC profile and attach to the output image.\n         * @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk).\n         * @returns A sharp instance that can be used to chain operations\n         * @throws {Error} Invalid parameters\n         */\n        withIccProfile(icc: string, options?: WithIccProfileOptions): Sharp;\n\n        /**\n         * Keep all XMP metadata from the input image in the output image.\n         * @returns A sharp instance that can be used to chain operations\n         */\n        keepXmp(): Sharp;\n\n        /**\n         * Set XMP metadata in the output image.\n         * @param {string} xmp - String containing XMP metadata to be embedded in the output image.\n         * @returns A sharp instance that can be used to chain operations\n         * @throws {Error} Invalid parameters\n         */\n        withXmp(xmp: string): Sharp;\n\n        /**\n         * Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.\n         * The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space.\n         * This will also convert to and add a web-friendly sRGB ICC profile.\n         * @param withMetadata\n         * @throws {Error} Invalid parameters.\n         */\n        withMetadata(withMetadata?: WriteableMetadata): Sharp;\n\n        /**\n         * Use these JPEG options for output image.\n         * @param options Output options.\n         * @throws {Error} Invalid options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        jpeg(options?: JpegOptions): Sharp;\n\n        /**\n         * Use these JP2 (JPEG 2000) options for output image.\n         * @param options Output options.\n         * @throws {Error} Invalid options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        jp2(options?: Jp2Options): Sharp;\n\n        /**\n         * Use these JPEG-XL (JXL) options for output image.\n         * This feature is experimental, please do not use in production systems.\n         * Requires libvips compiled with support for libjxl.\n         * The prebuilt binaries do not include this.\n         * Image metadata (EXIF, XMP) is unsupported.\n         * @param options Output options.\n         * @throws {Error} Invalid options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        jxl(options?: JxlOptions): Sharp;\n\n        /**\n         * Use these PNG options for output image.\n         * PNG output is always full colour at 8 or 16 bits per pixel.\n         * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.\n         * @param options Output options.\n         * @throws {Error} Invalid options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        png(options?: PngOptions): Sharp;\n\n        /**\n         * Use these WebP options for output image.\n         * @param options Output options.\n         * @throws {Error} Invalid options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        webp(options?: WebpOptions): Sharp;\n\n        /**\n         * Use these GIF options for output image.\n         * Requires libvips compiled with support for ImageMagick or GraphicsMagick. The prebuilt binaries do not include this - see installing a custom libvips.\n         * @param options Output options.\n         * @throws {Error} Invalid options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        gif(options?: GifOptions): Sharp;\n\n        /**\n         * Use these AVIF options for output image.\n         * @param options Output options.\n         * @throws {Error} Invalid options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        avif(options?: AvifOptions): Sharp;\n\n        /**\n         * Use these HEIF options for output image.\n         * Support for patent-encumbered HEIC images requires the use of a globally-installed libvips compiled with support for libheif, libde265 and x265.\n         * @param options Output options.\n         * @throws {Error} Invalid options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        heif(options?: HeifOptions): Sharp;\n\n        /**\n         * Use these TIFF options for output image.\n         * @param options Output options.\n         * @throws {Error} Invalid options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        tiff(options?: TiffOptions): Sharp;\n\n        /**\n         * Force output to be raw, uncompressed uint8 pixel data.\n         * @param options Raw output options.\n         * @throws {Error} Invalid options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        raw(options?: RawOptions): Sharp;\n\n        /**\n         * Force output to a given format.\n         * @param format a String or an Object with an 'id' attribute\n         * @param options output options\n         * @throws {Error} Unsupported format or options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        toFormat(\n            format: keyof FormatEnum | AvailableFormatInfo,\n            options?:\n                | OutputOptions\n                | JpegOptions\n                | PngOptions\n                | WebpOptions\n                | AvifOptions\n                | HeifOptions\n                | JxlOptions\n                | GifOptions\n                | Jp2Options\n                | RawOptions\n                | TiffOptions,\n        ): Sharp;\n\n        /**\n         * Use tile-based deep zoom (image pyramid) output.\n         * Set the format and options for tile images via the toFormat, jpeg, png or webp functions.\n         * Use a .zip or .szi file extension with toFile to write to a compressed archive file format.\n         * @param tile tile options\n         * @throws {Error} Invalid options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        tile(tile?: TileOptions): Sharp;\n\n        /**\n         * Set a timeout for processing, in seconds. Use a value of zero to continue processing indefinitely, the default behaviour.\n         * The clock starts when libvips opens an input image for processing. Time spent waiting for a libuv thread to become available is not included.\n         * @param options Object with a `seconds` attribute between 0 and 3600 (number)\n         * @throws {Error} Invalid options\n         * @returns A sharp instance that can be used to chain operations\n         */\n        timeout(options: TimeoutOptions): Sharp;\n\n        //#endregion\n\n        //#region Resize functions\n\n        /**\n         * Resize image to width, height or width x height.\n         *\n         * When both a width and height are provided, the possible methods by which the image should fit these are:\n         *  - cover: Crop to cover both provided dimensions (the default).\n         *  - contain: Embed within both provided dimensions.\n         *  - fill: Ignore the aspect ratio of the input and stretch to both provided dimensions.\n         *  - inside: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.\n         *  - outside: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.\n         *             Some of these values are based on the object-fit CSS property.\n         *\n         * When using a fit of cover or contain, the default position is centre. Other options are:\n         *  - sharp.position: top, right top, right, right bottom, bottom, left bottom, left, left top.\n         *  - sharp.gravity: north, northeast, east, southeast, south, southwest, west, northwest, center or centre.\n         *  - sharp.strategy: cover only, dynamically crop using either the entropy or attention strategy. Some of these values are based on the object-position CSS property.\n         *\n         * The experimental strategy-based approach resizes so one dimension is at its target length then repeatedly ranks edge regions,\n         * discarding the edge with the lowest score based on the selected strategy.\n         *  - entropy: focus on the region with the highest Shannon entropy.\n         *  - attention: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.\n         *\n         * Possible interpolation kernels are:\n         *  - nearest: Use nearest neighbour interpolation.\n         *  - cubic: Use a Catmull-Rom spline.\n         *  - lanczos2: Use a Lanczos kernel with a=2.\n         *  - lanczos3: Use a Lanczos kernel with a=3 (the default).\n         *\n         * @param width pixels wide the resultant image should be. Use null or undefined to auto-scale the width to match the height.\n         * @param height pixels high the resultant image should be. Use null or undefined to auto-scale the height to match the width.\n         * @param options resize options\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        resize(widthOrOptions?: number | ResizeOptions | null, height?: number | null, options?: ResizeOptions): Sharp;\n\n        /**\n         * Shorthand for resize(null, null, options);\n         *\n         * @param options resize options\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        resize(options: ResizeOptions): Sharp;\n\n        /**\n         * Extend / pad / extrude one or more edges of the image with either\n         * the provided background colour or pixels derived from the image.\n         * This operation will always occur after resizing and extraction, if any.\n         * @param extend single pixel count to add to all edges or an Object with per-edge counts\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        extend(extend: number | ExtendOptions): Sharp;\n\n        /**\n         * Extract a region of the image.\n         *  - Use extract() before resize() for pre-resize extraction.\n         *  - Use extract() after resize() for post-resize extraction.\n         *  - Use extract() before and after for both.\n         *\n         * @param region The region to extract\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        extract(region: Region): Sharp;\n\n        /**\n         * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.\n         * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.\n         * The info response Object will contain trimOffsetLeft and trimOffsetTop properties.\n         * @param options trim options\n         * @throws {Error} Invalid parameters\n         * @returns A sharp instance that can be used to chain operations\n         */\n        trim(options?: TrimOptions): Sharp;\n\n        //#endregion\n    }\n\n    type SharpInput = Buffer\n        | ArrayBuffer\n        | Uint8Array\n        | Uint8ClampedArray\n        | Int8Array\n        | Uint16Array\n        | Int16Array\n        | Uint32Array\n        | Int32Array\n        | Float32Array\n        | Float64Array\n        | string;\n\n    interface SharpOptions {\n        /**\n         * Auto-orient based on the EXIF `Orientation` tag, if present.\n         * Mirroring is supported and may infer the use of a flip operation.\n         *\n         * Using this option will remove the EXIF `Orientation` tag, if any.\n         */\n        autoOrient?: boolean | undefined;\n        /**\n         *  When to abort processing of invalid pixel data, one of (in order of sensitivity):\n         *  'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. (optional, default 'warning')\n         */\n        failOn?: FailOnOptions | undefined;\n        /**\n         * By default halt processing and raise an error when loading invalid images.\n         * Set this flag to false if you'd rather apply a \"best effort\" to decode images,\n         * even if the data is corrupt or invalid. (optional, default true)\n         *\n         * @deprecated Use `failOn` instead\n         */\n        failOnError?: boolean | undefined;\n        /**\n         * Do not process input images where the number of pixels (width x height) exceeds this limit.\n         * Assumes image dimensions contained in the input metadata can be trusted.\n         * An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). (optional, default 268402689)\n         */\n        limitInputPixels?: number | boolean | undefined;\n        /** Set this to true to remove safety features that help prevent memory exhaustion (SVG, PNG). (optional, default false) */\n        unlimited?: boolean | undefined;\n        /** Set this to false to use random access rather than sequential read. Some operations will do this automatically. */\n        sequentialRead?: boolean | undefined;\n        /** Number representing the DPI for vector images in the range 1 to 100000. (optional, default 72) */\n        density?: number | undefined;\n        /** Should the embedded ICC profile, if any, be ignored. */\n        ignoreIcc?: boolean | undefined;\n        /** Number of pages to extract for multi-page input (GIF, TIFF, PDF), use -1 for all pages */\n        pages?: number | undefined;\n        /** Page number to start extracting from for multi-page input (GIF, TIFF, PDF), zero based. (optional, default 0) */\n        page?: number | undefined;\n        /** TIFF specific input options */\n        tiff?: TiffInputOptions | undefined;\n        /** SVG specific input options */\n        svg?: SvgInputOptions | undefined;\n        /** PDF specific input options */\n        pdf?: PdfInputOptions | undefined;\n        /** OpenSlide specific input options */\n        openSlide?: OpenSlideInputOptions | undefined;\n        /** JPEG 2000 specific input options */\n        jp2?: Jp2InputOptions | undefined;\n        /** @deprecated Use {@link SharpOptions.tiff} instead */\n        subifd?: number | undefined;\n        /** @deprecated Use {@link SharpOptions.pdf} instead */\n        pdfBackground?: Colour | Color | undefined;\n        /** @deprecated Use {@link SharpOptions.openSlide} instead */\n        level?: number | undefined;\n        /** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default false) */\n        animated?: boolean | undefined;\n        /** Describes raw pixel input image data. See raw() for pixel ordering. */\n        raw?: CreateRaw | undefined;\n        /** Describes a new image to be created. */\n        create?: Create | undefined;\n        /** Describes a new text image to be created. */\n        text?: CreateText | undefined;\n        /** Describes how array of input images should be joined. */\n        join?: Join | undefined;\n    }\n\n    interface CacheOptions {\n        /** Is the maximum memory in MB to use for this cache (optional, default 50) */\n        memory?: number | undefined;\n        /** Is the maximum number of files to hold open (optional, default 20) */\n        files?: number | undefined;\n        /** Is the maximum number of operations to cache (optional, default 100) */\n        items?: number | undefined;\n    }\n\n    interface TimeoutOptions {\n        /** Number of seconds after which processing will be stopped (default 0, eg disabled) */\n        seconds: number;\n    }\n\n    interface SharpCounters {\n        /** The number of tasks this module has queued waiting for libuv to provide a worker thread from its pool. */\n        queue: number;\n        /** The number of resize tasks currently being processed. */\n        process: number;\n    }\n\n    interface Raw {\n        width: number;\n        height: number;\n        channels: Channels;\n    }\n\n    interface CreateRaw extends Raw {\n        /** Specifies that the raw input has already been premultiplied, set to true to avoid sharp premultiplying the image. (optional, default false) */\n        premultiplied?: boolean | undefined;\n        /** The height of each page/frame for animated images, must be an integral factor of the overall image height. */\n        pageHeight?: number | undefined;\n    }\n\n    type CreateChannels = 3 | 4;\n\n    interface Create {\n        /** Number of pixels wide. */\n        width: number;\n        /** Number of pixels high. */\n        height: number;\n        /** Number of bands, 3 for RGB, 4 for RGBA */\n        channels: CreateChannels;\n        /** Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. */\n        background: Colour | Color;\n        /** Describes a noise to be created. */\n        noise?: Noise | undefined;\n        /** The height of each page/frame for animated images, must be an integral factor of the overall image height. */\n        pageHeight?: number | undefined;\n\n    }\n\n    interface CreateText {\n        /** Text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`. */\n        text: string;\n        /** Font name to render with. */\n        font?: string;\n        /** Absolute filesystem path to a font file that can be used by `font`. */\n        fontfile?: string;\n        /** Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. (optional, default `0`) */\n        width?: number;\n        /**\n         * Integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution\n         * defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. (optional, default `0`)\n         */\n        height?: number;\n        /** Text alignment ('left', 'centre', 'center', 'right'). (optional, default 'left') */\n        align?: TextAlign;\n        /** Set this to true to apply justification to the text. (optional, default `false`) */\n        justify?: boolean;\n        /** The resolution (size) at which to render the text. Does not take effect if `height` is specified. (optional, default `72`) */\n        dpi?: number;\n        /**\n         * Set this to true to enable RGBA output. This is useful for colour emoji rendering,\n         * or support for pango markup features like `<span foreground=\"red\">Red!</span>`. (optional, default `false`)\n         */\n        rgba?: boolean;\n        /** Text line height in points. Will use the font line height if none is specified. (optional, default `0`) */\n        spacing?: number;\n        /** Word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none' */\n        wrap?: TextWrap;\n    }\n\n    interface Join {\n        /** Number of images per row. */\n        across?: number | undefined;\n        /** Treat input as frames of an animated image. */\n        animated?: boolean | undefined;\n        /** Space between images, in pixels. */\n        shim?: number | undefined;\n        /** Background colour. */\n        background?: Colour | Color | undefined;\n        /** Horizontal alignment. */\n        halign?: HorizontalAlignment | undefined;\n        /** Vertical alignment. */\n        valign?: VerticalAlignment | undefined;\n    }\n\n    interface TiffInputOptions {\n        /** Sub Image File Directory to extract, defaults to main image. Use -1 for all subifds. */\n        subifd?: number | undefined;\n    }\n\n    interface SvgInputOptions {\n        /** Custom CSS for SVG input, applied with a User Origin during the CSS cascade. */\n        stylesheet?: string | undefined;\n        /** Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA. */\n        highBitdepth?: boolean | undefined;\n    }\n\n    interface PdfInputOptions {\n        /** Background colour to use when PDF is partially transparent. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick. */\n        background?: Colour | Color | undefined;\n    }\n\n    interface OpenSlideInputOptions {\n        /** Level to extract from a multi-level input, zero based. (optional, default 0) */\n        level?: number | undefined;\n    }\n\n    interface Jp2InputOptions {\n        /** Set to `true` to load JPEG 2000 images using [oneshot mode](https://github.com/libvips/libvips/issues/4205) */\n        oneshot?: boolean | undefined;\n    }\n\n    interface ExifDir {\n        [k: string]: string;\n    }\n\n    interface Exif {\n        'IFD0'?: ExifDir;\n        'IFD1'?: ExifDir;\n        'IFD2'?: ExifDir;\n        'IFD3'?: ExifDir;\n    }\n\n    type HeifCompression = 'av1' | 'hevc';\n\n    type Unit = 'inch' | 'cm';\n\n    interface WriteableMetadata {\n        /** Number of pixels per inch (DPI) */\n        density?: number | undefined;\n        /** Value between 1 and 8, used to update the EXIF Orientation tag. */\n        orientation?: number | undefined;\n        /**\n         * Filesystem path to output ICC profile, defaults to sRGB.\n         * @deprecated Use `withIccProfile()` instead.\n        */\n        icc?: string | undefined;\n        /**\n         * Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.\n         * @deprecated Use `withExif()` or `withExifMerge()` instead.\n         */\n        exif?: Exif | undefined;\n    }\n\n    interface Metadata {\n        /** Number value of the EXIF Orientation header, if present */\n        orientation?: number | undefined;\n        /** Name of decoder used to decompress image data e.g. jpeg, png, webp, gif, svg */\n        format: keyof FormatEnum;\n        /** Total size of image in bytes, for Stream and Buffer input only */\n        size?: number | undefined;\n        /** Number of pixels wide (EXIF orientation is not taken into consideration) */\n        width: number;\n        /** Number of pixels high (EXIF orientation is not taken into consideration) */\n        height: number;\n        /** Any changed metadata after the image orientation is applied. */\n        autoOrient: {\n            /** Number of pixels wide (EXIF orientation is taken into consideration) */\n            width: number;\n            /** Number of pixels high (EXIF orientation is taken into consideration) */\n            height: number;\n        };\n        /** Name of colour space interpretation */\n        space: keyof ColourspaceEnum;\n        /** Number of bands e.g. 3 for sRGB, 4 for CMYK */\n        channels: Channels;\n        /** Name of pixel depth format e.g. uchar, char, ushort, float ... */\n        depth: keyof DepthEnum;\n        /** Number of pixels per inch (DPI), if present */\n        density?: number | undefined;\n        /** String containing JPEG chroma subsampling, 4:2:0 or 4:4:4 for RGB, 4:2:0:4 or 4:4:4:4 for CMYK */\n        chromaSubsampling?: string | undefined;\n        /** Boolean indicating whether the image is interlaced using a progressive scan */\n        isProgressive: boolean;\n        /** Boolean indicating whether the image is palette-based (GIF, PNG). */\n        isPalette: boolean;\n        /** Number of bits per sample for each channel (GIF, PNG). */\n        bitsPerSample?: number | undefined;\n        /** Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP */\n        pages?: number | undefined;\n        /** Number of pixels high each page in a multi-page image will be. */\n        pageHeight?: number | undefined;\n        /** Number of times to loop an animated image, zero refers to a continuous loop. */\n        loop?: number | undefined;\n        /** Delay in ms between each page in an animated image, provided as an array of integers. */\n        delay?: number[] | undefined;\n        /**  Number of the primary page in a HEIF image */\n        pagePrimary?: number | undefined;\n        /** Boolean indicating the presence of an embedded ICC profile */\n        hasProfile: boolean;\n        /** Boolean indicating the presence of an alpha transparency channel */\n        hasAlpha: boolean;\n        /** Buffer containing raw EXIF data, if present */\n        exif?: Buffer | undefined;\n        /** Buffer containing raw ICC profile data, if present */\n        icc?: Buffer | undefined;\n        /** Buffer containing raw IPTC data, if present */\n        iptc?: Buffer | undefined;\n        /** Buffer containing raw XMP data, if present */\n        xmp?: Buffer | undefined;\n        /** String containing XMP data, if valid UTF-8 */\n        xmpAsString?: string | undefined;\n        /** Buffer containing raw TIFFTAG_PHOTOSHOP data, if present */\n        tifftagPhotoshop?: Buffer | undefined;\n        /** The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) */\n        compression?: HeifCompression | undefined;\n        /** Default background colour, if present, for PNG (bKGD) and GIF images */\n        background?: { r: number; g: number; b: number } | { gray: number };\n        /** Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide */\n        levels?: LevelMetadata[] | undefined;\n        /** Number of Sub Image File Directories in an OME-TIFF image */\n        subifds?: number | undefined;\n        /** The unit of resolution (density) */\n        resolutionUnit?: Unit | undefined;\n        /** String containing format for images loaded via *magick */\n        formatMagick?: string | undefined;\n        /** Array of keyword/text pairs representing PNG text blocks, if present. */\n        comments?: CommentsMetadata[] | undefined;\n    }\n\n    interface LevelMetadata {\n        width: number;\n        height: number;\n    }\n\n    interface CommentsMetadata {\n        keyword: string;\n        text: string;\n    }\n\n    interface Stats {\n        /** Array of channel statistics for each channel in the image. */\n        channels: ChannelStats[];\n        /** Value to identify if the image is opaque or transparent, based on the presence and use of alpha channel */\n        isOpaque: boolean;\n        /** Histogram-based estimation of greyscale entropy, discarding alpha channel if any (experimental) */\n        entropy: number;\n        /** Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any (experimental) */\n        sharpness: number;\n        /** Object containing most dominant sRGB colour based on a 4096-bin 3D histogram (experimental) */\n        dominant: { r: number; g: number; b: number };\n    }\n\n    interface ChannelStats {\n        /** minimum value in the channel */\n        min: number;\n        /** maximum value in the channel */\n        max: number;\n        /** sum of all values in a channel */\n        sum: number;\n        /** sum of squared values in a channel */\n        squaresSum: number;\n        /** mean of the values in a channel */\n        mean: number;\n        /** standard deviation for the values in a channel */\n        stdev: number;\n        /** x-coordinate of one of the pixel where the minimum lies */\n        minX: number;\n        /** y-coordinate of one of the pixel where the minimum lies */\n        minY: number;\n        /** x-coordinate of one of the pixel where the maximum lies */\n        maxX: number;\n        /** y-coordinate of one of the pixel where the maximum lies */\n        maxY: number;\n    }\n\n    interface OutputOptions {\n        /** Force format output, otherwise attempt to use input format (optional, default true) */\n        force?: boolean | undefined;\n    }\n\n    interface WithIccProfileOptions {\n        /**  Should the ICC profile be included in the output image metadata? (optional, default true) */\n        attach?: boolean | undefined;\n    }\n\n    interface JpegOptions extends OutputOptions {\n        /** Quality, integer 1-100 (optional, default 80) */\n        quality?: number | undefined;\n        /** Use progressive (interlace) scan (optional, default false) */\n        progressive?: boolean | undefined;\n        /** Set to '4:4:4' to prevent chroma subsampling when quality <= 90 (optional, default '4:2:0') */\n        chromaSubsampling?: string | undefined;\n        /** Apply trellis quantisation (optional, default  false) */\n        trellisQuantisation?: boolean | undefined;\n        /** Apply overshoot deringing (optional, default  false) */\n        overshootDeringing?: boolean | undefined;\n        /** Optimise progressive scans, forces progressive (optional, default false) */\n        optimiseScans?: boolean | undefined;\n        /** Alternative spelling of optimiseScans (optional, default false) */\n        optimizeScans?: boolean | undefined;\n        /** Optimise Huffman coding tables (optional, default true) */\n        optimiseCoding?: boolean | undefined;\n        /** Alternative spelling of optimiseCoding (optional, default true) */\n        optimizeCoding?: boolean | undefined;\n        /** Quantization table to use, integer 0-8 (optional, default 0) */\n        quantisationTable?: number | undefined;\n        /** Alternative spelling of quantisationTable (optional, default 0) */\n        quantizationTable?: number | undefined;\n        /** Use mozjpeg defaults (optional, default false) */\n        mozjpeg?: boolean | undefined;\n    }\n\n    interface Jp2Options extends OutputOptions {\n        /** Quality, integer 1-100 (optional, default 80) */\n        quality?: number;\n        /** Use lossless compression mode (optional, default false) */\n        lossless?: boolean;\n        /** Horizontal tile size (optional, default 512) */\n        tileWidth?: number;\n        /** Vertical tile size (optional, default 512) */\n        tileHeight?: number;\n        /** Set to '4:2:0' to enable chroma subsampling (optional, default '4:4:4') */\n        chromaSubsampling?: '4:4:4' | '4:2:0';\n    }\n\n    interface JxlOptions extends OutputOptions {\n        /** Maximum encoding error, between 0 (highest quality) and 15 (lowest quality) (optional, default 1.0) */\n        distance?: number;\n        /** Calculate distance based on JPEG-like quality, between 1 and 100, overrides distance if specified */\n        quality?: number;\n        /** Target decode speed tier, between 0 (highest quality) and 4 (lowest quality) (optional, default 0) */\n        decodingTier?: number;\n        /** Use lossless compression (optional, default false) */\n        lossless?: boolean;\n        /** CPU effort, between 3 (fastest) and 9 (slowest) (optional, default 7) */\n        effort?: number | undefined;\n    }\n\n    interface WebpOptions extends OutputOptions, AnimationOptions {\n        /** Quality, integer 1-100 (optional, default 80) */\n        quality?: number | undefined;\n        /** Quality of alpha layer, number from 0-100 (optional, default 100) */\n        alphaQuality?: number | undefined;\n        /** Use lossless compression mode (optional, default false) */\n        lossless?: boolean | undefined;\n        /** Use near_lossless compression mode (optional, default false) */\n        nearLossless?: boolean | undefined;\n        /** Use high quality chroma subsampling (optional, default false) */\n        smartSubsample?: boolean | undefined;\n        /** Auto-adjust the deblocking filter, slow but can improve low contrast edges (optional, default false) */\n        smartDeblock?: boolean | undefined;\n        /** Level of CPU effort to reduce file size, integer 0-6 (optional, default 4) */\n        effort?: number | undefined;\n        /** Prevent use of animation key frames to minimise file size (slow) (optional, default false) */\n        minSize?: boolean;\n        /** Allow mixture of lossy and lossless animation frames (slow) (optional, default false) */\n        mixed?: boolean;\n        /** Preset options: one of default, photo, picture, drawing, icon, text (optional, default 'default') */\n        preset?: keyof PresetEnum | undefined;\n    }\n\n    interface AvifOptions extends OutputOptions {\n        /** quality, integer 1-100 (optional, default 50) */\n        quality?: number | undefined;\n        /** use lossless compression (optional, default false) */\n        lossless?: boolean | undefined;\n        /** Level of CPU effort to reduce file size, between 0 (fastest) and 9 (slowest) (optional, default 4) */\n        effort?: number | undefined;\n        /** set to '4:2:0' to use chroma subsampling, requires libvips v8.11.0 (optional, default '4:4:4') */\n        chromaSubsampling?: string | undefined;\n        /** Set bitdepth to 8, 10 or 12 bit (optional, default 8) */\n        bitdepth?: 8 | 10 | 12 | undefined;\n    }\n\n    interface HeifOptions extends OutputOptions {\n        /** quality, integer 1-100 (optional, default 50) */\n        quality?: number | undefined;\n        /** compression format: av1, hevc (optional, default 'av1') */\n        compression?: HeifCompression | undefined;\n        /** use lossless compression (optional, default false) */\n        lossless?: boolean | undefined;\n        /** Level of CPU effort to reduce file size, between 0 (fastest) and 9 (slowest) (optional, default 4) */\n        effort?: number | undefined;\n        /** set to '4:2:0' to use chroma subsampling (optional, default '4:4:4') */\n        chromaSubsampling?: string | undefined;\n        /** Set bitdepth to 8, 10 or 12 bit (optional, default 8) */\n        bitdepth?: 8 | 10 | 12 | undefined;\n    }\n\n    interface GifOptions extends OutputOptions, AnimationOptions {\n        /** Re-use existing palette, otherwise generate new (slow) */\n        reuse?: boolean | undefined;\n        /** Use progressive (interlace) scan */\n        progressive?: boolean | undefined;\n        /** Maximum number of palette entries, including transparency, between 2 and 256 (optional, default 256) */\n        colours?: number | undefined;\n        /** Alternative spelling of \"colours\". Maximum number of palette entries, including transparency, between 2 and 256 (optional, default 256) */\n        colors?: number | undefined;\n        /** Level of CPU effort to reduce file size, between 1 (fastest) and 10 (slowest) (optional, default 7) */\n        effort?: number | undefined;\n        /** Level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default 1.0) */\n        dither?: number | undefined;\n        /** Maximum inter-frame error for transparency, between 0 (lossless) and 32 (optional, default 0) */\n        interFrameMaxError?: number | undefined;\n        /** Maximum inter-palette error for palette reuse, between 0 and 256 (optional, default 3) */\n        interPaletteMaxError?: number | undefined;\n        /** Keep duplicate frames in the output instead of combining them (optional, default false) */\n        keepDuplicateFrames?: boolean | undefined;\n    }\n\n    interface TiffOptions extends OutputOptions {\n        /** Quality, integer 1-100 (optional, default 80) */\n        quality?: number | undefined;\n        /** Compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k (optional, default 'jpeg') */\n        compression?: string | undefined;\n        /** Use BigTIFF variant (has no effect when compression is none) (optional, default false) */\n        bigtiff?: boolean | undefined;\n        /** Compression predictor options: none, horizontal, float (optional, default 'horizontal') */\n        predictor?: string | undefined;\n        /** Write an image pyramid (optional, default false) */\n        pyramid?: boolean | undefined;\n        /** Write a tiled tiff (optional, default false) */\n        tile?: boolean | undefined;\n        /** Horizontal tile size (optional, default 256) */\n        tileWidth?: number | undefined;\n        /** Vertical tile size (optional, default 256) */\n        tileHeight?: number | undefined;\n        /** Horizontal resolution in pixels/mm (optional, default 1.0) */\n        xres?: number | undefined;\n        /** Vertical resolution in pixels/mm (optional, default 1.0) */\n        yres?: number | undefined;\n        /** Reduce bitdepth to 1, 2 or 4 bit (optional, default 8) */\n        bitdepth?: 1 | 2 | 4 | 8 | undefined;\n        /** Write 1-bit images as miniswhite (optional, default false) */\n        miniswhite?: boolean | undefined;\n        /** Resolution unit options: inch, cm (optional, default 'inch') */\n        resolutionUnit?: Unit | undefined;\n    }\n\n    interface PngOptions extends OutputOptions {\n        /** Use progressive (interlace) scan (optional, default false) */\n        progressive?: boolean | undefined;\n        /** zlib compression level, 0-9 (optional, default 6) */\n        compressionLevel?: number | undefined;\n        /** Use adaptive row filtering (optional, default false) */\n        adaptiveFiltering?: boolean | undefined;\n        /** Use the lowest number of colours needed to achieve given quality (optional, default `100`) */\n        quality?: number | undefined;\n        /** Level of CPU effort to reduce file size, between 1 (fastest) and 10 (slowest), sets palette to true (optional, default 7) */\n        effort?: number | undefined;\n        /** Quantise to a palette-based image with alpha transparency support (optional, default false) */\n        palette?: boolean | undefined;\n        /** Maximum number of palette entries (optional, default 256) */\n        colours?: number | undefined;\n        /** Alternative Spelling of \"colours\". Maximum number of palette entries (optional, default 256) */\n        colors?: number | undefined;\n        /**  Level of Floyd-Steinberg error diffusion (optional, default 1.0) */\n        dither?: number | undefined;\n    }\n\n    interface RotateOptions {\n        /** parsed by the color module to extract values for red, green, blue and alpha. (optional, default \"#000000\") */\n        background?: Colour | Color | undefined;\n    }\n\n    type Precision = 'integer' | 'float' | 'approximate';\n\n    interface BlurOptions {\n        /** A value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2` */\n        sigma: number;\n        /** A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. */\n        minAmplitude?: number;\n        /** How accurate the operation should be, one of: integer, float, approximate. (optional, default \"integer\") */\n        precision?: Precision | undefined;\n    }\n\n    interface FlattenOptions {\n        /** background colour, parsed by the color module, defaults to black. (optional, default {r:0,g:0,b:0}) */\n        background?: Colour | Color | undefined;\n    }\n\n    interface NegateOptions {\n        /** whether or not to negate any alpha channel. (optional, default true) */\n        alpha?: boolean | undefined;\n    }\n\n    interface NormaliseOptions {\n        /** Percentile below which luminance values will be underexposed. */\n        lower?: number | undefined;\n        /** Percentile above which luminance values will be overexposed. */\n        upper?: number | undefined;\n    }\n\n    interface ResizeOptions {\n        /** Alternative means of specifying width. If both are present this takes priority. */\n        width?: number | undefined;\n        /** Alternative means of specifying height. If both are present this takes priority. */\n        height?: number | undefined;\n        /** How the image should be resized to fit both provided dimensions, one of cover, contain, fill, inside or outside. (optional, default 'cover') */\n        fit?: keyof FitEnum | undefined;\n        /** Position, gravity or strategy to use when fit is cover or contain. (optional, default 'centre') */\n        position?: number | string | undefined;\n        /** Background colour when using a fit of contain, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */\n        background?: Colour | Color | undefined;\n        /** The kernel to use for image reduction. (optional, default 'lanczos3') */\n        kernel?: keyof KernelEnum | undefined;\n        /** Do not enlarge if the width or height are already less than the specified dimensions, equivalent to GraphicsMagick's > geometry option. (optional, default false) */\n        withoutEnlargement?: boolean | undefined;\n        /** Do not reduce if the width or height are already greater than the specified dimensions, equivalent to GraphicsMagick's < geometry option. (optional, default false) */\n        withoutReduction?: boolean | undefined;\n        /** Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default true) */\n        fastShrinkOnLoad?: boolean | undefined;\n    }\n\n    interface Region {\n        /** zero-indexed offset from left edge */\n        left: number;\n        /** zero-indexed offset from top edge */\n        top: number;\n        /** dimension of extracted image */\n        width: number;\n        /** dimension of extracted image */\n        height: number;\n    }\n\n    interface Noise {\n        /** type of generated noise, currently only gaussian is supported. */\n        type: 'gaussian';\n        /** mean of pixels in generated noise. */\n        mean?: number | undefined;\n        /** standard deviation of pixels in generated noise. */\n        sigma?: number | undefined;\n    }\n\n    type ExtendWith = 'background' | 'copy' | 'repeat' | 'mirror';\n\n    interface ExtendOptions {\n        /** single pixel count to top edge (optional, default 0) */\n        top?: number | undefined;\n        /** single pixel count to left edge (optional, default 0) */\n        left?: number | undefined;\n        /** single pixel count to bottom edge (optional, default 0) */\n        bottom?: number | undefined;\n        /** single pixel count to right edge (optional, default 0) */\n        right?: number | undefined;\n        /** background colour, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */\n        background?: Colour | Color | undefined;\n        /** how the extension is done, one of: \"background\", \"copy\", \"repeat\", \"mirror\" (optional, default `'background'`) */\n        extendWith?: ExtendWith | undefined;\n    }\n\n    interface TrimOptions {\n        /** Background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */\n        background?: Colour | Color | undefined;\n        /** Allowed difference from the above colour, a positive number. (optional, default 10) */\n        threshold?: number | undefined;\n        /** Does the input more closely resemble line art (e.g. vector) rather than being photographic? (optional, default false) */\n        lineArt?: boolean | undefined;\n    }\n\n    interface RawOptions {\n        depth?: keyof DepthEnum;\n    }\n\n    /** 1 for grayscale, 2 for grayscale + alpha, 3 for sRGB, 4 for CMYK or RGBA */\n    type Channels = 1 | 2 | 3 | 4;\n\n    interface RGBA {\n        r?: number | undefined;\n        g?: number | undefined;\n        b?: number | undefined;\n        alpha?: number | undefined;\n    }\n\n    type Colour = string | RGBA;\n    type Color = Colour;\n\n    interface Kernel {\n        /** width of the kernel in pixels. */\n        width: number;\n        /** height of the kernel in pixels. */\n        height: number;\n        /** Array of length width*height containing the kernel values. */\n        kernel: ArrayLike<number>;\n        /** the scale of the kernel in pixels. (optional, default sum) */\n        scale?: number | undefined;\n        /** the offset of the kernel in pixels. (optional, default 0) */\n        offset?: number | undefined;\n    }\n\n    interface ClaheOptions {\n        /** width of the region */\n        width: number;\n        /** height of the region */\n        height: number;\n        /** max slope of the cumulative contrast. A value of 0 disables contrast limiting. Valid values are integers in the range 0-100 (inclusive) (optional, default 3) */\n        maxSlope?: number | undefined;\n    }\n\n    interface ThresholdOptions {\n        /** convert to single channel greyscale. (optional, default true) */\n        greyscale?: boolean | undefined;\n        /** alternative spelling for greyscale. (optional, default true) */\n        grayscale?: boolean | undefined;\n    }\n\n    interface OverlayOptions extends SharpOptions {\n        /** Buffer containing image data, String containing the path to an image file, or Create object  */\n        input?: string | Buffer | { create: Create } | { text: CreateText } | { raw: CreateRaw } | undefined;\n        /** how to blend this image with the image below. (optional, default `'over'`) */\n        blend?: Blend | undefined;\n        /** gravity at which to place the overlay. (optional, default 'centre') */\n        gravity?: Gravity | undefined;\n        /** the pixel offset from the top edge. */\n        top?: number | undefined;\n        /** the pixel offset from the left edge. */\n        left?: number | undefined;\n        /** set to true to repeat the overlay image across the entire image with the given  gravity. (optional, default false) */\n        tile?: boolean | undefined;\n        /** Set to true to avoid premultipling the image below. Equivalent to the --premultiplied vips option. */\n        premultiplied?: boolean | undefined;\n        /** number representing the DPI for vector overlay image. (optional, default 72)*/\n        density?: number | undefined;\n        /** Set to true to read all frames/pages of an animated image. (optional, default false) */\n        animated?: boolean | undefined;\n        /** see sharp() constructor, (optional, default 'warning') */\n        failOn?: FailOnOptions | undefined;\n        /** see sharp() constructor, (optional, default 268402689) */\n        limitInputPixels?: number | boolean | undefined;\n        /** see sharp() constructor, (optional, default false) */\n        autoOrient?: boolean | undefined;\n    }\n\n    interface TileOptions {\n        /** Tile size in pixels, a value between 1 and 8192. (optional, default 256) */\n        size?: number | undefined;\n        /** Tile overlap in pixels, a value between 0 and 8192. (optional, default 0) */\n        overlap?: number | undefined;\n        /** Tile angle of rotation, must be a multiple of 90. (optional, default 0) */\n        angle?: number | undefined;\n        /** background colour, parsed by the color module, defaults to white without transparency. (optional, default {r:255,g:255,b:255,alpha:1}) */\n        background?: string | RGBA | undefined;\n        /** How deep to make the pyramid, possible values are \"onepixel\", \"onetile\" or \"one\" (default based on layout) */\n        depth?: string | undefined;\n        /** Threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images */\n        skipBlanks?: number | undefined;\n        /** Tile container, with value fs (filesystem) or zip (compressed file). (optional, default 'fs') */\n        container?: TileContainer | undefined;\n        /** Filesystem layout, possible values are dz, iiif, iiif3, zoomify or google. (optional, default 'dz') */\n        layout?: TileLayout | undefined;\n        /** Centre image in tile. (optional, default false) */\n        centre?: boolean | undefined;\n        /** Alternative spelling of centre. (optional, default false) */\n        center?: boolean | undefined;\n        /** When layout is iiif/iiif3, sets the @id/id attribute of info.json (optional, default 'https://example.com/iiif') */\n        id?: string | undefined;\n        /** The name of the directory within the zip file when container is `zip`. */\n        basename?: string | undefined;\n    }\n\n    interface AnimationOptions {\n        /** Number of animation iterations, a value between 0 and 65535. Use 0 for infinite animation. (optional, default 0) */\n        loop?: number | undefined;\n        /** delay(s) between animation frames (in milliseconds), each value between 0 and 65535. (optional) */\n        delay?: number | number[] | undefined;\n    }\n\n    interface SharpenOptions {\n        /** The sigma of the Gaussian mask, where sigma = 1 + radius / 2, between 0.000001 and 10000 */\n        sigma: number;\n        /** The level of sharpening to apply to \"flat\" areas, between 0 and 1000000 (optional, default 1.0) */\n        m1?: number | undefined;\n        /** The level of sharpening to apply to \"jagged\" areas, between 0 and 1000000 (optional, default 2.0) */\n        m2?: number | undefined;\n        /** Threshold between \"flat\" and \"jagged\", between 0 and 1000000 (optional, default 2.0) */\n        x1?: number | undefined;\n        /** Maximum amount of brightening, between 0 and 1000000 (optional, default 10.0) */\n        y2?: number | undefined;\n        /** Maximum amount of darkening, between 0 and 1000000 (optional, default 20.0) */\n        y3?: number | undefined;\n    }\n\n    interface AffineOptions {\n        /** Parsed by the color module to extract values for red, green, blue and alpha. (optional, default \"#000000\") */\n        background?: string | object | undefined;\n        /** Input horizontal offset (optional, default 0) */\n        idx?: number | undefined;\n        /** Input vertical offset (optional, default 0) */\n        idy?: number | undefined;\n        /** Output horizontal offset (optional, default 0) */\n        odx?: number | undefined;\n        /** Output horizontal offset (optional, default 0) */\n        ody?: number | undefined;\n        /** Interpolator (optional, default sharp.interpolators.bicubic) */\n        interpolator?: Interpolators[keyof Interpolators] | undefined;\n    }\n\n    interface OutputInfo {\n        format: string;\n        size: number;\n        width: number;\n        height: number;\n        channels: Channels;\n        /** indicating if premultiplication was used */\n        premultiplied: boolean;\n        /** Only defined when using a crop strategy */\n        cropOffsetLeft?: number | undefined;\n        /** Only defined when using a crop strategy */\n        cropOffsetTop?: number | undefined;\n        /** Only defined when using a trim method */\n        trimOffsetLeft?: number | undefined;\n        /** Only defined when using a trim method */\n        trimOffsetTop?: number | undefined;\n        /** DPI the font was rendered at, only defined when using `text` input */\n        textAutofitDpi?: number | undefined;\n        /** When using the attention crop strategy, the focal point of the cropped region */\n        attentionX?: number | undefined;\n        attentionY?: number | undefined;\n        /** Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP */\n        pages?: number | undefined;\n        /** Number of pixels high each page in a multi-page image will be. */\n        pageHeight?: number | undefined;\n    }\n\n    interface AvailableFormatInfo {\n        id: string;\n        input: { file: boolean; buffer: boolean; stream: boolean; fileSuffix?: string[] };\n        output: { file: boolean; buffer: boolean; stream: boolean; alias?: string[] };\n    }\n\n    interface FitEnum {\n        contain: 'contain';\n        cover: 'cover';\n        fill: 'fill';\n        inside: 'inside';\n        outside: 'outside';\n    }\n\n    interface KernelEnum {\n        nearest: 'nearest';\n        cubic: 'cubic';\n        linear: 'linear';\n        mitchell: 'mitchell';\n        lanczos2: 'lanczos2';\n        lanczos3: 'lanczos3';\n        mks2013: 'mks2013';\n        mks2021: 'mks2021';\n    }\n\n    interface PresetEnum {\n        default: 'default';\n        picture: 'picture';\n        photo: 'photo';\n        drawing: 'drawing';\n        icon: 'icon';\n        text: 'text';\n    }\n\n    interface BoolEnum {\n        and: 'and';\n        or: 'or';\n        eor: 'eor';\n    }\n\n    interface ColourspaceEnum {\n        'b-w': string;\n        cmc: string;\n        cmyk: string;\n        fourier: string;\n        grey16: string;\n        histogram: string;\n        hsv: string;\n        lab: string;\n        labq: string;\n        labs: string;\n        lch: string;\n        matrix: string;\n        multiband: string;\n        rgb: string;\n        rgb16: string;\n        scrgb: string;\n        srgb: string;\n        xyz: string;\n        yxy: string;\n    }\n\n    interface DepthEnum {\n        char: string;\n        complex: string;\n        double: string;\n        dpcomplex: string;\n        float: string;\n        int: string;\n        short: string;\n        uchar: string;\n        uint: string;\n        ushort: string;\n    }\n\n    type FailOnOptions = 'none' | 'truncated' | 'error' | 'warning';\n\n    type TextAlign = 'left' | 'centre' | 'center' | 'right';\n\n    type TextWrap = 'word' | 'char' | 'word-char' | 'none';\n\n    type HorizontalAlignment = 'left' | 'centre' | 'center' | 'right';\n\n    type VerticalAlignment = 'top' | 'centre' | 'center' | 'bottom';\n\n    type TileContainer = 'fs' | 'zip';\n\n    type TileLayout = 'dz' | 'iiif' | 'iiif3' | 'zoomify' | 'google';\n\n    type Blend =\n        | 'clear'\n        | 'source'\n        | 'over'\n        | 'in'\n        | 'out'\n        | 'atop'\n        | 'dest'\n        | 'dest-over'\n        | 'dest-in'\n        | 'dest-out'\n        | 'dest-atop'\n        | 'xor'\n        | 'add'\n        | 'saturate'\n        | 'multiply'\n        | 'screen'\n        | 'overlay'\n        | 'darken'\n        | 'lighten'\n        | 'color-dodge'\n        | 'colour-dodge'\n        | 'color-burn'\n        | 'colour-burn'\n        | 'hard-light'\n        | 'soft-light'\n        | 'difference'\n        | 'exclusion';\n\n    type Gravity = number | string;\n\n    interface GravityEnum {\n        north: number;\n        northeast: number;\n        southeast: number;\n        south: number;\n        southwest: number;\n        west: number;\n        northwest: number;\n        east: number;\n        center: number;\n        centre: number;\n    }\n\n    interface StrategyEnum {\n        entropy: number;\n        attention: number;\n    }\n\n    interface FormatEnum {\n        avif: AvailableFormatInfo;\n        dcraw: AvailableFormatInfo;\n        dz: AvailableFormatInfo;\n        exr: AvailableFormatInfo;\n        fits: AvailableFormatInfo;\n        gif: AvailableFormatInfo;\n        heif: AvailableFormatInfo;\n        input: AvailableFormatInfo;\n        jpeg: AvailableFormatInfo;\n        jpg: AvailableFormatInfo;\n        jp2: AvailableFormatInfo;\n        jxl: AvailableFormatInfo;\n        magick: AvailableFormatInfo;\n        openslide: AvailableFormatInfo;\n        pdf: AvailableFormatInfo;\n        png: AvailableFormatInfo;\n        ppm: AvailableFormatInfo;\n        rad: AvailableFormatInfo;\n        raw: AvailableFormatInfo;\n        svg: AvailableFormatInfo;\n        tiff: AvailableFormatInfo;\n        tif: AvailableFormatInfo;\n        v: AvailableFormatInfo;\n        webp: AvailableFormatInfo;\n    }\n\n    interface CacheResult {\n        memory: { current: number; high: number; max: number };\n        files: { current: number; max: number };\n        items: { current: number; max: number };\n    }\n\n    interface Interpolators {\n        /** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */\n        nearest: 'nearest';\n        /** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */\n        bilinear: 'bilinear';\n        /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */\n        bicubic: 'bicubic';\n        /**\n         * [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100).\n         * Prevents some \"[acutance](http://en.wikipedia.org/wiki/Acutance)\" but typically reduces performance by a factor of 2.\n         */\n        locallyBoundedBicubic: 'lbb';\n        /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */\n        nohalo: 'nohalo';\n        /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents \"staircasing\" when enlarging. */\n        vertexSplitQuadraticBasisSpline: 'vsqbs';\n    }\n\n    type Matrix2x2 = [[number, number], [number, number]];\n    type Matrix3x3 = [[number, number, number], [number, number, number], [number, number, number]];\n    type Matrix4x4 = [[number, number, number, number], [number, number, number, number], [number, number, number, number], [number, number, number, number]];\n}\n\nexport = sharp;\n"
  },
  {
    "path": "lib/index.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst Sharp = require('./constructor');\nrequire('./input')(Sharp);\nrequire('./resize')(Sharp);\nrequire('./composite')(Sharp);\nrequire('./operation')(Sharp);\nrequire('./colour')(Sharp);\nrequire('./channel')(Sharp);\nrequire('./output')(Sharp);\nrequire('./utility')(Sharp);\n\nmodule.exports = Sharp;\n"
  },
  {
    "path": "lib/input.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst is = require('./is');\nconst sharp = require('./sharp');\n\n/**\n * Justification alignment\n * @member\n * @private\n */\nconst align = {\n  left: 'low',\n  top: 'low',\n  low: 'low',\n  center: 'centre',\n  centre: 'centre',\n  right: 'high',\n  bottom: 'high',\n  high: 'high'\n};\n\nconst inputStreamParameters = [\n  // Limits and error handling\n  'failOn', 'limitInputPixels', 'unlimited',\n  // Format-generic\n  'animated', 'autoOrient', 'density', 'ignoreIcc', 'page', 'pages', 'sequentialRead',\n  // Format-specific\n  'jp2', 'openSlide', 'pdf', 'raw', 'svg', 'tiff',\n  // Deprecated\n  'failOnError', 'openSlideLevel', 'pdfBackground', 'tiffSubifd'\n];\n\n/**\n * Extract input options, if any, from an object.\n * @private\n */\nfunction _inputOptionsFromObject (obj) {\n  const params = inputStreamParameters\n    .filter(p => is.defined(obj[p]))\n    .map(p => ([p, obj[p]]));\n  return params.length\n    ? Object.fromEntries(params)\n    : undefined;\n}\n\n/**\n * Create Object containing input and input-related options.\n * @private\n */\nfunction _createInputDescriptor (input, inputOptions, containerOptions) {\n  const inputDescriptor = {\n    autoOrient: false,\n    failOn: 'warning',\n    limitInputPixels: 0x3FFF ** 2,\n    ignoreIcc: false,\n    unlimited: false,\n    sequentialRead: true\n  };\n  if (is.string(input)) {\n    // filesystem\n    inputDescriptor.file = input;\n  } else if (is.buffer(input)) {\n    // Buffer\n    if (input.length === 0) {\n      throw Error('Input Buffer is empty');\n    }\n    inputDescriptor.buffer = input;\n  } else if (is.arrayBuffer(input)) {\n    if (input.byteLength === 0) {\n      throw Error('Input bit Array is empty');\n    }\n    inputDescriptor.buffer = Buffer.from(input, 0, input.byteLength);\n  } else if (is.typedArray(input)) {\n    if (input.length === 0) {\n      throw Error('Input Bit Array is empty');\n    }\n    inputDescriptor.buffer = Buffer.from(input.buffer, input.byteOffset, input.byteLength);\n  } else if (is.plainObject(input) && !is.defined(inputOptions)) {\n    // Plain Object descriptor, e.g. create\n    inputOptions = input;\n    if (_inputOptionsFromObject(inputOptions)) {\n      // Stream with options\n      inputDescriptor.buffer = [];\n    }\n  } else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) {\n    // Stream without options\n    inputDescriptor.buffer = [];\n  } else if (Array.isArray(input)) {\n    if (input.length > 1) {\n      // Join images together\n      if (!this.options.joining) {\n        this.options.joining = true;\n        this.options.join = input.map(i => this._createInputDescriptor(i));\n      } else {\n        throw new Error('Recursive join is unsupported');\n      }\n    } else {\n      throw new Error('Expected at least two images to join');\n    }\n  } else {\n    throw new Error(`Unsupported input '${input}' of type ${typeof input}${\n      is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : ''\n    }`);\n  }\n  if (is.object(inputOptions)) {\n    // Deprecated: failOnError\n    if (is.defined(inputOptions.failOnError)) {\n      if (is.bool(inputOptions.failOnError)) {\n        inputDescriptor.failOn = inputOptions.failOnError ? 'warning' : 'none';\n      } else {\n        throw is.invalidParameterError('failOnError', 'boolean', inputOptions.failOnError);\n      }\n    }\n    // failOn\n    if (is.defined(inputOptions.failOn)) {\n      if (is.string(inputOptions.failOn) && is.inArray(inputOptions.failOn, ['none', 'truncated', 'error', 'warning'])) {\n        inputDescriptor.failOn = inputOptions.failOn;\n      } else {\n        throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn);\n      }\n    }\n    // autoOrient\n    if (is.defined(inputOptions.autoOrient)) {\n      if (is.bool(inputOptions.autoOrient)) {\n        inputDescriptor.autoOrient = inputOptions.autoOrient;\n      } else {\n        throw is.invalidParameterError('autoOrient', 'boolean', inputOptions.autoOrient);\n      }\n    }\n    // Density\n    if (is.defined(inputOptions.density)) {\n      if (is.inRange(inputOptions.density, 1, 100000)) {\n        inputDescriptor.density = inputOptions.density;\n      } else {\n        throw is.invalidParameterError('density', 'number between 1 and 100000', inputOptions.density);\n      }\n    }\n    // Ignore embeddded ICC profile\n    if (is.defined(inputOptions.ignoreIcc)) {\n      if (is.bool(inputOptions.ignoreIcc)) {\n        inputDescriptor.ignoreIcc = inputOptions.ignoreIcc;\n      } else {\n        throw is.invalidParameterError('ignoreIcc', 'boolean', inputOptions.ignoreIcc);\n      }\n    }\n    // limitInputPixels\n    if (is.defined(inputOptions.limitInputPixels)) {\n      if (is.bool(inputOptions.limitInputPixels)) {\n        inputDescriptor.limitInputPixels = inputOptions.limitInputPixels\n          ? 0x3FFF ** 2\n          : 0;\n      } else if (is.integer(inputOptions.limitInputPixels) && is.inRange(inputOptions.limitInputPixels, 0, Number.MAX_SAFE_INTEGER)) {\n        inputDescriptor.limitInputPixels = inputOptions.limitInputPixels;\n      } else {\n        throw is.invalidParameterError('limitInputPixels', 'positive integer', inputOptions.limitInputPixels);\n      }\n    }\n    // unlimited\n    if (is.defined(inputOptions.unlimited)) {\n      if (is.bool(inputOptions.unlimited)) {\n        inputDescriptor.unlimited = inputOptions.unlimited;\n      } else {\n        throw is.invalidParameterError('unlimited', 'boolean', inputOptions.unlimited);\n      }\n    }\n    // sequentialRead\n    if (is.defined(inputOptions.sequentialRead)) {\n      if (is.bool(inputOptions.sequentialRead)) {\n        inputDescriptor.sequentialRead = inputOptions.sequentialRead;\n      } else {\n        throw is.invalidParameterError('sequentialRead', 'boolean', inputOptions.sequentialRead);\n      }\n    }\n    // Raw pixel input\n    if (is.defined(inputOptions.raw)) {\n      if (\n        is.object(inputOptions.raw) &&\n        is.integer(inputOptions.raw.width) && inputOptions.raw.width > 0 &&\n        is.integer(inputOptions.raw.height) && inputOptions.raw.height > 0 &&\n        is.integer(inputOptions.raw.channels) && is.inRange(inputOptions.raw.channels, 1, 4)\n      ) {\n        inputDescriptor.rawWidth = inputOptions.raw.width;\n        inputDescriptor.rawHeight = inputOptions.raw.height;\n        inputDescriptor.rawChannels = inputOptions.raw.channels;\n        switch (input.constructor) {\n          case Uint8Array:\n          case Uint8ClampedArray:\n            inputDescriptor.rawDepth = 'uchar';\n            break;\n          case Int8Array:\n            inputDescriptor.rawDepth = 'char';\n            break;\n          case Uint16Array:\n            inputDescriptor.rawDepth = 'ushort';\n            break;\n          case Int16Array:\n            inputDescriptor.rawDepth = 'short';\n            break;\n          case Uint32Array:\n            inputDescriptor.rawDepth = 'uint';\n            break;\n          case Int32Array:\n            inputDescriptor.rawDepth = 'int';\n            break;\n          case Float32Array:\n            inputDescriptor.rawDepth = 'float';\n            break;\n          case Float64Array:\n            inputDescriptor.rawDepth = 'double';\n            break;\n          default:\n            inputDescriptor.rawDepth = 'uchar';\n            break;\n        }\n      } else {\n        throw new Error('Expected width, height and channels for raw pixel input');\n      }\n      inputDescriptor.rawPremultiplied = false;\n      if (is.defined(inputOptions.raw.premultiplied)) {\n        if (is.bool(inputOptions.raw.premultiplied)) {\n          inputDescriptor.rawPremultiplied = inputOptions.raw.premultiplied;\n        } else {\n          throw is.invalidParameterError('raw.premultiplied', 'boolean', inputOptions.raw.premultiplied);\n        }\n      }\n      inputDescriptor.rawPageHeight = 0;\n      if (is.defined(inputOptions.raw.pageHeight)) {\n        if (is.integer(inputOptions.raw.pageHeight) && inputOptions.raw.pageHeight > 0 && inputOptions.raw.pageHeight <= inputOptions.raw.height) {\n          if (inputOptions.raw.height % inputOptions.raw.pageHeight !== 0) {\n            throw new Error(`Expected raw.height ${inputOptions.raw.height} to be a multiple of raw.pageHeight ${inputOptions.raw.pageHeight}`);\n          }\n          inputDescriptor.rawPageHeight = inputOptions.raw.pageHeight;\n        } else {\n          throw is.invalidParameterError('raw.pageHeight', 'positive integer', inputOptions.raw.pageHeight);\n        }\n      }\n    }\n    // Multi-page input (GIF, TIFF, PDF)\n    if (is.defined(inputOptions.animated)) {\n      if (is.bool(inputOptions.animated)) {\n        inputDescriptor.pages = inputOptions.animated ? -1 : 1;\n      } else {\n        throw is.invalidParameterError('animated', 'boolean', inputOptions.animated);\n      }\n    }\n    if (is.defined(inputOptions.pages)) {\n      if (is.integer(inputOptions.pages) && is.inRange(inputOptions.pages, -1, 100000)) {\n        inputDescriptor.pages = inputOptions.pages;\n      } else {\n        throw is.invalidParameterError('pages', 'integer between -1 and 100000', inputOptions.pages);\n      }\n    }\n    if (is.defined(inputOptions.page)) {\n      if (is.integer(inputOptions.page) && is.inRange(inputOptions.page, 0, 100000)) {\n        inputDescriptor.page = inputOptions.page;\n      } else {\n        throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page);\n      }\n    }\n    // OpenSlide specific options\n    if (is.object(inputOptions.openSlide) && is.defined(inputOptions.openSlide.level)) {\n      if (is.integer(inputOptions.openSlide.level) && is.inRange(inputOptions.openSlide.level, 0, 256)) {\n        inputDescriptor.openSlideLevel = inputOptions.openSlide.level;\n      } else {\n        throw is.invalidParameterError('openSlide.level', 'integer between 0 and 256', inputOptions.openSlide.level);\n      }\n    } else if (is.defined(inputOptions.level)) {\n      // Deprecated\n      if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) {\n        inputDescriptor.openSlideLevel = inputOptions.level;\n      } else {\n        throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level);\n      }\n    }\n    // TIFF specific options\n    if (is.object(inputOptions.tiff) && is.defined(inputOptions.tiff.subifd)) {\n      if (is.integer(inputOptions.tiff.subifd) && is.inRange(inputOptions.tiff.subifd, -1, 100000)) {\n        inputDescriptor.tiffSubifd = inputOptions.tiff.subifd;\n      } else {\n        throw is.invalidParameterError('tiff.subifd', 'integer between -1 and 100000', inputOptions.tiff.subifd);\n      }\n    } else if (is.defined(inputOptions.subifd)) {\n      // Deprecated\n      if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) {\n        inputDescriptor.tiffSubifd = inputOptions.subifd;\n      } else {\n        throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd);\n      }\n    }\n    // SVG specific options\n    if (is.object(inputOptions.svg)) {\n      if (is.defined(inputOptions.svg.stylesheet)) {\n        if (is.string(inputOptions.svg.stylesheet)) {\n          inputDescriptor.svgStylesheet = inputOptions.svg.stylesheet;\n        } else {\n          throw is.invalidParameterError('svg.stylesheet', 'string', inputOptions.svg.stylesheet);\n        }\n      }\n      if (is.defined(inputOptions.svg.highBitdepth)) {\n        if (is.bool(inputOptions.svg.highBitdepth)) {\n          inputDescriptor.svgHighBitdepth = inputOptions.svg.highBitdepth;\n        } else {\n          throw is.invalidParameterError('svg.highBitdepth', 'boolean', inputOptions.svg.highBitdepth);\n        }\n      }\n    }\n    // PDF specific options\n    if (is.object(inputOptions.pdf) && is.defined(inputOptions.pdf.background)) {\n      inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdf.background);\n    } else if (is.defined(inputOptions.pdfBackground)) {\n      // Deprecated\n      inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdfBackground);\n    }\n    // JPEG 2000 specific options\n    if (is.object(inputOptions.jp2) && is.defined(inputOptions.jp2.oneshot)) {\n      if (is.bool(inputOptions.jp2.oneshot)) {\n        inputDescriptor.jp2Oneshot = inputOptions.jp2.oneshot;\n      } else {\n        throw is.invalidParameterError('jp2.oneshot', 'boolean', inputOptions.jp2.oneshot);\n      }\n    }\n    // Create new image\n    if (is.defined(inputOptions.create)) {\n      if (\n        is.object(inputOptions.create) &&\n        is.integer(inputOptions.create.width) && inputOptions.create.width > 0 &&\n        is.integer(inputOptions.create.height) && inputOptions.create.height > 0 &&\n        is.integer(inputOptions.create.channels)\n      ) {\n        inputDescriptor.createWidth = inputOptions.create.width;\n        inputDescriptor.createHeight = inputOptions.create.height;\n        inputDescriptor.createChannels = inputOptions.create.channels;\n        inputDescriptor.createPageHeight = 0;\n        if (is.defined(inputOptions.create.pageHeight)) {\n          if (is.integer(inputOptions.create.pageHeight) && inputOptions.create.pageHeight > 0 && inputOptions.create.pageHeight <= inputOptions.create.height) {\n            if (inputOptions.create.height % inputOptions.create.pageHeight !== 0) {\n              throw new Error(`Expected create.height ${inputOptions.create.height} to be a multiple of create.pageHeight ${inputOptions.create.pageHeight}`);\n            }\n            inputDescriptor.createPageHeight = inputOptions.create.pageHeight;\n          } else {\n            throw is.invalidParameterError('create.pageHeight', 'positive integer', inputOptions.create.pageHeight);\n          }\n        }\n        // Noise\n        if (is.defined(inputOptions.create.noise)) {\n          if (!is.object(inputOptions.create.noise)) {\n            throw new Error('Expected noise to be an object');\n          }\n          if (inputOptions.create.noise.type !== 'gaussian') {\n            throw new Error('Only gaussian noise is supported at the moment');\n          }\n          inputDescriptor.createNoiseType = inputOptions.create.noise.type;\n          if (!is.inRange(inputOptions.create.channels, 1, 4)) {\n            throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels);\n          }\n          inputDescriptor.createNoiseMean = 128;\n          if (is.defined(inputOptions.create.noise.mean)) {\n            if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) {\n              inputDescriptor.createNoiseMean = inputOptions.create.noise.mean;\n            } else {\n              throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean);\n            }\n          }\n          inputDescriptor.createNoiseSigma = 30;\n          if (is.defined(inputOptions.create.noise.sigma)) {\n            if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) {\n              inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma;\n            } else {\n              throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma);\n            }\n          }\n        } else if (is.defined(inputOptions.create.background)) {\n          if (!is.inRange(inputOptions.create.channels, 3, 4)) {\n            throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels);\n          }\n          inputDescriptor.createBackground = this._getBackgroundColourOption(inputOptions.create.background);\n        } else {\n          throw new Error('Expected valid noise or background to create a new input image');\n        }\n        delete inputDescriptor.buffer;\n      } else {\n        throw new Error('Expected valid width, height and channels to create a new input image');\n      }\n    }\n    // Create a new image with text\n    if (is.defined(inputOptions.text)) {\n      if (is.object(inputOptions.text) && is.string(inputOptions.text.text)) {\n        inputDescriptor.textValue = inputOptions.text.text;\n        if (is.defined(inputOptions.text.height) && is.defined(inputOptions.text.dpi)) {\n          throw new Error('Expected only one of dpi or height');\n        }\n        if (is.defined(inputOptions.text.font)) {\n          if (is.string(inputOptions.text.font)) {\n            inputDescriptor.textFont = inputOptions.text.font;\n          } else {\n            throw is.invalidParameterError('text.font', 'string', inputOptions.text.font);\n          }\n        }\n        if (is.defined(inputOptions.text.fontfile)) {\n          if (is.string(inputOptions.text.fontfile)) {\n            inputDescriptor.textFontfile = inputOptions.text.fontfile;\n          } else {\n            throw is.invalidParameterError('text.fontfile', 'string', inputOptions.text.fontfile);\n          }\n        }\n        if (is.defined(inputOptions.text.width)) {\n          if (is.integer(inputOptions.text.width) && inputOptions.text.width > 0) {\n            inputDescriptor.textWidth = inputOptions.text.width;\n          } else {\n            throw is.invalidParameterError('text.width', 'positive integer', inputOptions.text.width);\n          }\n        }\n        if (is.defined(inputOptions.text.height)) {\n          if (is.integer(inputOptions.text.height) && inputOptions.text.height > 0) {\n            inputDescriptor.textHeight = inputOptions.text.height;\n          } else {\n            throw is.invalidParameterError('text.height', 'positive integer', inputOptions.text.height);\n          }\n        }\n        if (is.defined(inputOptions.text.align)) {\n          if (is.string(inputOptions.text.align) && is.string(this.constructor.align[inputOptions.text.align])) {\n            inputDescriptor.textAlign = this.constructor.align[inputOptions.text.align];\n          } else {\n            throw is.invalidParameterError('text.align', 'valid alignment', inputOptions.text.align);\n          }\n        }\n        if (is.defined(inputOptions.text.justify)) {\n          if (is.bool(inputOptions.text.justify)) {\n            inputDescriptor.textJustify = inputOptions.text.justify;\n          } else {\n            throw is.invalidParameterError('text.justify', 'boolean', inputOptions.text.justify);\n          }\n        }\n        if (is.defined(inputOptions.text.dpi)) {\n          if (is.integer(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 1000000)) {\n            inputDescriptor.textDpi = inputOptions.text.dpi;\n          } else {\n            throw is.invalidParameterError('text.dpi', 'integer between 1 and 1000000', inputOptions.text.dpi);\n          }\n        }\n        if (is.defined(inputOptions.text.rgba)) {\n          if (is.bool(inputOptions.text.rgba)) {\n            inputDescriptor.textRgba = inputOptions.text.rgba;\n          } else {\n            throw is.invalidParameterError('text.rgba', 'bool', inputOptions.text.rgba);\n          }\n        }\n        if (is.defined(inputOptions.text.spacing)) {\n          if (is.integer(inputOptions.text.spacing) && is.inRange(inputOptions.text.spacing, -1000000, 1000000)) {\n            inputDescriptor.textSpacing = inputOptions.text.spacing;\n          } else {\n            throw is.invalidParameterError('text.spacing', 'integer between -1000000 and 1000000', inputOptions.text.spacing);\n          }\n        }\n        if (is.defined(inputOptions.text.wrap)) {\n          if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'word-char', 'none'])) {\n            inputDescriptor.textWrap = inputOptions.text.wrap;\n          } else {\n            throw is.invalidParameterError('text.wrap', 'one of: word, char, word-char, none', inputOptions.text.wrap);\n          }\n        }\n        delete inputDescriptor.buffer;\n      } else {\n        throw new Error('Expected a valid string to create an image with text.');\n      }\n    }\n    // Join images together\n    if (is.defined(inputOptions.join)) {\n      if (is.defined(this.options.join)) {\n        if (is.defined(inputOptions.join.animated)) {\n          if (is.bool(inputOptions.join.animated)) {\n            inputDescriptor.joinAnimated = inputOptions.join.animated;\n          } else {\n            throw is.invalidParameterError('join.animated', 'boolean', inputOptions.join.animated);\n          }\n        }\n        if (is.defined(inputOptions.join.across)) {\n          if (is.integer(inputOptions.join.across) && is.inRange(inputOptions.join.across, 1, 1000000)) {\n            inputDescriptor.joinAcross = inputOptions.join.across;\n          } else {\n            throw is.invalidParameterError('join.across', 'integer between 1 and 100000', inputOptions.join.across);\n          }\n        }\n        if (is.defined(inputOptions.join.shim)) {\n          if (is.integer(inputOptions.join.shim) && is.inRange(inputOptions.join.shim, 0, 1000000)) {\n            inputDescriptor.joinShim = inputOptions.join.shim;\n          } else {\n            throw is.invalidParameterError('join.shim', 'integer between 0 and 100000', inputOptions.join.shim);\n          }\n        }\n        if (is.defined(inputOptions.join.background)) {\n          inputDescriptor.joinBackground = this._getBackgroundColourOption(inputOptions.join.background);\n        }\n        if (is.defined(inputOptions.join.halign)) {\n          if (is.string(inputOptions.join.halign) && is.string(this.constructor.align[inputOptions.join.halign])) {\n            inputDescriptor.joinHalign = this.constructor.align[inputOptions.join.halign];\n          } else {\n            throw is.invalidParameterError('join.halign', 'valid alignment', inputOptions.join.halign);\n          }\n        }\n        if (is.defined(inputOptions.join.valign)) {\n          if (is.string(inputOptions.join.valign) && is.string(this.constructor.align[inputOptions.join.valign])) {\n            inputDescriptor.joinValign = this.constructor.align[inputOptions.join.valign];\n          } else {\n            throw is.invalidParameterError('join.valign', 'valid alignment', inputOptions.join.valign);\n          }\n        }\n      } else {\n        throw new Error('Expected input to be an array of images to join');\n      }\n    }\n  } else if (is.defined(inputOptions)) {\n    throw new Error(`Invalid input options ${inputOptions}`);\n  }\n  return inputDescriptor;\n}\n\n/**\n * Handle incoming Buffer chunk on Writable Stream.\n * @private\n * @param {Buffer} chunk\n * @param {string} encoding - unused\n * @param {Function} callback\n */\nfunction _write (chunk, _encoding, callback) {\n  if (Array.isArray(this.options.input.buffer)) {\n    if (is.buffer(chunk)) {\n      if (this.options.input.buffer.length === 0) {\n        this.on('finish', () => {\n          this.streamInFinished = true;\n        });\n      }\n      this.options.input.buffer.push(chunk);\n      callback();\n    } else {\n      callback(new Error('Non-Buffer data on Writable Stream'));\n    }\n  } else {\n    callback(new Error('Unexpected data on Writable Stream'));\n  }\n}\n\n/**\n * Flattens the array of chunks accumulated in input.buffer.\n * @private\n */\nfunction _flattenBufferIn () {\n  if (this._isStreamInput()) {\n    this.options.input.buffer = Buffer.concat(this.options.input.buffer);\n  }\n}\n\n/**\n * Are we expecting Stream-based input?\n * @private\n * @returns {boolean}\n */\nfunction _isStreamInput () {\n  return Array.isArray(this.options.input.buffer);\n}\n\n/**\n * Fast access to (uncached) image metadata without decoding any compressed pixel data.\n *\n * This is read from the header of the input image.\n * It does not take into consideration any operations to be applied to the output image,\n * such as resize or rotate.\n *\n * Dimensions in the response will respect the `page` and `pages` properties of the\n * {@link /api-constructor/ constructor parameters}.\n *\n * A `Promise` is returned when `callback` is not provided.\n *\n * - `format`: Name of decoder used to parse image e.g. `jpeg`, `png`, `webp`, `gif`, `svg`, `heif`, `tiff`\n * - `size`: Total size of image in bytes, for Stream and Buffer input only\n * - `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below)\n * - `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below)\n * - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/enum.Interpretation.html)\n * - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK\n * - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://www.libvips.org/API/current/enum.BandFormat.html)\n * - `density`: Number of pixels per inch (DPI), if present\n * - `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK\n * - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan\n * - `isPalette`: Boolean indicating whether the image is palette-based (GIF, PNG).\n * - `bitsPerSample`: Number of bits per sample for each channel (GIF, PNG, HEIF).\n * - `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP\n * - `pageHeight`: Number of pixels high each page in a multi-page image will be.\n * - `loop`: Number of times to loop an animated image, zero refers to a continuous loop.\n * - `delay`: Delay in ms between each page in an animated image, provided as an array of integers.\n * - `pagePrimary`: Number of the primary page in a HEIF image\n * - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide\n * - `subifds`: Number of Sub Image File Directories in an OME-TIFF image\n * - `background`: Default background colour, if present, for PNG (bKGD) and GIF images\n * - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)\n * - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present\n * - `hasProfile`: Boolean indicating the presence of an embedded ICC profile\n * - `hasAlpha`: Boolean indicating the presence of an alpha transparency channel\n * - `orientation`: Number value of the EXIF Orientation header, if present\n * - `exif`: Buffer containing raw EXIF data, if present\n * - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present\n * - `iptc`: Buffer containing raw IPTC data, if present\n * - `xmp`: Buffer containing raw XMP data, if present\n * - `xmpAsString`: String containing XMP data, if valid UTF-8.\n * - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present\n * - `formatMagick`: String containing format for images loaded via *magick\n * - `comments`: Array of keyword/text pairs representing PNG text blocks, if present.\n *\n * @example\n * const metadata = await sharp(input).metadata();\n *\n * @example\n * const image = sharp(inputJpg);\n * image\n *   .metadata()\n *   .then(function(metadata) {\n *     return image\n *       .resize(Math.round(metadata.width / 2))\n *       .webp()\n *       .toBuffer();\n *   })\n *   .then(function(data) {\n *     // data contains a WebP image half the width and height of the original JPEG\n *   });\n *\n * @example\n * // Get dimensions taking EXIF Orientation into account.\n * const { autoOrient } = await sharp(input).metadata();\n * const { width, height } = autoOrient;\n *\n * @param {Function} [callback] - called with the arguments `(err, metadata)`\n * @returns {Promise<Object>|Sharp}\n */\nfunction metadata (callback) {\n  const stack = Error();\n  if (is.fn(callback)) {\n    if (this._isStreamInput()) {\n      this.on('finish', () => {\n        this._flattenBufferIn();\n        sharp.metadata(this.options, (err, metadata) => {\n          if (err) {\n            callback(is.nativeError(err, stack));\n          } else {\n            callback(null, metadata);\n          }\n        });\n      });\n    } else {\n      sharp.metadata(this.options, (err, metadata) => {\n        if (err) {\n          callback(is.nativeError(err, stack));\n        } else {\n          callback(null, metadata);\n        }\n      });\n    }\n    return this;\n  } else {\n    if (this._isStreamInput()) {\n      return new Promise((resolve, reject) => {\n        const finished = () => {\n          this._flattenBufferIn();\n          sharp.metadata(this.options, (err, metadata) => {\n            if (err) {\n              reject(is.nativeError(err, stack));\n            } else {\n              resolve(metadata);\n            }\n          });\n        };\n        if (this.writableFinished) {\n          finished();\n        } else {\n          this.once('finish', finished);\n        }\n      });\n    } else {\n      return new Promise((resolve, reject) => {\n        sharp.metadata(this.options, (err, metadata) => {\n          if (err) {\n            reject(is.nativeError(err, stack));\n          } else {\n            resolve(metadata);\n          }\n        });\n      });\n    }\n  }\n}\n\n/**\n * Access to pixel-derived image statistics for every channel in the image.\n * A `Promise` is returned when `callback` is not provided.\n *\n * - `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains\n *     - `min` (minimum value in the channel)\n *     - `max` (maximum value in the channel)\n *     - `sum` (sum of all values in a channel)\n *     - `squaresSum` (sum of squared values in a channel)\n *     - `mean` (mean of the values in a channel)\n *     - `stdev` (standard deviation for the values in a channel)\n *     - `minX` (x-coordinate of one of the pixel where the minimum lies)\n *     - `minY` (y-coordinate of one of the pixel where the minimum lies)\n *     - `maxX` (x-coordinate of one of the pixel where the maximum lies)\n *     - `maxY` (y-coordinate of one of the pixel where the maximum lies)\n * - `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.\n * - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.\n * - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any.\n * - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram.\n *\n * **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be\n * written to a buffer in order to run `stats` on the result (see third example).\n *\n * @example\n * const image = sharp(inputJpg);\n * image\n *   .stats()\n *   .then(function(stats) {\n *      // stats contains the channel-wise statistics array and the isOpaque value\n *   });\n *\n * @example\n * const { entropy, sharpness, dominant } = await sharp(input).stats();\n * const { r, g, b } = dominant;\n *\n * @example\n * const image = sharp(input);\n * // store intermediate result\n * const part = await image.extract(region).toBuffer();\n * // create new instance to obtain statistics of extracted region\n * const stats = await sharp(part).stats();\n *\n * @param {Function} [callback] - called with the arguments `(err, stats)`\n * @returns {Promise<Object>}\n */\nfunction stats (callback) {\n  const stack = Error();\n  if (is.fn(callback)) {\n    if (this._isStreamInput()) {\n      this.on('finish', () => {\n        this._flattenBufferIn();\n        sharp.stats(this.options, (err, stats) => {\n          if (err) {\n            callback(is.nativeError(err, stack));\n          } else {\n            callback(null, stats);\n          }\n        });\n      });\n    } else {\n      sharp.stats(this.options, (err, stats) => {\n        if (err) {\n          callback(is.nativeError(err, stack));\n        } else {\n          callback(null, stats);\n        }\n      });\n    }\n    return this;\n  } else {\n    if (this._isStreamInput()) {\n      return new Promise((resolve, reject) => {\n        this.on('finish', function () {\n          this._flattenBufferIn();\n          sharp.stats(this.options, (err, stats) => {\n            if (err) {\n              reject(is.nativeError(err, stack));\n            } else {\n              resolve(stats);\n            }\n          });\n        });\n      });\n    } else {\n      return new Promise((resolve, reject) => {\n        sharp.stats(this.options, (err, stats) => {\n          if (err) {\n            reject(is.nativeError(err, stack));\n          } else {\n            resolve(stats);\n          }\n        });\n      });\n    }\n  }\n}\n\n/**\n * Decorate the Sharp prototype with input-related functions.\n * @module Sharp\n * @private\n */\nmodule.exports = (Sharp) => {\n  Object.assign(Sharp.prototype, {\n    // Private\n    _inputOptionsFromObject,\n    _createInputDescriptor,\n    _write,\n    _flattenBufferIn,\n    _isStreamInput,\n    // Public\n    metadata,\n    stats\n  });\n  // Class attributes\n  Sharp.align = align;\n};\n"
  },
  {
    "path": "lib/is.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n/**\n * Is this value defined and not null?\n * @private\n */\nconst defined = (val) => typeof val !== 'undefined' && val !== null;\n\n/**\n * Is this value an object?\n * @private\n */\nconst object = (val) => typeof val === 'object';\n\n/**\n * Is this value a plain object?\n * @private\n */\nconst plainObject = (val) => Object.prototype.toString.call(val) === '[object Object]';\n\n/**\n * Is this value a function?\n * @private\n */\nconst fn = (val) => typeof val === 'function';\n\n/**\n * Is this value a boolean?\n * @private\n */\nconst bool = (val) => typeof val === 'boolean';\n\n/**\n * Is this value a Buffer object?\n * @private\n */\nconst buffer = (val) => val instanceof Buffer;\n\n/**\n * Is this value a typed array object?. E.g. Uint8Array or Uint8ClampedArray?\n * @private\n */\nconst typedArray = (val) => {\n  if (defined(val)) {\n    switch (val.constructor) {\n      case Uint8Array:\n      case Uint8ClampedArray:\n      case Int8Array:\n      case Uint16Array:\n      case Int16Array:\n      case Uint32Array:\n      case Int32Array:\n      case Float32Array:\n      case Float64Array:\n        return true;\n    }\n  }\n\n  return false;\n};\n\n/**\n * Is this value an ArrayBuffer object?\n * @private\n */\nconst arrayBuffer = (val) => val instanceof ArrayBuffer;\n\n/**\n * Is this value a non-empty string?\n * @private\n */\nconst string = (val) => typeof val === 'string' && val.length > 0;\n\n/**\n * Is this value a real number?\n * @private\n */\nconst number = (val) => typeof val === 'number' && !Number.isNaN(val);\n\n/**\n * Is this value an integer?\n * @private\n */\nconst integer = (val) => Number.isInteger(val);\n\n/**\n * Is this value within an inclusive given range?\n * @private\n */\nconst inRange = (val, min, max) => val >= min && val <= max;\n\n/**\n * Is this value within the elements of an array?\n * @private\n */\nconst inArray = (val, list) => list.includes(val);\n\n/**\n * Create an Error with a message relating to an invalid parameter.\n *\n * @param {string} name - parameter name.\n * @param {string} expected - description of the type/value/range expected.\n * @param {*} actual - the value received.\n * @returns {Error} Containing the formatted message.\n * @private\n */\nconst invalidParameterError = (name, expected, actual) => new Error(\n    `Expected ${expected} for ${name} but received ${actual} of type ${typeof actual}`\n  );\n\n/**\n * Ensures an Error from C++ contains a JS stack.\n *\n * @param {Error} native - Error with message from C++.\n * @param {Error} context - Error with stack from JS.\n * @returns {Error} Error with message and stack.\n * @private\n */\nconst nativeError = (native, context) => {\n  context.message = native.message;\n  return context;\n};\n\nmodule.exports = {\n  defined,\n  object,\n  plainObject,\n  fn,\n  bool,\n  buffer,\n  typedArray,\n  arrayBuffer,\n  string,\n  number,\n  integer,\n  inRange,\n  inArray,\n  invalidParameterError,\n  nativeError\n};\n"
  },
  {
    "path": "lib/libvips.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { spawnSync } = require('node:child_process');\nconst { createHash } = require('node:crypto');\nconst semverCoerce = require('semver/functions/coerce');\nconst semverGreaterThanOrEqualTo = require('semver/functions/gte');\nconst semverSatisfies = require('semver/functions/satisfies');\nconst detectLibc = require('detect-libc');\n\nconst { config, engines, optionalDependencies } = require('../package.json');\n\n/* node:coverage ignore next */\nconst minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || config.libvips;\nconst minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version;\n\nconst prebuiltPlatforms = [\n  'darwin-arm64', 'darwin-x64',\n  'linux-arm', 'linux-arm64', 'linux-ppc64', 'linux-riscv64', 'linux-s390x', 'linux-x64',\n  'linuxmusl-arm64', 'linuxmusl-x64',\n  'win32-arm64', 'win32-ia32', 'win32-x64'\n];\n\nconst spawnSyncOptions = {\n  encoding: 'utf8',\n  shell: true\n};\n\nconst log = (item) => {\n  if (item instanceof Error) {\n    console.error(`sharp: Installation error: ${item.message}`);\n  } else {\n    console.log(`sharp: ${item}`);\n  }\n};\n\n/* node:coverage ignore next */\nconst runtimeLibc = () => detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : '';\n\nconst runtimePlatformArch = () => `${process.platform}${runtimeLibc()}-${process.arch}`;\n\nconst buildPlatformArch = () => {\n  /* node:coverage ignore next 3 */\n  if (isEmscripten()) {\n    return 'wasm32';\n  }\n  const { npm_config_arch, npm_config_platform, npm_config_libc } = process.env;\n  const libc = typeof npm_config_libc === 'string' ? npm_config_libc : runtimeLibc();\n  return `${npm_config_platform || process.platform}${libc}-${npm_config_arch || process.arch}`;\n};\n\nconst buildSharpLibvipsIncludeDir = () => {\n  try {\n    return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/include`);\n  } catch {\n    /* node:coverage ignore next 5 */\n    try {\n      return require('@img/sharp-libvips-dev/include');\n    } catch {}\n  }\n  return '';\n};\n\nconst buildSharpLibvipsCPlusPlusDir = () => {\n  /* node:coverage ignore next 4 */\n  try {\n    return require('@img/sharp-libvips-dev/cplusplus');\n  } catch {}\n  return '';\n};\n\nconst buildSharpLibvipsLibDir = () => {\n  try {\n    return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/lib`);\n  } catch {\n    /* node:coverage ignore next 5 */\n    try {\n      return require(`@img/sharp-libvips-${buildPlatformArch()}/lib`);\n    } catch {}\n  }\n  return '';\n};\n\n/* node:coverage disable */\n\nconst isUnsupportedNodeRuntime = () => {\n  if (process.release?.name === 'node' && process.versions) {\n    if (!semverSatisfies(process.versions.node, engines.node)) {\n      return { found: process.versions.node, expected: engines.node };\n    }\n  }\n};\n\nconst isEmscripten = () => {\n  const { CC } = process.env;\n  return Boolean(CC?.endsWith('/emcc'));\n};\n\nconst isRosetta = () => {\n  if (process.platform === 'darwin' && process.arch === 'x64') {\n    const translated = spawnSync('sysctl sysctl.proc_translated', spawnSyncOptions).stdout;\n    return (translated || '').trim() === 'sysctl.proc_translated: 1';\n  }\n  return false;\n};\n\n/* node:coverage enable */\n\nconst sha512 = (s) => createHash('sha512').update(s).digest('hex');\n\nconst yarnLocator = () => {\n  try {\n    const identHash = sha512(`imgsharp-libvips-${buildPlatformArch()}`);\n    const npmVersion = semverCoerce(optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`], {\n      includePrerelease: true\n    }).version;\n    return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10);\n  } catch {}\n  return '';\n};\n\n/* node:coverage disable */\n\nconst spawnRebuild = () =>\n  spawnSync(`node-gyp rebuild --directory=src ${isEmscripten() ? '--nodedir=emscripten' : ''}`, {\n    ...spawnSyncOptions,\n    stdio: 'inherit'\n  }).status;\n\nconst globalLibvipsVersion = () => {\n  if (process.platform !== 'win32') {\n    const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', {\n      ...spawnSyncOptions,\n      env: {\n        ...process.env,\n        PKG_CONFIG_PATH: pkgConfigPath()\n      }\n    }).stdout;\n    return (globalLibvipsVersion || '').trim();\n  } else {\n    return '';\n  }\n};\n\n/* node:coverage enable */\n\nconst pkgConfigPath = () => {\n  if (process.platform !== 'win32') {\n    /* node:coverage ignore next 4 */\n    const brewPkgConfigPath = spawnSync(\n      'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d\" \" -f2',\n      spawnSyncOptions\n    ).stdout || '';\n    return [\n      brewPkgConfigPath.trim(),\n      process.env.PKG_CONFIG_PATH,\n      '/usr/local/lib/pkgconfig',\n      '/usr/lib/pkgconfig',\n      '/usr/local/libdata/pkgconfig',\n      '/usr/libdata/pkgconfig'\n    ].filter(Boolean).join(':');\n  } else {\n    return '';\n  }\n};\n\nconst skipSearch = (status, reason, logger) => {\n  if (logger) {\n    logger(`Detected ${reason}, skipping search for globally-installed libvips`);\n  }\n  return status;\n};\n\nconst useGlobalLibvips = (logger) => {\n  if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) {\n    return skipSearch(false, 'SHARP_IGNORE_GLOBAL_LIBVIPS', logger);\n  }\n  if (Boolean(process.env.SHARP_FORCE_GLOBAL_LIBVIPS) === true) {\n    return skipSearch(true, 'SHARP_FORCE_GLOBAL_LIBVIPS', logger);\n  }\n  /* node:coverage ignore next 3 */\n  if (isRosetta()) {\n    return skipSearch(false, 'Rosetta', logger);\n  }\n  const globalVipsVersion = globalLibvipsVersion();\n  /* node:coverage ignore next */\n  return !!globalVipsVersion && semverGreaterThanOrEqualTo(globalVipsVersion, minimumLibvipsVersion);\n};\n\nmodule.exports = {\n  minimumLibvipsVersion,\n  prebuiltPlatforms,\n  buildPlatformArch,\n  buildSharpLibvipsIncludeDir,\n  buildSharpLibvipsCPlusPlusDir,\n  buildSharpLibvipsLibDir,\n  isUnsupportedNodeRuntime,\n  runtimePlatformArch,\n  log,\n  yarnLocator,\n  spawnRebuild,\n  globalLibvipsVersion,\n  pkgConfigPath,\n  useGlobalLibvips\n};\n"
  },
  {
    "path": "lib/operation.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst is = require('./is');\n\n/**\n * How accurate an operation should be.\n * @member\n * @private\n */\nconst vipsPrecision = {\n  integer: 'integer',\n  float: 'float',\n  approximate: 'approximate'\n};\n\n/**\n * Rotate the output image.\n *\n * The provided angle is converted to a valid positive degree rotation.\n * For example, `-450` will produce a 270 degree rotation.\n *\n * When rotating by an angle other than a multiple of 90,\n * the background colour can be provided with the `background` option.\n *\n * For backwards compatibility, if no angle is provided, `.autoOrient()` will be called.\n *\n * Only one rotation can occur per pipeline (aside from an initial call without\n * arguments to orient via EXIF data). Previous calls to `rotate` in the same\n * pipeline will be ignored.\n *\n * Multi-page images can only be rotated by 180 degrees.\n *\n * Method order is important when rotating, resizing and/or extracting regions,\n * for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.\n *\n * @example\n * const rotateThenResize = await sharp(input)\n *   .rotate(90)\n *   .resize({ width: 16, height: 8, fit: 'fill' })\n *   .toBuffer();\n * const resizeThenRotate = await sharp(input)\n *   .resize({ width: 16, height: 8, fit: 'fill' })\n *   .rotate(90)\n *   .toBuffer();\n *\n * @param {number} [angle=auto] angle of rotation.\n * @param {Object} [options] - if present, is an Object with optional attributes.\n * @param {string|Object} [options.background=\"#000000\"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction rotate (angle, options) {\n  if (!is.defined(angle)) {\n    return this.autoOrient();\n  }\n  if (this.options.angle || this.options.rotationAngle) {\n    this.options.debuglog('ignoring previous rotate options');\n    this.options.angle = 0;\n    this.options.rotationAngle = 0;\n  }\n  if (is.integer(angle) && !(angle % 90)) {\n    this.options.angle = angle;\n  } else if (is.number(angle)) {\n    this.options.rotationAngle = angle;\n    if (is.object(options) && options.background) {\n      this._setBackgroundColourOption('rotationBackground', options.background);\n    }\n  } else {\n    throw is.invalidParameterError('angle', 'numeric', angle);\n  }\n  return this;\n}\n\n/**\n * Auto-orient based on the EXIF `Orientation` tag, then remove the tag.\n * Mirroring is supported and may infer the use of a flip operation.\n *\n * Previous or subsequent use of `rotate(angle)` and either `flip()` or `flop()`\n * will logically occur after auto-orientation, regardless of call order.\n *\n * @example\n * const output = await sharp(input).autoOrient().toBuffer();\n *\n * @example\n * const pipeline = sharp()\n *   .autoOrient()\n *   .resize(null, 200)\n *   .toBuffer(function (err, outputBuffer, info) {\n *     // outputBuffer contains 200px high JPEG image data,\n *     // auto-oriented using EXIF Orientation tag\n *     // info.width and info.height contain the dimensions of the resized image\n *   });\n * readableStream.pipe(pipeline);\n *\n * @returns {Sharp}\n */\nfunction autoOrient () {\n  this.options.input.autoOrient = true;\n  return this;\n}\n\n/**\n * Mirror the image vertically (up-down) about the x-axis.\n * This always occurs before rotation, if any.\n *\n * This operation does not work correctly with multi-page images.\n *\n * @example\n * const output = await sharp(input).flip().toBuffer();\n *\n * @param {Boolean} [flip=true]\n * @returns {Sharp}\n */\nfunction flip (flip) {\n  this.options.flip = is.bool(flip) ? flip : true;\n  return this;\n}\n\n/**\n * Mirror the image horizontally (left-right) about the y-axis.\n * This always occurs before rotation, if any.\n *\n * @example\n * const output = await sharp(input).flop().toBuffer();\n *\n * @param {Boolean} [flop=true]\n * @returns {Sharp}\n */\nfunction flop (flop) {\n  this.options.flop = is.bool(flop) ? flop : true;\n  return this;\n}\n\n/**\n * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.\n *\n * You must provide an array of length 4 or a 2x2 affine transformation matrix.\n * By default, new pixels are filled with a black background. You can provide a background colour with the `background` option.\n * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.\n *\n * In the case of a 2x2 matrix, the transform is:\n * - X = `matrix[0, 0]` \\* (x + `idx`) + `matrix[0, 1]` \\* (y + `idy`) + `odx`\n * - Y = `matrix[1, 0]` \\* (x + `idx`) + `matrix[1, 1]` \\* (y + `idy`) + `ody`\n *\n * where:\n * - x and y are the coordinates in input image.\n * - X and Y are the coordinates in output image.\n * - (0,0) is the upper left corner.\n *\n * @since 0.27.0\n *\n * @example\n * const pipeline = sharp()\n *   .affine([[1, 0.3], [0.1, 0.7]], {\n *      background: 'white',\n *      interpolator: sharp.interpolators.nohalo\n *   })\n *   .toBuffer((err, outputBuffer, info) => {\n *      // outputBuffer contains the transformed image\n *      // info.width and info.height contain the new dimensions\n *   });\n *\n * inputStream\n *   .pipe(pipeline);\n *\n * @param {Array<Array<number>>|Array<number>} matrix - affine transformation matrix\n * @param {Object} [options] - if present, is an Object with optional attributes.\n * @param {String|Object} [options.background=\"#000000\"] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @param {Number} [options.idx=0] - input horizontal offset\n * @param {Number} [options.idy=0] - input vertical offset\n * @param {Number} [options.odx=0] - output horizontal offset\n * @param {Number} [options.ody=0] - output vertical offset\n * @param {String} [options.interpolator=sharp.interpolators.bicubic] - interpolator\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction affine (matrix, options) {\n  const flatMatrix = [].concat(...matrix);\n  if (flatMatrix.length === 4 && flatMatrix.every(is.number)) {\n    this.options.affineMatrix = flatMatrix;\n  } else {\n    throw is.invalidParameterError('matrix', '1x4 or 2x2 array', matrix);\n  }\n\n  if (is.defined(options)) {\n    if (is.object(options)) {\n      this._setBackgroundColourOption('affineBackground', options.background);\n      if (is.defined(options.idx)) {\n        if (is.number(options.idx)) {\n          this.options.affineIdx = options.idx;\n        } else {\n          throw is.invalidParameterError('options.idx', 'number', options.idx);\n        }\n      }\n      if (is.defined(options.idy)) {\n        if (is.number(options.idy)) {\n          this.options.affineIdy = options.idy;\n        } else {\n          throw is.invalidParameterError('options.idy', 'number', options.idy);\n        }\n      }\n      if (is.defined(options.odx)) {\n        if (is.number(options.odx)) {\n          this.options.affineOdx = options.odx;\n        } else {\n          throw is.invalidParameterError('options.odx', 'number', options.odx);\n        }\n      }\n      if (is.defined(options.ody)) {\n        if (is.number(options.ody)) {\n          this.options.affineOdy = options.ody;\n        } else {\n          throw is.invalidParameterError('options.ody', 'number', options.ody);\n        }\n      }\n      if (is.defined(options.interpolator)) {\n        if (is.inArray(options.interpolator, Object.values(this.constructor.interpolators))) {\n          this.options.affineInterpolator = options.interpolator;\n        } else {\n          throw is.invalidParameterError('options.interpolator', 'valid interpolator name', options.interpolator);\n        }\n      }\n    } else {\n      throw is.invalidParameterError('options', 'object', options);\n    }\n  }\n\n  return this;\n}\n\n/**\n * Sharpen the image.\n *\n * When used without parameters, performs a fast, mild sharpen of the output image.\n *\n * When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.\n * Fine-grained control over the level of sharpening in \"flat\" (m1) and \"jagged\" (m2) areas is available.\n *\n * See {@link https://www.libvips.org/API/current/method.Image.sharpen.html libvips sharpen} operation.\n *\n * @example\n * const data = await sharp(input).sharpen().toBuffer();\n *\n * @example\n * const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer();\n *\n * @example\n * const data = await sharp(input)\n *   .sharpen({\n *     sigma: 2,\n *     m1: 0,\n *     m2: 3,\n *     x1: 3,\n *     y2: 15,\n *     y3: 15,\n *   })\n *   .toBuffer();\n *\n * @param {Object|number} [options] - if present, is an Object with attributes\n * @param {number} [options.sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10\n * @param {number} [options.m1=1.0] - the level of sharpening to apply to \"flat\" areas, between 0 and 1000000\n * @param {number} [options.m2=2.0] - the level of sharpening to apply to \"jagged\" areas, between 0 and 1000000\n * @param {number} [options.x1=2.0] - threshold between \"flat\" and \"jagged\", between 0 and 1000000\n * @param {number} [options.y2=10.0] - maximum amount of brightening, between 0 and 1000000\n * @param {number} [options.y3=20.0] - maximum amount of darkening, between 0 and 1000000\n * @param {number} [flat] - (deprecated) see `options.m1`.\n * @param {number} [jagged] - (deprecated) see `options.m2`.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction sharpen (options, flat, jagged) {\n  if (!is.defined(options)) {\n    // No arguments: default to mild sharpen\n    this.options.sharpenSigma = -1;\n  } else if (is.bool(options)) {\n    // Deprecated boolean argument: apply mild sharpen?\n    this.options.sharpenSigma = options ? -1 : 0;\n  } else if (is.number(options) && is.inRange(options, 0.01, 10000)) {\n    // Deprecated numeric argument: specific sigma\n    this.options.sharpenSigma = options;\n    // Deprecated control over flat areas\n    if (is.defined(flat)) {\n      if (is.number(flat) && is.inRange(flat, 0, 10000)) {\n        this.options.sharpenM1 = flat;\n      } else {\n        throw is.invalidParameterError('flat', 'number between 0 and 10000', flat);\n      }\n    }\n    // Deprecated control over jagged areas\n    if (is.defined(jagged)) {\n      if (is.number(jagged) && is.inRange(jagged, 0, 10000)) {\n        this.options.sharpenM2 = jagged;\n      } else {\n        throw is.invalidParameterError('jagged', 'number between 0 and 10000', jagged);\n      }\n    }\n  } else if (is.plainObject(options)) {\n    if (is.number(options.sigma) && is.inRange(options.sigma, 0.000001, 10)) {\n      this.options.sharpenSigma = options.sigma;\n    } else {\n      throw is.invalidParameterError('options.sigma', 'number between 0.000001 and 10', options.sigma);\n    }\n    if (is.defined(options.m1)) {\n      if (is.number(options.m1) && is.inRange(options.m1, 0, 1000000)) {\n        this.options.sharpenM1 = options.m1;\n      } else {\n        throw is.invalidParameterError('options.m1', 'number between 0 and 1000000', options.m1);\n      }\n    }\n    if (is.defined(options.m2)) {\n      if (is.number(options.m2) && is.inRange(options.m2, 0, 1000000)) {\n        this.options.sharpenM2 = options.m2;\n      } else {\n        throw is.invalidParameterError('options.m2', 'number between 0 and 1000000', options.m2);\n      }\n    }\n    if (is.defined(options.x1)) {\n      if (is.number(options.x1) && is.inRange(options.x1, 0, 1000000)) {\n        this.options.sharpenX1 = options.x1;\n      } else {\n        throw is.invalidParameterError('options.x1', 'number between 0 and 1000000', options.x1);\n      }\n    }\n    if (is.defined(options.y2)) {\n      if (is.number(options.y2) && is.inRange(options.y2, 0, 1000000)) {\n        this.options.sharpenY2 = options.y2;\n      } else {\n        throw is.invalidParameterError('options.y2', 'number between 0 and 1000000', options.y2);\n      }\n    }\n    if (is.defined(options.y3)) {\n      if (is.number(options.y3) && is.inRange(options.y3, 0, 1000000)) {\n        this.options.sharpenY3 = options.y3;\n      } else {\n        throw is.invalidParameterError('options.y3', 'number between 0 and 1000000', options.y3);\n      }\n    }\n  } else {\n    throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', options);\n  }\n  return this;\n}\n\n/**\n * Apply median filter.\n * When used without parameters the default window is 3x3.\n *\n * @example\n * const output = await sharp(input).median().toBuffer();\n *\n * @example\n * const output = await sharp(input).median(5).toBuffer();\n *\n * @param {number} [size=3] square mask size: size x size\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction median (size) {\n  if (!is.defined(size)) {\n    // No arguments: default to 3x3\n    this.options.medianSize = 3;\n  } else if (is.integer(size) && is.inRange(size, 1, 1000)) {\n    // Numeric argument: specific sigma\n    this.options.medianSize = size;\n  } else {\n    throw is.invalidParameterError('size', 'integer between 1 and 1000', size);\n  }\n  return this;\n}\n\n/**\n * Blur the image.\n *\n * When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter).\n *\n * When a `sigma` is provided, performs a slower, more accurate Gaussian blur.\n *\n * @example\n * const boxBlurred = await sharp(input)\n *   .blur()\n *   .toBuffer();\n *\n * @example\n * const gaussianBlurred = await sharp(input)\n *   .blur(5)\n *   .toBuffer();\n *\n * @param {Object|number|Boolean} [options]\n * @param {number} [options.sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.\n * @param {string} [options.precision='integer'] How accurate the operation should be, one of: integer, float, approximate.\n * @param {number} [options.minAmplitude=0.2] A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction blur (options) {\n  let sigma;\n  if (is.number(options)) {\n    sigma = options;\n  } else if (is.plainObject(options)) {\n    if (!is.number(options.sigma)) {\n      throw is.invalidParameterError('options.sigma', 'number between 0.3 and 1000', sigma);\n    }\n    sigma = options.sigma;\n    if ('precision' in options) {\n      if (is.string(vipsPrecision[options.precision])) {\n        this.options.precision = vipsPrecision[options.precision];\n      } else {\n        throw is.invalidParameterError('precision', 'one of: integer, float, approximate', options.precision);\n      }\n    }\n    if ('minAmplitude' in options) {\n      if (is.number(options.minAmplitude) && is.inRange(options.minAmplitude, 0.001, 1)) {\n        this.options.minAmpl = options.minAmplitude;\n      } else {\n        throw is.invalidParameterError('minAmplitude', 'number between 0.001 and 1', options.minAmplitude);\n      }\n    }\n  }\n\n  if (!is.defined(options)) {\n    // No arguments: default to mild blur\n    this.options.blurSigma = -1;\n  } else if (is.bool(options)) {\n    // Boolean argument: apply mild blur?\n    this.options.blurSigma = options ? -1 : 0;\n  } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) {\n    // Numeric argument: specific sigma\n    this.options.blurSigma = sigma;\n  } else {\n    throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma);\n  }\n\n  return this;\n}\n\n/**\n * Expand foreground objects using the dilate morphological operator.\n *\n * @example\n * const output = await sharp(input)\n *   .dilate()\n *   .toBuffer();\n *\n * @param {Number} [width=1] dilation width in pixels.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction dilate (width) {\n  if (!is.defined(width)) {\n    this.options.dilateWidth = 1;\n  } else if (is.integer(width) && width > 0) {\n    this.options.dilateWidth = width;\n  } else {\n    throw is.invalidParameterError('dilate', 'positive integer', dilate);\n  }\n  return this;\n}\n\n/**\n * Shrink foreground objects using the erode morphological operator.\n *\n * @example\n * const output = await sharp(input)\n *   .erode()\n *   .toBuffer();\n *\n * @param {Number} [width=1] erosion width in pixels.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction erode (width) {\n  if (!is.defined(width)) {\n    this.options.erodeWidth = 1;\n  } else if (is.integer(width) && width > 0) {\n    this.options.erodeWidth = width;\n  } else {\n    throw is.invalidParameterError('erode', 'positive integer', erode);\n  }\n  return this;\n}\n\n/**\n * Merge alpha transparency channel, if any, with a background, then remove the alpha channel.\n *\n * See also {@link /api-channel#removealpha removeAlpha}.\n *\n * @example\n * await sharp(rgbaInput)\n *   .flatten({ background: '#F0A703' })\n *   .toBuffer();\n *\n * @param {Object} [options]\n * @param {string|Object} [options.background={r: 0, g: 0, b: 0}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black.\n * @returns {Sharp}\n */\nfunction flatten (options) {\n  this.options.flatten = is.bool(options) ? options : true;\n  if (is.object(options)) {\n    this._setBackgroundColourOption('flattenBackground', options.background);\n  }\n  return this;\n}\n\n/**\n * Ensure the image has an alpha channel\n * with all white pixel values made fully transparent.\n *\n * Existing alpha channel values for non-white pixels remain unchanged.\n *\n * This feature is experimental and the API may change.\n *\n * @since 0.32.1\n *\n * @example\n * await sharp(rgbInput)\n *   .unflatten()\n *   .toBuffer();\n *\n * @example\n * await sharp(rgbInput)\n *   .threshold(128, { grayscale: false }) // converter bright pixels to white\n *   .unflatten()\n *   .toBuffer();\n */\nfunction unflatten () {\n  this.options.unflatten = true;\n  return this;\n}\n\n/**\n * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma`\n * then increasing the encoding (brighten) post-resize at a factor of `gamma`.\n * This can improve the perceived brightness of a resized image in non-linear colour spaces.\n * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation\n * when applying a gamma correction.\n *\n * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases.\n *\n * @param {number} [gamma=2.2] value between 1.0 and 3.0.\n * @param {number} [gammaOut] value between 1.0 and 3.0. (optional, defaults to same as `gamma`)\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction gamma (gamma, gammaOut) {\n  if (!is.defined(gamma)) {\n    // Default gamma correction of 2.2 (sRGB)\n    this.options.gamma = 2.2;\n  } else if (is.number(gamma) && is.inRange(gamma, 1, 3)) {\n    this.options.gamma = gamma;\n  } else {\n    throw is.invalidParameterError('gamma', 'number between 1.0 and 3.0', gamma);\n  }\n  if (!is.defined(gammaOut)) {\n    // Default gamma correction for output is same as input\n    this.options.gammaOut = this.options.gamma;\n  } else if (is.number(gammaOut) && is.inRange(gammaOut, 1, 3)) {\n    this.options.gammaOut = gammaOut;\n  } else {\n    throw is.invalidParameterError('gammaOut', 'number between 1.0 and 3.0', gammaOut);\n  }\n  return this;\n}\n\n/**\n * Produce the \"negative\" of the image.\n *\n * @example\n * const output = await sharp(input)\n *   .negate()\n *   .toBuffer();\n *\n * @example\n * const output = await sharp(input)\n *   .negate({ alpha: false })\n *   .toBuffer();\n *\n * @param {Object} [options]\n * @param {Boolean} [options.alpha=true] Whether or not to negate any alpha channel\n * @returns {Sharp}\n */\nfunction negate (options) {\n  this.options.negate = is.bool(options) ? options : true;\n  if (is.plainObject(options) && 'alpha' in options) {\n    if (!is.bool(options.alpha)) {\n      throw is.invalidParameterError('alpha', 'should be boolean value', options.alpha);\n    } else {\n      this.options.negateAlpha = options.alpha;\n    }\n  }\n  return this;\n}\n\n/**\n * Enhance output image contrast by stretching its luminance to cover a full dynamic range.\n *\n * Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes.\n *\n * Luminance values below the `lower` percentile will be underexposed by clipping to zero.\n * Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value.\n *\n * @example\n * const output = await sharp(input)\n *   .normalise()\n *   .toBuffer();\n *\n * @example\n * const output = await sharp(input)\n *   .normalise({ lower: 0, upper: 100 })\n *   .toBuffer();\n *\n * @param {Object} [options]\n * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed.\n * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed.\n * @returns {Sharp}\n */\nfunction normalise (options) {\n  if (is.plainObject(options)) {\n    if (is.defined(options.lower)) {\n      if (is.number(options.lower) && is.inRange(options.lower, 0, 99)) {\n        this.options.normaliseLower = options.lower;\n      } else {\n        throw is.invalidParameterError('lower', 'number between 0 and 99', options.lower);\n      }\n    }\n    if (is.defined(options.upper)) {\n      if (is.number(options.upper) && is.inRange(options.upper, 1, 100)) {\n        this.options.normaliseUpper = options.upper;\n      } else {\n        throw is.invalidParameterError('upper', 'number between 1 and 100', options.upper);\n      }\n    }\n  }\n  if (this.options.normaliseLower >= this.options.normaliseUpper) {\n    throw is.invalidParameterError('range', 'lower to be less than upper',\n      `${this.options.normaliseLower} >= ${this.options.normaliseUpper}`);\n  }\n  this.options.normalise = true;\n  return this;\n}\n\n/**\n * Alternative spelling of normalise.\n *\n * @example\n * const output = await sharp(input)\n *   .normalize()\n *   .toBuffer();\n *\n * @param {Object} [options]\n * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed.\n * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed.\n * @returns {Sharp}\n */\nfunction normalize (options) {\n  return this.normalise(options);\n}\n\n/**\n * Perform contrast limiting adaptive histogram equalization\n * {@link https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE CLAHE}.\n *\n * This will, in general, enhance the clarity of the image by bringing out darker details.\n *\n * @since 0.28.3\n *\n * @example\n * const output = await sharp(input)\n *   .clahe({\n *     width: 3,\n *     height: 3,\n *   })\n *   .toBuffer();\n *\n * @param {Object} options\n * @param {number} options.width - Integral width of the search window, in pixels.\n * @param {number} options.height - Integral height of the search window, in pixels.\n * @param {number} [options.maxSlope=3] - Integral level of brightening, between 0 and 100, where 0 disables contrast limiting.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction clahe (options) {\n  if (is.plainObject(options)) {\n    if (is.integer(options.width) && options.width > 0) {\n      this.options.claheWidth = options.width;\n    } else {\n      throw is.invalidParameterError('width', 'integer greater than zero', options.width);\n    }\n    if (is.integer(options.height) && options.height > 0) {\n      this.options.claheHeight = options.height;\n    } else {\n      throw is.invalidParameterError('height', 'integer greater than zero', options.height);\n    }\n    if (is.defined(options.maxSlope)) {\n      if (is.integer(options.maxSlope) && is.inRange(options.maxSlope, 0, 100)) {\n        this.options.claheMaxSlope = options.maxSlope;\n      } else {\n        throw is.invalidParameterError('maxSlope', 'integer between 0 and 100', options.maxSlope);\n      }\n    }\n  } else {\n    throw is.invalidParameterError('options', 'plain object', options);\n  }\n  return this;\n}\n\n/**\n * Convolve the image with the specified kernel.\n *\n * @example\n * sharp(input)\n *   .convolve({\n *     width: 3,\n *     height: 3,\n *     kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1]\n *   })\n *   .raw()\n *   .toBuffer(function(err, data, info) {\n *     // data contains the raw pixel data representing the convolution\n *     // of the input image with the horizontal Sobel operator\n *   });\n *\n * @param {Object} kernel\n * @param {number} kernel.width - width of the kernel in pixels.\n * @param {number} kernel.height - height of the kernel in pixels.\n * @param {Array<number>} kernel.kernel - Array of length `width*height` containing the kernel values.\n * @param {number} [kernel.scale=sum] - the scale of the kernel in pixels.\n * @param {number} [kernel.offset=0] - the offset of the kernel in pixels.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction convolve (kernel) {\n  if (!is.object(kernel) || !Array.isArray(kernel.kernel) ||\n      !is.integer(kernel.width) || !is.integer(kernel.height) ||\n      !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) ||\n      kernel.height * kernel.width !== kernel.kernel.length\n  ) {\n    // must pass in a kernel\n    throw new Error('Invalid convolution kernel');\n  }\n  // Default scale is sum of kernel values\n  if (!is.integer(kernel.scale)) {\n    kernel.scale = kernel.kernel.reduce((a, b) => a + b, 0);\n  }\n  // Clip scale to a minimum value of 1\n  if (kernel.scale < 1) {\n    kernel.scale = 1;\n  }\n  if (!is.integer(kernel.offset)) {\n    kernel.offset = 0;\n  }\n  this.options.convKernel = kernel;\n  return this;\n}\n\n/**\n * Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.\n * @param {number} [threshold=128] - a value in the range 0-255 representing the level at which the threshold will be applied.\n * @param {Object} [options]\n * @param {Boolean} [options.greyscale=true] - convert to single channel greyscale.\n * @param {Boolean} [options.grayscale=true] - alternative spelling for greyscale.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction threshold (threshold, options) {\n  if (!is.defined(threshold)) {\n    this.options.threshold = 128;\n  } else if (is.bool(threshold)) {\n    this.options.threshold = threshold ? 128 : 0;\n  } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) {\n    this.options.threshold = threshold;\n  } else {\n    throw is.invalidParameterError('threshold', 'integer between 0 and 255', threshold);\n  }\n  if (!is.object(options) || options.greyscale === true || options.grayscale === true) {\n    this.options.thresholdGrayscale = true;\n  } else {\n    this.options.thresholdGrayscale = false;\n  }\n  return this;\n}\n\n/**\n * Perform a bitwise boolean operation with operand image.\n *\n * This operation creates an output image where each pixel is the result of\n * the selected bitwise boolean `operation` between the corresponding pixels of the input images.\n *\n * @param {Buffer|string} operand - Buffer containing image data or string containing the path to an image file.\n * @param {string} operator - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.\n * @param {Object} [options]\n * @param {Object} [options.raw] - describes operand when using raw pixel data.\n * @param {number} [options.raw.width]\n * @param {number} [options.raw.height]\n * @param {number} [options.raw.channels]\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction boolean (operand, operator, options) {\n  this.options.boolean = this._createInputDescriptor(operand, options);\n  if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) {\n    this.options.booleanOp = operator;\n  } else {\n    throw is.invalidParameterError('operator', 'one of: and, or, eor', operator);\n  }\n  return this;\n}\n\n/**\n * Apply the linear formula `a` * input + `b` to the image to adjust image levels.\n *\n * When a single number is provided, it will be used for all image channels.\n * When an array of numbers is provided, the array length must match the number of channels.\n *\n * @example\n * await sharp(input)\n *   .linear(0.5, 2)\n *   .toBuffer();\n *\n * @example\n * await sharp(rgbInput)\n *   .linear(\n *     [0.25, 0.5, 0.75],\n *     [150, 100, 50]\n *   )\n *   .toBuffer();\n *\n * @param {(number|number[])} [a=[]] multiplier\n * @param {(number|number[])} [b=[]] offset\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction linear (a, b) {\n  if (!is.defined(a) && is.number(b)) {\n    a = 1.0;\n  } else if (is.number(a) && !is.defined(b)) {\n    b = 0.0;\n  }\n  if (!is.defined(a)) {\n    this.options.linearA = [];\n  } else if (is.number(a)) {\n    this.options.linearA = [a];\n  } else if (Array.isArray(a) && a.length && a.every(is.number)) {\n    this.options.linearA = a;\n  } else {\n    throw is.invalidParameterError('a', 'number or array of numbers', a);\n  }\n  if (!is.defined(b)) {\n    this.options.linearB = [];\n  } else if (is.number(b)) {\n    this.options.linearB = [b];\n  } else if (Array.isArray(b) && b.length && b.every(is.number)) {\n    this.options.linearB = b;\n  } else {\n    throw is.invalidParameterError('b', 'number or array of numbers', b);\n  }\n  if (this.options.linearA.length !== this.options.linearB.length) {\n    throw new Error('Expected a and b to be arrays of the same length');\n  }\n  return this;\n}\n\n/**\n * Recombine the image with the specified matrix.\n *\n * @since 0.21.1\n *\n * @example\n * sharp(input)\n *   .recomb([\n *    [0.3588, 0.7044, 0.1368],\n *    [0.2990, 0.5870, 0.1140],\n *    [0.2392, 0.4696, 0.0912],\n *   ])\n *   .raw()\n *   .toBuffer(function(err, data, info) {\n *     // data contains the raw pixel data after applying the matrix\n *     // With this example input, a sepia filter has been applied\n *   });\n *\n * @param {Array<Array<number>>} inputMatrix - 3x3 or 4x4 Recombination matrix\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction recomb (inputMatrix) {\n  if (!Array.isArray(inputMatrix)) {\n    throw is.invalidParameterError('inputMatrix', 'array', inputMatrix);\n  }\n  if (inputMatrix.length !== 3 && inputMatrix.length !== 4) {\n    throw is.invalidParameterError('inputMatrix', '3x3 or 4x4 array', inputMatrix.length);\n  }\n  const recombMatrix = inputMatrix.flat().map(Number);\n  if (recombMatrix.length !== 9 && recombMatrix.length !== 16) {\n    throw is.invalidParameterError('inputMatrix', 'cardinality of 9 or 16', recombMatrix.length);\n  }\n  this.options.recombMatrix = recombMatrix;\n  return this;\n}\n\n/**\n * Transforms the image using brightness, saturation, hue rotation, and lightness.\n * Brightness and lightness both operate on luminance, with the difference being that\n * brightness is multiplicative whereas lightness is additive.\n *\n * @since 0.22.1\n *\n * @example\n * // increase brightness by a factor of 2\n * const output = await sharp(input)\n *   .modulate({\n *     brightness: 2\n *   })\n *   .toBuffer();\n *\n * @example\n * // hue-rotate by 180 degrees\n * const output = await sharp(input)\n *   .modulate({\n *     hue: 180\n *   })\n *   .toBuffer();\n *\n * @example\n * // increase lightness by +50\n * const output = await sharp(input)\n *   .modulate({\n *     lightness: 50\n *   })\n *   .toBuffer();\n *\n * @example\n * // decrease brightness and saturation while also hue-rotating by 90 degrees\n * const output = await sharp(input)\n *   .modulate({\n *     brightness: 0.5,\n *     saturation: 0.5,\n *     hue: 90,\n *   })\n *   .toBuffer();\n *\n * @param {Object} [options]\n * @param {number} [options.brightness] Brightness multiplier\n * @param {number} [options.saturation] Saturation multiplier\n * @param {number} [options.hue] Degrees for hue rotation\n * @param {number} [options.lightness] Lightness addend\n * @returns {Sharp}\n */\nfunction modulate (options) {\n  if (!is.plainObject(options)) {\n    throw is.invalidParameterError('options', 'plain object', options);\n  }\n  if ('brightness' in options) {\n    if (is.number(options.brightness) && options.brightness >= 0) {\n      this.options.brightness = options.brightness;\n    } else {\n      throw is.invalidParameterError('brightness', 'number above zero', options.brightness);\n    }\n  }\n  if ('saturation' in options) {\n    if (is.number(options.saturation) && options.saturation >= 0) {\n      this.options.saturation = options.saturation;\n    } else {\n      throw is.invalidParameterError('saturation', 'number above zero', options.saturation);\n    }\n  }\n  if ('hue' in options) {\n    if (is.integer(options.hue)) {\n      this.options.hue = options.hue % 360;\n    } else {\n      throw is.invalidParameterError('hue', 'number', options.hue);\n    }\n  }\n  if ('lightness' in options) {\n    if (is.number(options.lightness)) {\n      this.options.lightness = options.lightness;\n    } else {\n      throw is.invalidParameterError('lightness', 'number', options.lightness);\n    }\n  }\n  return this;\n}\n\n/**\n * Decorate the Sharp prototype with operation-related functions.\n * @module Sharp\n * @private\n */\nmodule.exports = (Sharp) => {\n  Object.assign(Sharp.prototype, {\n    autoOrient,\n    rotate,\n    flip,\n    flop,\n    affine,\n    sharpen,\n    erode,\n    dilate,\n    median,\n    blur,\n    flatten,\n    unflatten,\n    gamma,\n    negate,\n    normalise,\n    normalize,\n    clahe,\n    convolve,\n    threshold,\n    boolean,\n    linear,\n    recomb,\n    modulate\n  });\n};\n"
  },
  {
    "path": "lib/output.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst path = require('node:path');\nconst is = require('./is');\nconst sharp = require('./sharp');\n\nconst formats = new Map([\n  ['heic', 'heif'],\n  ['heif', 'heif'],\n  ['avif', 'avif'],\n  ['jpeg', 'jpeg'],\n  ['jpg', 'jpeg'],\n  ['jpe', 'jpeg'],\n  ['tile', 'tile'],\n  ['dz', 'tile'],\n  ['png', 'png'],\n  ['raw', 'raw'],\n  ['tiff', 'tiff'],\n  ['tif', 'tiff'],\n  ['webp', 'webp'],\n  ['gif', 'gif'],\n  ['jp2', 'jp2'],\n  ['jpx', 'jp2'],\n  ['j2k', 'jp2'],\n  ['j2c', 'jp2'],\n  ['jxl', 'jxl']\n]);\n\nconst jp2Regex = /\\.(jp[2x]|j2[kc])$/i;\n\nconst errJp2Save = () => new Error('JP2 output requires libvips with support for OpenJPEG');\n\nconst bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours)));\n\n/**\n * Write output image data to a file.\n *\n * If an explicit output format is not selected, it will be inferred from the extension,\n * with JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported.\n * Note that raw pixel data is only supported for buffer output.\n *\n * By default all metadata will be removed, which includes EXIF-based orientation.\n * See {@link #withmetadata withMetadata} for control over this.\n *\n * The caller is responsible for ensuring directory structures and permissions exist.\n *\n * A `Promise` is returned when `callback` is not provided.\n *\n * @example\n * sharp(input)\n *   .toFile('output.png', (err, info) => { ... });\n *\n * @example\n * sharp(input)\n *   .toFile('output.png')\n *   .then(info => { ... })\n *   .catch(err => { ... });\n *\n * @param {string} fileOut - the path to write the image data to.\n * @param {Function} [callback] - called on completion with two arguments `(err, info)`.\n * `info` contains the output image `format`, `size` (bytes), `width`, `height`,\n * `channels` and `premultiplied` (indicating if premultiplication was used).\n * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.\n * When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region.\n * Animated output will also contain `pageHeight` and `pages`.\n * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.\n * @returns {Promise<Object>} - when no callback is provided\n * @throws {Error} Invalid parameters\n */\nfunction toFile (fileOut, callback) {\n  let err;\n  if (!is.string(fileOut)) {\n    err = new Error('Missing output file path');\n  } else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) {\n    err = new Error('Cannot use same file for input and output');\n  } else if (jp2Regex.test(path.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {\n    err = errJp2Save();\n  }\n  if (err) {\n    if (is.fn(callback)) {\n      callback(err);\n    } else {\n      return Promise.reject(err);\n    }\n  } else {\n    this.options.fileOut = fileOut;\n    const stack = Error();\n    return this._pipeline(callback, stack);\n  }\n  return this;\n}\n\n/**\n * Write output to a Buffer.\n * JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.\n *\n * Use {@link #toformat toFormat} or one of the format-specific functions such as {@link #jpeg jpeg}, {@link #png png} etc. to set the output format.\n *\n * If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.\n *\n * By default all metadata will be removed, which includes EXIF-based orientation.\n * See {@link #withmetadata withMetadata} for control over this.\n *\n * `callback`, if present, gets three arguments `(err, data, info)` where:\n * - `err` is an error, if any.\n * - `data` is the output image data.\n * - `info` contains the output image `format`, `size` (bytes), `width`, `height`,\n * `channels` and `premultiplied` (indicating if premultiplication was used).\n * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.\n * Animated output will also contain `pageHeight` and `pages`.\n * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.\n *\n * A `Promise` is returned when `callback` is not provided.\n *\n * @example\n * sharp(input)\n *   .toBuffer((err, data, info) => { ... });\n *\n * @example\n * sharp(input)\n *   .toBuffer()\n *   .then(data => { ... })\n *   .catch(err => { ... });\n *\n * @example\n * sharp(input)\n *   .png()\n *   .toBuffer({ resolveWithObject: true })\n *   .then(({ data, info }) => { ... })\n *   .catch(err => { ... });\n *\n * @example\n * const { data, info } = await sharp('my-image.jpg')\n *   // output the raw pixels\n *   .raw()\n *   .toBuffer({ resolveWithObject: true });\n *\n * // create a more type safe way to work with the raw pixel data\n * // this will not copy the data, instead it will change `data`s underlying ArrayBuffer\n * // so `data` and `pixelArray` point to the same memory location\n * const pixelArray = new Uint8ClampedArray(data.buffer);\n *\n * // When you are done changing the pixelArray, sharp takes the `pixelArray` as an input\n * const { width, height, channels } = info;\n * await sharp(pixelArray, { raw: { width, height, channels } })\n *   .toFile('my-changed-image.jpg');\n *\n * @param {Object} [options]\n * @param {boolean} [options.resolveWithObject] Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`.\n * @param {Function} [callback]\n * @returns {Promise<Buffer>} - when no callback is provided\n */\nfunction toBuffer (options, callback) {\n  if (is.object(options)) {\n    this._setBooleanOption('resolveWithObject', options.resolveWithObject);\n  } else if (this.options.resolveWithObject) {\n    this.options.resolveWithObject = false;\n  }\n  this.options.fileOut = '';\n  const stack = Error();\n  return this._pipeline(is.fn(options) ? options : callback, stack);\n}\n\n/**\n * Keep all EXIF metadata from the input image in the output image.\n *\n * EXIF metadata is unsupported for TIFF output.\n *\n * @since 0.33.0\n *\n * @example\n * const outputWithExif = await sharp(inputWithExif)\n *   .keepExif()\n *   .toBuffer();\n *\n * @returns {Sharp}\n */\nfunction keepExif () {\n  this.options.keepMetadata |= 0b00001;\n  return this;\n}\n\n/**\n * Set EXIF metadata in the output image, ignoring any EXIF in the input image.\n *\n * @since 0.33.0\n *\n * @example\n * const dataWithExif = await sharp(input)\n *   .withExif({\n *     IFD0: {\n *       Copyright: 'The National Gallery'\n *     },\n *     IFD3: {\n *       GPSLatitudeRef: 'N',\n *       GPSLatitude: '51/1 30/1 3230/100',\n *       GPSLongitudeRef: 'W',\n *       GPSLongitude: '0/1 7/1 4366/100'\n *     }\n *   })\n *   .toBuffer();\n *\n * @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withExif (exif) {\n  if (is.object(exif)) {\n    for (const [ifd, entries] of Object.entries(exif)) {\n      if (is.object(entries)) {\n        for (const [k, v] of Object.entries(entries)) {\n          if (is.string(v)) {\n            this.options.withExif[`exif-${ifd.toLowerCase()}-${k}`] = v;\n          } else {\n            throw is.invalidParameterError(`${ifd}.${k}`, 'string', v);\n          }\n        }\n      } else {\n        throw is.invalidParameterError(ifd, 'object', entries);\n      }\n    }\n  } else {\n    throw is.invalidParameterError('exif', 'object', exif);\n  }\n  this.options.withExifMerge = false;\n  return this.keepExif();\n}\n\n/**\n * Update EXIF metadata from the input image in the output image.\n *\n * @since 0.33.0\n *\n * @example\n * const dataWithMergedExif = await sharp(inputWithExif)\n *   .withExifMerge({\n *     IFD0: {\n *       Copyright: 'The National Gallery'\n *     }\n *   })\n *   .toBuffer();\n *\n * @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withExifMerge (exif) {\n  this.withExif(exif);\n  this.options.withExifMerge = true;\n  return this;\n}\n\n/**\n * Keep ICC profile from the input image in the output image.\n *\n * When input and output colour spaces differ, use with {@link /api-colour/#tocolourspace toColourspace} and optionally {@link /api-colour/#pipelinecolourspace pipelineColourspace}.\n *\n * @since 0.33.0\n *\n * @example\n * const outputWithIccProfile = await sharp(inputWithIccProfile)\n *   .keepIccProfile()\n *   .toBuffer();\n *\n * @example\n * const cmykOutputWithIccProfile = await sharp(cmykInputWithIccProfile)\n *   .pipelineColourspace('cmyk')\n *   .toColourspace('cmyk')\n *   .keepIccProfile()\n *   .toBuffer();\n *\n * @returns {Sharp}\n */\nfunction keepIccProfile () {\n  this.options.keepMetadata |= 0b01000;\n  return this;\n}\n\n/**\n * Transform using an ICC profile and attach to the output image.\n *\n * This can either be an absolute filesystem path or\n * built-in profile name (`srgb`, `p3`, `cmyk`).\n *\n * @since 0.33.0\n *\n * @example\n * const outputWithP3 = await sharp(input)\n *   .withIccProfile('p3')\n *   .toBuffer();\n *\n * @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk).\n * @param {Object} [options]\n * @param {number} [options.attach=true] Should the ICC profile be included in the output image metadata?\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withIccProfile (icc, options) {\n  if (is.string(icc)) {\n    this.options.withIccProfile = icc;\n  } else {\n    throw is.invalidParameterError('icc', 'string', icc);\n  }\n  this.keepIccProfile();\n  if (is.object(options)) {\n    if (is.defined(options.attach)) {\n      if (is.bool(options.attach)) {\n        if (!options.attach) {\n          this.options.keepMetadata &= ~0b01000;\n        }\n      } else {\n        throw is.invalidParameterError('attach', 'boolean', options.attach);\n      }\n    }\n  }\n  return this;\n}\n\n/**\n * Keep XMP metadata from the input image in the output image.\n *\n * @since 0.34.3\n *\n * @example\n * const outputWithXmp = await sharp(inputWithXmp)\n *   .keepXmp()\n *   .toBuffer();\n *\n * @returns {Sharp}\n */\nfunction keepXmp () {\n  this.options.keepMetadata |= 0b00010;\n  return this;\n}\n\n/**\n * Set XMP metadata in the output image.\n *\n * Supported by PNG, JPEG, WebP, and TIFF output.\n *\n * @since 0.34.3\n *\n * @example\n * const xmpString = `\n *   <?xml version=\"1.0\"?>\n *   <x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n *     <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n *       <rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n *         <dc:creator><rdf:Seq><rdf:li>John Doe</rdf:li></rdf:Seq></dc:creator>\n *       </rdf:Description>\n *     </rdf:RDF>\n *   </x:xmpmeta>`;\n *\n * const data = await sharp(input)\n *   .withXmp(xmpString)\n *   .toBuffer();\n *\n * @param {string} xmp String containing XMP metadata to be embedded in the output image.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withXmp (xmp) {\n  if (is.string(xmp) && xmp.length > 0) {\n    this.options.withXmp = xmp;\n    this.options.keepMetadata |= 0b00010;\n  } else {\n    throw is.invalidParameterError('xmp', 'non-empty string', xmp);\n  }\n  return this;\n}\n\n/**\n * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.\n *\n * The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent\n * sRGB colour space and strip all metadata, including the removal of any ICC profile.\n *\n * @since 0.33.0\n *\n * @example\n * const outputWithMetadata = await sharp(inputWithMetadata)\n *   .keepMetadata()\n *   .toBuffer();\n *\n * @returns {Sharp}\n */\nfunction keepMetadata () {\n  this.options.keepMetadata = 0b11111;\n  return this;\n}\n\n/**\n * Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image.\n *\n * This will also convert to and add a web-friendly sRGB ICC profile if appropriate.\n *\n * Allows orientation and density to be set or updated.\n *\n * @example\n * const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)\n *   .withMetadata()\n *   .toBuffer();\n *\n * @example\n * // Set output metadata to 96 DPI\n * const data = await sharp(input)\n *   .withMetadata({ density: 96 })\n *   .toBuffer();\n *\n * @param {Object} [options]\n * @param {number} [options.orientation] Used to update the EXIF `Orientation` tag, integer between 1 and 8.\n * @param {number} [options.density] Number of pixels per inch (DPI).\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withMetadata (options) {\n  this.keepMetadata();\n  this.withIccProfile('srgb');\n  if (is.object(options)) {\n    if (is.defined(options.orientation)) {\n      if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) {\n        this.options.withMetadataOrientation = options.orientation;\n      } else {\n        throw is.invalidParameterError('orientation', 'integer between 1 and 8', options.orientation);\n      }\n    }\n    if (is.defined(options.density)) {\n      if (is.number(options.density) && options.density > 0) {\n        this.options.withMetadataDensity = options.density;\n      } else {\n        throw is.invalidParameterError('density', 'positive number', options.density);\n      }\n    }\n    if (is.defined(options.icc)) {\n      this.withIccProfile(options.icc);\n    }\n    if (is.defined(options.exif)) {\n      this.withExifMerge(options.exif);\n    }\n  }\n  return this;\n}\n\n/**\n * Force output to a given format.\n *\n * @example\n * // Convert any input to PNG output\n * const data = await sharp(input)\n *   .toFormat('png')\n *   .toBuffer();\n *\n * @param {(string|Object)} format - as a string or an Object with an 'id' attribute\n * @param {Object} options - output options\n * @returns {Sharp}\n * @throws {Error} unsupported format or options\n */\nfunction toFormat (format, options) {\n  const actualFormat = formats.get((is.object(format) && is.string(format.id) ? format.id : format).toLowerCase());\n  if (!actualFormat) {\n    throw is.invalidParameterError('format', `one of: ${[...formats.keys()].join(', ')}`, format);\n  }\n  return this[actualFormat](options);\n}\n\n/**\n * Use these JPEG options for output image.\n *\n * @example\n * // Convert any input to very high quality JPEG output\n * const data = await sharp(input)\n *   .jpeg({\n *     quality: 100,\n *     chromaSubsampling: '4:4:4'\n *   })\n *   .toBuffer();\n *\n * @example\n * // Use mozjpeg to reduce output JPEG file size (slower)\n * const data = await sharp(input)\n *   .jpeg({ mozjpeg: true })\n *   .toBuffer();\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=80] - quality, integer 1-100\n * @param {boolean} [options.progressive=false] - use progressive (interlace) scan\n * @param {string} [options.chromaSubsampling='4:2:0'] - set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling\n * @param {boolean} [options.optimiseCoding=true] - optimise Huffman coding tables\n * @param {boolean} [options.optimizeCoding=true] - alternative spelling of optimiseCoding\n * @param {boolean} [options.mozjpeg=false] - use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }`\n * @param {boolean} [options.trellisQuantisation=false] - apply trellis quantisation\n * @param {boolean} [options.overshootDeringing=false] - apply overshoot deringing\n * @param {boolean} [options.optimiseScans=false] - optimise progressive scans, forces progressive\n * @param {boolean} [options.optimizeScans=false] - alternative spelling of optimiseScans\n * @param {number} [options.quantisationTable=0] - quantization table to use, integer 0-8\n * @param {number} [options.quantizationTable=0] - alternative spelling of quantisationTable\n * @param {boolean} [options.force=true] - force JPEG output, otherwise attempt to use input format\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction jpeg (options) {\n  if (is.object(options)) {\n    if (is.defined(options.quality)) {\n      if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n        this.options.jpegQuality = options.quality;\n      } else {\n        throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n      }\n    }\n    if (is.defined(options.progressive)) {\n      this._setBooleanOption('jpegProgressive', options.progressive);\n    }\n    if (is.defined(options.chromaSubsampling)) {\n      if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {\n        this.options.jpegChromaSubsampling = options.chromaSubsampling;\n      } else {\n        throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);\n      }\n    }\n    const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding;\n    if (is.defined(optimiseCoding)) {\n      this._setBooleanOption('jpegOptimiseCoding', optimiseCoding);\n    }\n    if (is.defined(options.mozjpeg)) {\n      if (is.bool(options.mozjpeg)) {\n        if (options.mozjpeg) {\n          this.options.jpegTrellisQuantisation = true;\n          this.options.jpegOvershootDeringing = true;\n          this.options.jpegOptimiseScans = true;\n          this.options.jpegProgressive = true;\n          this.options.jpegQuantisationTable = 3;\n        }\n      } else {\n        throw is.invalidParameterError('mozjpeg', 'boolean', options.mozjpeg);\n      }\n    }\n    const trellisQuantisation = is.bool(options.trellisQuantization) ? options.trellisQuantization : options.trellisQuantisation;\n    if (is.defined(trellisQuantisation)) {\n      this._setBooleanOption('jpegTrellisQuantisation', trellisQuantisation);\n    }\n    if (is.defined(options.overshootDeringing)) {\n      this._setBooleanOption('jpegOvershootDeringing', options.overshootDeringing);\n    }\n    const optimiseScans = is.bool(options.optimizeScans) ? options.optimizeScans : options.optimiseScans;\n    if (is.defined(optimiseScans)) {\n      this._setBooleanOption('jpegOptimiseScans', optimiseScans);\n      if (optimiseScans) {\n        this.options.jpegProgressive = true;\n      }\n    }\n    const quantisationTable = is.number(options.quantizationTable) ? options.quantizationTable : options.quantisationTable;\n    if (is.defined(quantisationTable)) {\n      if (is.integer(quantisationTable) && is.inRange(quantisationTable, 0, 8)) {\n        this.options.jpegQuantisationTable = quantisationTable;\n      } else {\n        throw is.invalidParameterError('quantisationTable', 'integer between 0 and 8', quantisationTable);\n      }\n    }\n  }\n  return this._updateFormatOut('jpeg', options);\n}\n\n/**\n * Use these PNG options for output image.\n *\n * By default, PNG output is full colour at 8 bits per pixel.\n *\n * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.\n * Set `palette` to `true` for slower, indexed PNG output.\n *\n * For 16 bits per pixel output, convert to `rgb16` via\n * {@link /api-colour/#tocolourspace toColourspace}.\n *\n * @example\n * // Convert any input to full colour PNG output\n * const data = await sharp(input)\n *   .png()\n *   .toBuffer();\n *\n * @example\n * // Convert any input to indexed PNG output (slower)\n * const data = await sharp(input)\n *   .png({ palette: true })\n *   .toBuffer();\n *\n * @example\n * // Output 16 bits per pixel RGB(A)\n * const data = await sharp(input)\n *  .toColourspace('rgb16')\n *  .png()\n *  .toBuffer();\n *\n * @param {Object} [options]\n * @param {boolean} [options.progressive=false] - use progressive (interlace) scan\n * @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest)\n * @param {boolean} [options.adaptiveFiltering=false] - use adaptive row filtering\n * @param {boolean} [options.palette=false] - quantise to a palette-based image with alpha transparency support\n * @param {number} [options.quality=100] - use the lowest number of colours needed to achieve given quality, sets `palette` to `true`\n * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true`\n * @param {number} [options.colours=256] - maximum number of palette entries, sets `palette` to `true`\n * @param {number} [options.colors=256] - alternative spelling of `options.colours`, sets `palette` to `true`\n * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, sets `palette` to `true`\n * @param {boolean} [options.force=true] - force PNG output, otherwise attempt to use input format\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction png (options) {\n  if (is.object(options)) {\n    if (is.defined(options.progressive)) {\n      this._setBooleanOption('pngProgressive', options.progressive);\n    }\n    if (is.defined(options.compressionLevel)) {\n      if (is.integer(options.compressionLevel) && is.inRange(options.compressionLevel, 0, 9)) {\n        this.options.pngCompressionLevel = options.compressionLevel;\n      } else {\n        throw is.invalidParameterError('compressionLevel', 'integer between 0 and 9', options.compressionLevel);\n      }\n    }\n    if (is.defined(options.adaptiveFiltering)) {\n      this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering);\n    }\n    const colours = options.colours || options.colors;\n    if (is.defined(colours)) {\n      if (is.integer(colours) && is.inRange(colours, 2, 256)) {\n        this.options.pngBitdepth = bitdepthFromColourCount(colours);\n      } else {\n        throw is.invalidParameterError('colours', 'integer between 2 and 256', colours);\n      }\n    }\n    if (is.defined(options.palette)) {\n      this._setBooleanOption('pngPalette', options.palette);\n    } else if ([options.quality, options.effort, options.colours, options.colors, options.dither].some(is.defined)) {\n      this._setBooleanOption('pngPalette', true);\n    }\n    if (this.options.pngPalette) {\n      if (is.defined(options.quality)) {\n        if (is.integer(options.quality) && is.inRange(options.quality, 0, 100)) {\n          this.options.pngQuality = options.quality;\n        } else {\n          throw is.invalidParameterError('quality', 'integer between 0 and 100', options.quality);\n        }\n      }\n      if (is.defined(options.effort)) {\n        if (is.integer(options.effort) && is.inRange(options.effort, 1, 10)) {\n          this.options.pngEffort = options.effort;\n        } else {\n          throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort);\n        }\n      }\n      if (is.defined(options.dither)) {\n        if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) {\n          this.options.pngDither = options.dither;\n        } else {\n          throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);\n        }\n      }\n    }\n  }\n  return this._updateFormatOut('png', options);\n}\n\n/**\n * Use these WebP options for output image.\n *\n * @example\n * // Convert any input to lossless WebP output\n * const data = await sharp(input)\n *   .webp({ lossless: true })\n *   .toBuffer();\n *\n * @example\n * // Optimise the file size of an animated WebP\n * const outputWebp = await sharp(inputWebp, { animated: true })\n *   .webp({ effort: 6 })\n *   .toBuffer();\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=80] - quality, integer 1-100\n * @param {number} [options.alphaQuality=100] - quality of alpha layer, integer 0-100\n * @param {boolean} [options.lossless=false] - use lossless compression mode\n * @param {boolean} [options.nearLossless=false] - use near_lossless compression mode\n * @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling\n * @param {boolean} [options.smartDeblock=false] - auto-adjust the deblocking filter, can improve low contrast edges (slow)\n * @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text\n * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest)\n * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation\n * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)\n * @param {boolean} [options.minSize=false] - prevent use of animation key frames to minimise file size (slow)\n * @param {boolean} [options.mixed=false] - allow mixture of lossy and lossless animation frames (slow)\n * @param {boolean} [options.force=true] - force WebP output, otherwise attempt to use input format\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction webp (options) {\n  if (is.object(options)) {\n    if (is.defined(options.quality)) {\n      if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n        this.options.webpQuality = options.quality;\n      } else {\n        throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n      }\n    }\n    if (is.defined(options.alphaQuality)) {\n      if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) {\n        this.options.webpAlphaQuality = options.alphaQuality;\n      } else {\n        throw is.invalidParameterError('alphaQuality', 'integer between 0 and 100', options.alphaQuality);\n      }\n    }\n    if (is.defined(options.lossless)) {\n      this._setBooleanOption('webpLossless', options.lossless);\n    }\n    if (is.defined(options.nearLossless)) {\n      this._setBooleanOption('webpNearLossless', options.nearLossless);\n    }\n    if (is.defined(options.smartSubsample)) {\n      this._setBooleanOption('webpSmartSubsample', options.smartSubsample);\n    }\n    if (is.defined(options.smartDeblock)) {\n      this._setBooleanOption('webpSmartDeblock', options.smartDeblock);\n    }\n    if (is.defined(options.preset)) {\n      if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) {\n        this.options.webpPreset = options.preset;\n      } else {\n        throw is.invalidParameterError('preset', 'one of: default, photo, picture, drawing, icon, text', options.preset);\n      }\n    }\n    if (is.defined(options.effort)) {\n      if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) {\n        this.options.webpEffort = options.effort;\n      } else {\n        throw is.invalidParameterError('effort', 'integer between 0 and 6', options.effort);\n      }\n    }\n    if (is.defined(options.minSize)) {\n      this._setBooleanOption('webpMinSize', options.minSize);\n    }\n    if (is.defined(options.mixed)) {\n      this._setBooleanOption('webpMixed', options.mixed);\n    }\n  }\n  trySetAnimationOptions(options, this.options);\n  return this._updateFormatOut('webp', options);\n}\n\n/**\n * Use these GIF options for the output image.\n *\n * The first entry in the palette is reserved for transparency.\n *\n * The palette of the input image will be re-used if possible.\n *\n * @since 0.30.0\n *\n * @example\n * // Convert PNG to GIF\n * await sharp(pngBuffer)\n *   .gif()\n *   .toBuffer();\n *\n * @example\n * // Convert animated WebP to animated GIF\n * await sharp('animated.webp', { animated: true })\n *   .toFile('animated.gif');\n *\n * @example\n * // Create a 128x128, cropped, non-dithered, animated thumbnail of an animated GIF\n * const out = await sharp('in.gif', { animated: true })\n *   .resize({ width: 128, height: 128 })\n *   .gif({ dither: 0 })\n *   .toBuffer();\n *\n * @example\n * // Lossy file size reduction of animated GIF\n * await sharp('in.gif', { animated: true })\n *   .gif({ interFrameMaxError: 8 })\n *   .toFile('optim.gif');\n *\n * @param {Object} [options] - output options\n * @param {boolean} [options.reuse=true] - re-use existing palette, otherwise generate new (slow)\n * @param {boolean} [options.progressive=false] - use progressive (interlace) scan\n * @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256\n * @param {number} [options.colors=256] - alternative spelling of `options.colours`\n * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest)\n * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most)\n * @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32\n * @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256\n * @param {boolean} [options.keepDuplicateFrames=false] - keep duplicate frames in the output instead of combining them\n * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation\n * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)\n * @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction gif (options) {\n  if (is.object(options)) {\n    if (is.defined(options.reuse)) {\n      this._setBooleanOption('gifReuse', options.reuse);\n    }\n    if (is.defined(options.progressive)) {\n      this._setBooleanOption('gifProgressive', options.progressive);\n    }\n    const colours = options.colours || options.colors;\n    if (is.defined(colours)) {\n      if (is.integer(colours) && is.inRange(colours, 2, 256)) {\n        this.options.gifBitdepth = bitdepthFromColourCount(colours);\n      } else {\n        throw is.invalidParameterError('colours', 'integer between 2 and 256', colours);\n      }\n    }\n    if (is.defined(options.effort)) {\n      if (is.number(options.effort) && is.inRange(options.effort, 1, 10)) {\n        this.options.gifEffort = options.effort;\n      } else {\n        throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort);\n      }\n    }\n    if (is.defined(options.dither)) {\n      if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) {\n        this.options.gifDither = options.dither;\n      } else {\n        throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);\n      }\n    }\n    if (is.defined(options.interFrameMaxError)) {\n      if (is.number(options.interFrameMaxError) && is.inRange(options.interFrameMaxError, 0, 32)) {\n        this.options.gifInterFrameMaxError = options.interFrameMaxError;\n      } else {\n        throw is.invalidParameterError('interFrameMaxError', 'number between 0.0 and 32.0', options.interFrameMaxError);\n      }\n    }\n    if (is.defined(options.interPaletteMaxError)) {\n      if (is.number(options.interPaletteMaxError) && is.inRange(options.interPaletteMaxError, 0, 256)) {\n        this.options.gifInterPaletteMaxError = options.interPaletteMaxError;\n      } else {\n        throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError);\n      }\n    }\n    if (is.defined(options.keepDuplicateFrames)) {\n      if (is.bool(options.keepDuplicateFrames)) {\n        this._setBooleanOption('gifKeepDuplicateFrames', options.keepDuplicateFrames);\n      } else {\n        throw is.invalidParameterError('keepDuplicateFrames', 'boolean', options.keepDuplicateFrames);\n      }\n    }\n  }\n  trySetAnimationOptions(options, this.options);\n  return this._updateFormatOut('gif', options);\n}\n\n/**\n * Use these JP2 options for output image.\n *\n * Requires libvips compiled with support for OpenJPEG.\n * The prebuilt binaries do not include this - see\n * {@link /install#custom-libvips installing a custom libvips}.\n *\n * @example\n * // Convert any input to lossless JP2 output\n * const data = await sharp(input)\n *   .jp2({ lossless: true })\n *   .toBuffer();\n *\n * @example\n * // Convert any input to very high quality JP2 output\n * const data = await sharp(input)\n *   .jp2({\n *     quality: 100,\n *     chromaSubsampling: '4:4:4'\n *   })\n *   .toBuffer();\n *\n * @since 0.29.1\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=80] - quality, integer 1-100\n * @param {boolean} [options.lossless=false] - use lossless compression mode\n * @param {number} [options.tileWidth=512] - horizontal tile size\n * @param {number} [options.tileHeight=512] - vertical tile size\n * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction jp2 (options) {\n  /* node:coverage ignore next 41 */\n  if (!this.constructor.format.jp2k.output.buffer) {\n    throw errJp2Save();\n  }\n  if (is.object(options)) {\n    if (is.defined(options.quality)) {\n      if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n        this.options.jp2Quality = options.quality;\n      } else {\n        throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n      }\n    }\n    if (is.defined(options.lossless)) {\n      if (is.bool(options.lossless)) {\n        this.options.jp2Lossless = options.lossless;\n      } else {\n        throw is.invalidParameterError('lossless', 'boolean', options.lossless);\n      }\n    }\n    if (is.defined(options.tileWidth)) {\n      if (is.integer(options.tileWidth) && is.inRange(options.tileWidth, 1, 32768)) {\n        this.options.jp2TileWidth = options.tileWidth;\n      } else {\n        throw is.invalidParameterError('tileWidth', 'integer between 1 and 32768', options.tileWidth);\n      }\n    }\n    if (is.defined(options.tileHeight)) {\n      if (is.integer(options.tileHeight) && is.inRange(options.tileHeight, 1, 32768)) {\n        this.options.jp2TileHeight = options.tileHeight;\n      } else {\n        throw is.invalidParameterError('tileHeight', 'integer between 1 and 32768', options.tileHeight);\n      }\n    }\n    if (is.defined(options.chromaSubsampling)) {\n      if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {\n        this.options.jp2ChromaSubsampling = options.chromaSubsampling;\n      } else {\n        throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);\n      }\n    }\n  }\n  return this._updateFormatOut('jp2', options);\n}\n\n/**\n * Set animation options if available.\n * @private\n *\n * @param {Object} [source] - output options\n * @param {number} [source.loop=0] - number of animation iterations, use 0 for infinite animation\n * @param {number[]} [source.delay] - list of delays between animation frames (in milliseconds)\n * @param {Object} [target] - target object for valid options\n * @throws {Error} Invalid options\n */\nfunction trySetAnimationOptions (source, target) {\n  if (is.object(source) && is.defined(source.loop)) {\n    if (is.integer(source.loop) && is.inRange(source.loop, 0, 65535)) {\n      target.loop = source.loop;\n    } else {\n      throw is.invalidParameterError('loop', 'integer between 0 and 65535', source.loop);\n    }\n  }\n  if (is.object(source) && is.defined(source.delay)) {\n    // We allow singular values as well\n    if (is.integer(source.delay) && is.inRange(source.delay, 0, 65535)) {\n      target.delay = [source.delay];\n    } else if (\n      Array.isArray(source.delay) &&\n      source.delay.every(is.integer) &&\n      source.delay.every(v => is.inRange(v, 0, 65535))) {\n      target.delay = source.delay;\n    } else {\n      throw is.invalidParameterError('delay', 'integer or an array of integers between 0 and 65535', source.delay);\n    }\n  }\n}\n\n/**\n * Use these TIFF options for output image.\n *\n * The `density` can be set in pixels/inch via {@link #withmetadata withMetadata}\n * instead of providing `xres` and `yres` in pixels/mm.\n *\n * @example\n * // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output\n * sharp('input.svg')\n *   .tiff({\n *     compression: 'lzw',\n *     bitdepth: 1\n *   })\n *   .toFile('1-bpp-output.tiff')\n *   .then(info => { ... });\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=80] - quality, integer 1-100\n * @param {boolean} [options.force=true] - force TIFF output, otherwise attempt to use input format\n * @param {string} [options.compression='jpeg'] - compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k\n * @param {boolean} [options.bigtiff=false] - use BigTIFF variant (has no effect when compression is none)\n * @param {string} [options.predictor='horizontal'] - compression predictor options: none, horizontal, float\n * @param {boolean} [options.pyramid=false] - write an image pyramid\n * @param {boolean} [options.tile=false] - write a tiled tiff\n * @param {number} [options.tileWidth=256] - horizontal tile size\n * @param {number} [options.tileHeight=256] - vertical tile size\n * @param {number} [options.xres=1.0] - horizontal resolution in pixels/mm\n * @param {number} [options.yres=1.0] - vertical resolution in pixels/mm\n * @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm\n * @param {number} [options.bitdepth=8] - reduce bitdepth to 1, 2 or 4 bit\n * @param {boolean} [options.miniswhite=false] - write 1-bit images as miniswhite\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction tiff (options) {\n  if (is.object(options)) {\n    if (is.defined(options.quality)) {\n      if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n        this.options.tiffQuality = options.quality;\n      } else {\n        throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n      }\n    }\n    if (is.defined(options.bitdepth)) {\n      if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [1, 2, 4, 8])) {\n        this.options.tiffBitdepth = options.bitdepth;\n      } else {\n        throw is.invalidParameterError('bitdepth', '1, 2, 4 or 8', options.bitdepth);\n      }\n    }\n    // tiling\n    if (is.defined(options.tile)) {\n      this._setBooleanOption('tiffTile', options.tile);\n    }\n    if (is.defined(options.tileWidth)) {\n      if (is.integer(options.tileWidth) && options.tileWidth > 0) {\n        this.options.tiffTileWidth = options.tileWidth;\n      } else {\n        throw is.invalidParameterError('tileWidth', 'integer greater than zero', options.tileWidth);\n      }\n    }\n    if (is.defined(options.tileHeight)) {\n      if (is.integer(options.tileHeight) && options.tileHeight > 0) {\n        this.options.tiffTileHeight = options.tileHeight;\n      } else {\n        throw is.invalidParameterError('tileHeight', 'integer greater than zero', options.tileHeight);\n      }\n    }\n    // miniswhite\n    if (is.defined(options.miniswhite)) {\n      this._setBooleanOption('tiffMiniswhite', options.miniswhite);\n    }\n    // pyramid\n    if (is.defined(options.pyramid)) {\n      this._setBooleanOption('tiffPyramid', options.pyramid);\n    }\n    // resolution\n    if (is.defined(options.xres)) {\n      if (is.number(options.xres) && options.xres > 0) {\n        this.options.tiffXres = options.xres;\n      } else {\n        throw is.invalidParameterError('xres', 'number greater than zero', options.xres);\n      }\n    }\n    if (is.defined(options.yres)) {\n      if (is.number(options.yres) && options.yres > 0) {\n        this.options.tiffYres = options.yres;\n      } else {\n        throw is.invalidParameterError('yres', 'number greater than zero', options.yres);\n      }\n    }\n    // compression\n    if (is.defined(options.compression)) {\n      if (is.string(options.compression) && is.inArray(options.compression, ['none', 'jpeg', 'deflate', 'packbits', 'ccittfax4', 'lzw', 'webp', 'zstd', 'jp2k'])) {\n        this.options.tiffCompression = options.compression;\n      } else {\n        throw is.invalidParameterError('compression', 'one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k', options.compression);\n      }\n    }\n    // bigtiff\n    if (is.defined(options.bigtiff)) {\n      this._setBooleanOption('tiffBigtiff', options.bigtiff);\n    }\n    // predictor\n    if (is.defined(options.predictor)) {\n      if (is.string(options.predictor) && is.inArray(options.predictor, ['none', 'horizontal', 'float'])) {\n        this.options.tiffPredictor = options.predictor;\n      } else {\n        throw is.invalidParameterError('predictor', 'one of: none, horizontal, float', options.predictor);\n      }\n    }\n    // resolutionUnit\n    if (is.defined(options.resolutionUnit)) {\n      if (is.string(options.resolutionUnit) && is.inArray(options.resolutionUnit, ['inch', 'cm'])) {\n        this.options.tiffResolutionUnit = options.resolutionUnit;\n      } else {\n        throw is.invalidParameterError('resolutionUnit', 'one of: inch, cm', options.resolutionUnit);\n      }\n    }\n  }\n  return this._updateFormatOut('tiff', options);\n}\n\n/**\n * Use these AVIF options for output image.\n *\n * AVIF image sequences are not supported.\n * Prebuilt binaries support a bitdepth of 8 only.\n *\n * This feature is experimental on the Windows ARM64 platform\n * and requires a CPU with ARM64v8.4 or later.\n *\n * @example\n * const data = await sharp(input)\n *   .avif({ effort: 2 })\n *   .toBuffer();\n *\n * @example\n * const data = await sharp(input)\n *   .avif({ lossless: true })\n *   .toBuffer();\n *\n * @since 0.27.0\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=50] - quality, integer 1-100\n * @param {boolean} [options.lossless=false] - use lossless compression\n * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)\n * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling\n * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction avif (options) {\n  return this.heif({ ...options, compression: 'av1' });\n}\n\n/**\n * Use these HEIF options for output image.\n *\n * Support for patent-encumbered HEIC images using `hevc` compression requires the use of a\n * globally-installed libvips compiled with support for libheif, libde265 and x265.\n *\n * @example\n * const data = await sharp(input)\n *   .heif({ compression: 'hevc' })\n *   .toBuffer();\n *\n * @since 0.23.0\n *\n * @param {Object} options - output options\n * @param {string} options.compression - compression format: av1, hevc\n * @param {number} [options.quality=50] - quality, integer 1-100\n * @param {boolean} [options.lossless=false] - use lossless compression\n * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)\n * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling\n * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction heif (options) {\n  if (is.object(options)) {\n    if (is.string(options.compression) && is.inArray(options.compression, ['av1', 'hevc'])) {\n      this.options.heifCompression = options.compression;\n    } else {\n      throw is.invalidParameterError('compression', 'one of: av1, hevc', options.compression);\n    }\n    if (is.defined(options.quality)) {\n      if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n        this.options.heifQuality = options.quality;\n      } else {\n        throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n      }\n    }\n    if (is.defined(options.lossless)) {\n      if (is.bool(options.lossless)) {\n        this.options.heifLossless = options.lossless;\n      } else {\n        throw is.invalidParameterError('lossless', 'boolean', options.lossless);\n      }\n    }\n    if (is.defined(options.effort)) {\n      if (is.integer(options.effort) && is.inRange(options.effort, 0, 9)) {\n        this.options.heifEffort = options.effort;\n      } else {\n        throw is.invalidParameterError('effort', 'integer between 0 and 9', options.effort);\n      }\n    }\n    if (is.defined(options.chromaSubsampling)) {\n      if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {\n        this.options.heifChromaSubsampling = options.chromaSubsampling;\n      } else {\n        throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);\n      }\n    }\n    if (is.defined(options.bitdepth)) {\n      if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [8, 10, 12])) {\n        if (options.bitdepth !== 8 && this.constructor.versions.heif) {\n          throw is.invalidParameterError('bitdepth when using prebuilt binaries', 8, options.bitdepth);\n        }\n        this.options.heifBitdepth = options.bitdepth;\n      } else {\n        throw is.invalidParameterError('bitdepth', '8, 10 or 12', options.bitdepth);\n      }\n    }\n  } else {\n    throw is.invalidParameterError('options', 'Object', options);\n  }\n  return this._updateFormatOut('heif', options);\n}\n\n/**\n * Use these JPEG-XL (JXL) options for output image.\n *\n * This feature is experimental, please do not use in production systems.\n *\n * Requires libvips compiled with support for libjxl.\n * The prebuilt binaries do not include this - see\n * {@link /install/#custom-libvips installing a custom libvips}.\n *\n * @since 0.31.3\n *\n * @param {Object} [options] - output options\n * @param {number} [options.distance=1.0] - maximum encoding error, between 0 (highest quality) and 15 (lowest quality)\n * @param {number} [options.quality] - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified\n * @param {number} [options.decodingTier=0] - target decode speed tier, between 0 (highest quality) and 4 (lowest quality)\n * @param {boolean} [options.lossless=false] - use lossless compression\n * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 9 (slowest)\n * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation\n * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction jxl (options) {\n  if (is.object(options)) {\n    if (is.defined(options.quality)) {\n      if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n        // https://github.com/libjxl/libjxl/blob/0aeea7f180bafd6893c1db8072dcb67d2aa5b03d/tools/cjxl_main.cc#L640-L644\n        this.options.jxlDistance = options.quality >= 30\n          ? 0.1 + (100 - options.quality) * 0.09\n          : 53 / 3000 * options.quality * options.quality - 23 / 20 * options.quality + 25;\n      } else {\n        throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n      }\n    } else if (is.defined(options.distance)) {\n      if (is.number(options.distance) && is.inRange(options.distance, 0, 15)) {\n        this.options.jxlDistance = options.distance;\n      } else {\n        throw is.invalidParameterError('distance', 'number between 0.0 and 15.0', options.distance);\n      }\n    }\n    if (is.defined(options.decodingTier)) {\n      if (is.integer(options.decodingTier) && is.inRange(options.decodingTier, 0, 4)) {\n        this.options.jxlDecodingTier = options.decodingTier;\n      } else {\n        throw is.invalidParameterError('decodingTier', 'integer between 0 and 4', options.decodingTier);\n      }\n    }\n    if (is.defined(options.lossless)) {\n      if (is.bool(options.lossless)) {\n        this.options.jxlLossless = options.lossless;\n      } else {\n        throw is.invalidParameterError('lossless', 'boolean', options.lossless);\n      }\n    }\n    if (is.defined(options.effort)) {\n      if (is.integer(options.effort) && is.inRange(options.effort, 1, 9)) {\n        this.options.jxlEffort = options.effort;\n      } else {\n        throw is.invalidParameterError('effort', 'integer between 1 and 9', options.effort);\n      }\n    }\n  }\n  trySetAnimationOptions(options, this.options);\n  return this._updateFormatOut('jxl', options);\n}\n\n/**\n * Force output to be raw, uncompressed pixel data.\n * Pixel ordering is left-to-right, top-to-bottom, without padding.\n * Channel ordering will be RGB or RGBA for non-greyscale colourspaces.\n *\n * @example\n * // Extract raw, unsigned 8-bit RGB pixel data from JPEG input\n * const { data, info } = await sharp('input.jpg')\n *   .raw()\n *   .toBuffer({ resolveWithObject: true });\n *\n * @example\n * // Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input\n * const data = await sharp('input.png')\n *   .ensureAlpha()\n *   .extractChannel(3)\n *   .toColourspace('b-w')\n *   .raw({ depth: 'ushort' })\n *   .toBuffer();\n *\n * @param {Object} [options] - output options\n * @param {string} [options.depth='uchar'] - bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction raw (options) {\n  if (is.object(options)) {\n    if (is.defined(options.depth)) {\n      if (is.string(options.depth) && is.inArray(options.depth,\n        ['char', 'uchar', 'short', 'ushort', 'int', 'uint', 'float', 'complex', 'double', 'dpcomplex']\n      )) {\n        this.options.rawDepth = options.depth;\n      } else {\n        throw is.invalidParameterError('depth', 'one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex', options.depth);\n      }\n    }\n  }\n  return this._updateFormatOut('raw');\n}\n\n/**\n * Use tile-based deep zoom (image pyramid) output.\n *\n * Set the format and options for tile images via the `toFormat`, `jpeg`, `png` or `webp` functions.\n * Use a `.zip` or `.szi` file extension with `toFile` to write to a compressed archive file format.\n *\n * The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`.\n *\n * @example\n *  sharp('input.tiff')\n *   .png()\n *   .tile({\n *     size: 512\n *   })\n *   .toFile('output.dz', function(err, info) {\n *     // output.dzi is the Deep Zoom XML definition\n *     // output_files contains 512x512 tiles grouped by zoom level\n *   });\n *\n * @example\n * const zipFileWithTiles = await sharp(input)\n *   .tile({ basename: \"tiles\" })\n *   .toBuffer();\n *\n * @example\n * const iiififier = sharp().tile({ layout: \"iiif\" });\n * readableStream\n *   .pipe(iiififier)\n *   .pipe(writeableStream);\n *\n * @param {Object} [options]\n * @param {number} [options.size=256] tile size in pixels, a value between 1 and 8192.\n * @param {number} [options.overlap=0] tile overlap in pixels, a value between 0 and 8192.\n * @param {number} [options.angle=0] tile angle of rotation, must be a multiple of 90.\n * @param {string|Object} [options.background={r: 255, g: 255, b: 255, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency.\n * @param {string} [options.depth] how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.\n * @param {number} [options.skipBlanks=-1] Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise.\n * @param {string} [options.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file).\n * @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`.\n * @param {boolean} [options.centre=false] centre image in tile.\n * @param {boolean} [options.center=false] alternative spelling of centre.\n * @param {string} [options.id='https://example.com/iiif'] when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json`\n * @param {string} [options.basename] the name of the directory within the zip file when container is `zip`.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction tile (options) {\n  if (is.object(options)) {\n    // Size of square tiles, in pixels\n    if (is.defined(options.size)) {\n      if (is.integer(options.size) && is.inRange(options.size, 1, 8192)) {\n        this.options.tileSize = options.size;\n      } else {\n        throw is.invalidParameterError('size', 'integer between 1 and 8192', options.size);\n      }\n    }\n    // Overlap of tiles, in pixels\n    if (is.defined(options.overlap)) {\n      if (is.integer(options.overlap) && is.inRange(options.overlap, 0, 8192)) {\n        if (options.overlap > this.options.tileSize) {\n          throw is.invalidParameterError('overlap', `<= size (${this.options.tileSize})`, options.overlap);\n        }\n        this.options.tileOverlap = options.overlap;\n      } else {\n        throw is.invalidParameterError('overlap', 'integer between 0 and 8192', options.overlap);\n      }\n    }\n    // Container\n    if (is.defined(options.container)) {\n      if (is.string(options.container) && is.inArray(options.container, ['fs', 'zip'])) {\n        this.options.tileContainer = options.container;\n      } else {\n        throw is.invalidParameterError('container', 'one of: fs, zip', options.container);\n      }\n    }\n    // Layout\n    if (is.defined(options.layout)) {\n      if (is.string(options.layout) && is.inArray(options.layout, ['dz', 'google', 'iiif', 'iiif3', 'zoomify'])) {\n        this.options.tileLayout = options.layout;\n      } else {\n        throw is.invalidParameterError('layout', 'one of: dz, google, iiif, iiif3, zoomify', options.layout);\n      }\n    }\n    // Angle of rotation,\n    if (is.defined(options.angle)) {\n      if (is.integer(options.angle) && !(options.angle % 90)) {\n        this.options.tileAngle = options.angle;\n      } else {\n        throw is.invalidParameterError('angle', 'positive/negative multiple of 90', options.angle);\n      }\n    }\n    // Background colour\n    this._setBackgroundColourOption('tileBackground', options.background);\n    // Depth of tiles\n    if (is.defined(options.depth)) {\n      if (is.string(options.depth) && is.inArray(options.depth, ['onepixel', 'onetile', 'one'])) {\n        this.options.tileDepth = options.depth;\n      } else {\n        throw is.invalidParameterError('depth', 'one of: onepixel, onetile, one', options.depth);\n      }\n    }\n    // Threshold to skip blank tiles\n    if (is.defined(options.skipBlanks)) {\n      if (is.integer(options.skipBlanks) && is.inRange(options.skipBlanks, -1, 65535)) {\n        this.options.tileSkipBlanks = options.skipBlanks;\n      } else {\n        throw is.invalidParameterError('skipBlanks', 'integer between -1 and 255/65535', options.skipBlanks);\n      }\n    } else if (is.defined(options.layout) && options.layout === 'google') {\n      this.options.tileSkipBlanks = 5;\n    }\n    // Center image in tile\n    const centre = is.bool(options.center) ? options.center : options.centre;\n    if (is.defined(centre)) {\n      this._setBooleanOption('tileCentre', centre);\n    }\n    // @id attribute for IIIF layout\n    if (is.defined(options.id)) {\n      if (is.string(options.id)) {\n        this.options.tileId = options.id;\n      } else {\n        throw is.invalidParameterError('id', 'string', options.id);\n      }\n    }\n    // Basename for zip container\n    if (is.defined(options.basename)) {\n      if (is.string(options.basename)) {\n        this.options.tileBasename = options.basename;\n      } else {\n        throw is.invalidParameterError('basename', 'string', options.basename);\n      }\n    }\n  }\n  // Format\n  if (is.inArray(this.options.formatOut, ['jpeg', 'png', 'webp'])) {\n    this.options.tileFormat = this.options.formatOut;\n  } else if (this.options.formatOut !== 'input') {\n    throw is.invalidParameterError('format', 'one of: jpeg, png, webp', this.options.formatOut);\n  }\n  return this._updateFormatOut('dz');\n}\n\n/**\n * Set a timeout for processing, in seconds.\n * Use a value of zero to continue processing indefinitely, the default behaviour.\n *\n * The clock starts when libvips opens an input image for processing.\n * Time spent waiting for a libuv thread to become available is not included.\n *\n * @example\n * // Ensure processing takes no longer than 3 seconds\n * try {\n *   const data = await sharp(input)\n *     .blur(1000)\n *     .timeout({ seconds: 3 })\n *     .toBuffer();\n * } catch (err) {\n *   if (err.message.includes('timeout')) { ... }\n * }\n *\n * @since 0.29.2\n *\n * @param {Object} options\n * @param {number} options.seconds - Number of seconds after which processing will be stopped\n * @returns {Sharp}\n */\nfunction timeout (options) {\n  if (!is.plainObject(options)) {\n    throw is.invalidParameterError('options', 'object', options);\n  }\n  if (is.integer(options.seconds) && is.inRange(options.seconds, 0, 3600)) {\n    this.options.timeoutSeconds = options.seconds;\n  } else {\n    throw is.invalidParameterError('seconds', 'integer between 0 and 3600', options.seconds);\n  }\n  return this;\n}\n\n/**\n * Update the output format unless options.force is false,\n * in which case revert to input format.\n * @private\n * @param {string} formatOut\n * @param {Object} [options]\n * @param {boolean} [options.force=true] - force output format, otherwise attempt to use input format\n * @returns {Sharp}\n */\nfunction _updateFormatOut (formatOut, options) {\n  if (!(is.object(options) && options.force === false)) {\n    this.options.formatOut = formatOut;\n  }\n  return this;\n}\n\n/**\n * Update a boolean attribute of the this.options Object.\n * @private\n * @param {string} key\n * @param {boolean} val\n * @throws {Error} Invalid key\n */\nfunction _setBooleanOption (key, val) {\n  if (is.bool(val)) {\n    this.options[key] = val;\n  } else {\n    throw is.invalidParameterError(key, 'boolean', val);\n  }\n}\n\n/**\n * Called by a WriteableStream to notify us it is ready for data.\n * @private\n */\nfunction _read () {\n  if (!this.options.streamOut) {\n    this.options.streamOut = true;\n    const stack = Error();\n    this._pipeline(undefined, stack);\n  }\n}\n\n/**\n * Invoke the C++ image processing pipeline\n * Supports callback, stream and promise variants\n * @private\n */\nfunction _pipeline (callback, stack) {\n  if (typeof callback === 'function') {\n    // output=file/buffer\n    if (this._isStreamInput()) {\n      // output=file/buffer, input=stream\n      this.on('finish', () => {\n        this._flattenBufferIn();\n        sharp.pipeline(this.options, (err, data, info) => {\n          if (err) {\n            callback(is.nativeError(err, stack));\n          } else {\n            callback(null, data, info);\n          }\n        });\n      });\n    } else {\n      // output=file/buffer, input=file/buffer\n      sharp.pipeline(this.options, (err, data, info) => {\n        if (err) {\n          callback(is.nativeError(err, stack));\n        } else {\n          callback(null, data, info);\n        }\n      });\n    }\n    return this;\n  } else if (this.options.streamOut) {\n    // output=stream\n    if (this._isStreamInput()) {\n      // output=stream, input=stream\n      this.once('finish', () => {\n        this._flattenBufferIn();\n        sharp.pipeline(this.options, (err, data, info) => {\n          if (err) {\n            this.emit('error', is.nativeError(err, stack));\n          } else {\n            this.emit('info', info);\n            this.push(data);\n          }\n          this.push(null);\n          this.on('end', () => this.emit('close'));\n        });\n      });\n      if (this.streamInFinished) {\n        this.emit('finish');\n      }\n    } else {\n      // output=stream, input=file/buffer\n      sharp.pipeline(this.options, (err, data, info) => {\n        if (err) {\n          this.emit('error', is.nativeError(err, stack));\n        } else {\n          this.emit('info', info);\n          this.push(data);\n        }\n        this.push(null);\n        this.on('end', () => this.emit('close'));\n      });\n    }\n    return this;\n  } else {\n    // output=promise\n    if (this._isStreamInput()) {\n      // output=promise, input=stream\n      return new Promise((resolve, reject) => {\n        this.once('finish', () => {\n          this._flattenBufferIn();\n          sharp.pipeline(this.options, (err, data, info) => {\n            if (err) {\n              reject(is.nativeError(err, stack));\n            } else {\n              if (this.options.resolveWithObject) {\n                resolve({ data, info });\n              } else {\n                resolve(data);\n              }\n            }\n          });\n        });\n      });\n    } else {\n      // output=promise, input=file/buffer\n      return new Promise((resolve, reject) => {\n        sharp.pipeline(this.options, (err, data, info) => {\n          if (err) {\n            reject(is.nativeError(err, stack));\n          } else {\n            if (this.options.resolveWithObject) {\n              resolve({ data, info });\n            } else {\n              resolve(data);\n            }\n          }\n        });\n      });\n    }\n  }\n}\n\n/**\n * Decorate the Sharp prototype with output-related functions.\n * @module Sharp\n * @private\n */\nmodule.exports = (Sharp) => {\n  Object.assign(Sharp.prototype, {\n    // Public\n    toFile,\n    toBuffer,\n    keepExif,\n    withExif,\n    withExifMerge,\n    keepIccProfile,\n    withIccProfile,\n    keepXmp,\n    withXmp,\n    keepMetadata,\n    withMetadata,\n    toFormat,\n    jpeg,\n    jp2,\n    png,\n    webp,\n    tiff,\n    avif,\n    heif,\n    jxl,\n    gif,\n    raw,\n    tile,\n    timeout,\n    // Private\n    _updateFormatOut,\n    _setBooleanOption,\n    _read,\n    _pipeline\n  });\n};\n"
  },
  {
    "path": "lib/resize.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst is = require('./is');\n\n/**\n * Weighting to apply when using contain/cover fit.\n * @member\n * @private\n */\nconst gravity = {\n  center: 0,\n  centre: 0,\n  north: 1,\n  east: 2,\n  south: 3,\n  west: 4,\n  northeast: 5,\n  southeast: 6,\n  southwest: 7,\n  northwest: 8\n};\n\n/**\n * Position to apply when using contain/cover fit.\n * @member\n * @private\n */\nconst position = {\n  top: 1,\n  right: 2,\n  bottom: 3,\n  left: 4,\n  'right top': 5,\n  'right bottom': 6,\n  'left bottom': 7,\n  'left top': 8\n};\n\n/**\n * How to extend the image.\n * @member\n * @private\n */\nconst extendWith = {\n  background: 'background',\n  copy: 'copy',\n  repeat: 'repeat',\n  mirror: 'mirror'\n};\n\n/**\n * Strategies for automagic cover behaviour.\n * @member\n * @private\n */\nconst strategy = {\n  entropy: 16,\n  attention: 17\n};\n\n/**\n * Reduction kernels.\n * @member\n * @private\n */\nconst kernel = {\n  nearest: 'nearest',\n  linear: 'linear',\n  cubic: 'cubic',\n  mitchell: 'mitchell',\n  lanczos2: 'lanczos2',\n  lanczos3: 'lanczos3',\n  mks2013: 'mks2013',\n  mks2021: 'mks2021'\n};\n\n/**\n * Methods by which an image can be resized to fit the provided dimensions.\n * @member\n * @private\n */\nconst fit = {\n  contain: 'contain',\n  cover: 'cover',\n  fill: 'fill',\n  inside: 'inside',\n  outside: 'outside'\n};\n\n/**\n * Map external fit property to internal canvas property.\n * @member\n * @private\n */\nconst mapFitToCanvas = {\n  contain: 'embed',\n  cover: 'crop',\n  fill: 'ignore_aspect',\n  inside: 'max',\n  outside: 'min'\n};\n\n/**\n * @private\n */\nfunction isRotationExpected (options) {\n  return (options.angle % 360) !== 0 || options.rotationAngle !== 0;\n}\n\n/**\n * @private\n */\nfunction isResizeExpected (options) {\n  return options.width !== -1 || options.height !== -1;\n}\n\n/**\n * Resize image to `width`, `height` or `width x height`.\n *\n * When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are:\n * - `cover`: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit.\n * - `contain`: Preserving aspect ratio, contain within both provided dimensions using \"letterboxing\" where necessary.\n * - `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions.\n * - `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.\n * - `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.\n *\n * Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.\n *\n * <img alt=\"Examples of various values for the fit property when resizing\" width=\"100%\" style=\"aspect-ratio: 998/243\" src=\"/api-resize-fit.svg\">\n *\n * When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are:\n * - `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.\n * - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.\n * - `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.\n *\n * Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.\n *\n * The strategy-based approach initially resizes so one dimension is at its target length\n * then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.\n * - `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).\n * - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.\n *\n * Possible downsizing kernels are:\n * - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).\n * - `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function).\n * - `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).\n * - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).\n * - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.\n * - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).\n * - `mks2013`: Use a [Magic Kernel Sharp](https://johncostella.com/magic/mks.pdf) 2013 kernel, as adopted by Facebook.\n * - `mks2021`: Use a Magic Kernel Sharp 2021 kernel, with more accurate (reduced) sharpening than the 2013 version.\n *\n * When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.\n * Downsampling kernels without a matching upsampling interpolator map to `cubic`.\n *\n * Only one resize can occur per pipeline.\n * Previous calls to `resize` in the same pipeline will be ignored.\n *\n * @example\n * sharp(input)\n *   .resize({ width: 100 })\n *   .toBuffer()\n *   .then(data => {\n *     // 100 pixels wide, auto-scaled height\n *   });\n *\n * @example\n * sharp(input)\n *   .resize({ height: 100 })\n *   .toBuffer()\n *   .then(data => {\n *     // 100 pixels high, auto-scaled width\n *   });\n *\n * @example\n * sharp(input)\n *   .resize(200, 300, {\n *     kernel: sharp.kernel.nearest,\n *     fit: 'contain',\n *     position: 'right top',\n *     background: { r: 255, g: 255, b: 255, alpha: 0.5 }\n *   })\n *   .toFile('output.png')\n *   .then(() => {\n *     // output.png is a 200 pixels wide and 300 pixels high image\n *     // containing a nearest-neighbour scaled version\n *     // contained within the north-east corner of a semi-transparent white canvas\n *   });\n *\n * @example\n * const transformer = sharp()\n *   .resize({\n *     width: 200,\n *     height: 200,\n *     fit: sharp.fit.cover,\n *     position: sharp.strategy.entropy\n *   });\n * // Read image data from readableStream\n * // Write 200px square auto-cropped image data to writableStream\n * readableStream\n *   .pipe(transformer)\n *   .pipe(writableStream);\n *\n * @example\n * sharp(input)\n *   .resize(200, 200, {\n *     fit: sharp.fit.inside,\n *     withoutEnlargement: true\n *   })\n *   .toFormat('jpeg')\n *   .toBuffer()\n *   .then(function(outputBuffer) {\n *     // outputBuffer contains JPEG image data\n *     // no wider and no higher than 200 pixels\n *     // and no larger than the input image\n *   });\n *\n * @example\n * sharp(input)\n *   .resize(200, 200, {\n *     fit: sharp.fit.outside,\n *     withoutReduction: true\n *   })\n *   .toFormat('jpeg')\n *   .toBuffer()\n *   .then(function(outputBuffer) {\n *     // outputBuffer contains JPEG image data\n *     // of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio\n *     // and no smaller than the input image\n *   });\n *\n * @example\n * const scaleByHalf = await sharp(input)\n *   .metadata()\n *   .then(({ width }) => sharp(input)\n *     .resize(Math.round(width * 0.5))\n *     .toBuffer()\n *   );\n *\n * @param {number} [width] - How many pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.\n * @param {number} [height] - How many pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.\n * @param {Object} [options]\n * @param {number} [options.width] - An alternative means of specifying `width`. If both are present this takes priority.\n * @param {number} [options.height] - An alternative means of specifying `height`. If both are present this takes priority.\n * @param {String} [options.fit='cover'] - How the image should be resized/cropped to fit the target dimension(s), one of `cover`, `contain`, `fill`, `inside` or `outside`.\n * @param {String} [options.position='centre'] - A position, gravity or strategy to use when `fit` is `cover` or `contain`.\n * @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.\n * @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load.\n * @param {Boolean} [options.withoutEnlargement=false] - Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions.\n * @param {Boolean} [options.withoutReduction=false] - Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions.\n * @param {Boolean} [options.fastShrinkOnLoad=true] - Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction resize (widthOrOptions, height, options) {\n  if (isResizeExpected(this.options)) {\n    this.options.debuglog('ignoring previous resize options');\n  }\n  if (this.options.widthPost !== -1) {\n    this.options.debuglog('operation order will be: extract, resize, extract');\n  }\n  if (is.defined(widthOrOptions)) {\n    if (is.object(widthOrOptions) && !is.defined(options)) {\n      options = widthOrOptions;\n    } else if (is.integer(widthOrOptions) && widthOrOptions > 0) {\n      this.options.width = widthOrOptions;\n    } else {\n      throw is.invalidParameterError('width', 'positive integer', widthOrOptions);\n    }\n  } else {\n    this.options.width = -1;\n  }\n  if (is.defined(height)) {\n    if (is.integer(height) && height > 0) {\n      this.options.height = height;\n    } else {\n      throw is.invalidParameterError('height', 'positive integer', height);\n    }\n  } else {\n    this.options.height = -1;\n  }\n  if (is.object(options)) {\n    // Width\n    if (is.defined(options.width)) {\n      if (is.integer(options.width) && options.width > 0) {\n        this.options.width = options.width;\n      } else {\n        throw is.invalidParameterError('width', 'positive integer', options.width);\n      }\n    }\n    // Height\n    if (is.defined(options.height)) {\n      if (is.integer(options.height) && options.height > 0) {\n        this.options.height = options.height;\n      } else {\n        throw is.invalidParameterError('height', 'positive integer', options.height);\n      }\n    }\n    // Fit\n    if (is.defined(options.fit)) {\n      const canvas = mapFitToCanvas[options.fit];\n      if (is.string(canvas)) {\n        this.options.canvas = canvas;\n      } else {\n        throw is.invalidParameterError('fit', 'valid fit', options.fit);\n      }\n    }\n    // Position\n    if (is.defined(options.position)) {\n      const pos = is.integer(options.position)\n        ? options.position\n        : strategy[options.position] || position[options.position] || gravity[options.position];\n      if (is.integer(pos) && (is.inRange(pos, 0, 8) || is.inRange(pos, 16, 17))) {\n        this.options.position = pos;\n      } else {\n        throw is.invalidParameterError('position', 'valid position/gravity/strategy', options.position);\n      }\n    }\n    // Background\n    this._setBackgroundColourOption('resizeBackground', options.background);\n    // Kernel\n    if (is.defined(options.kernel)) {\n      if (is.string(kernel[options.kernel])) {\n        this.options.kernel = kernel[options.kernel];\n      } else {\n        throw is.invalidParameterError('kernel', 'valid kernel name', options.kernel);\n      }\n    }\n    // Without enlargement\n    if (is.defined(options.withoutEnlargement)) {\n      this._setBooleanOption('withoutEnlargement', options.withoutEnlargement);\n    }\n    // Without reduction\n    if (is.defined(options.withoutReduction)) {\n      this._setBooleanOption('withoutReduction', options.withoutReduction);\n    }\n    // Shrink on load\n    if (is.defined(options.fastShrinkOnLoad)) {\n      this._setBooleanOption('fastShrinkOnLoad', options.fastShrinkOnLoad);\n    }\n  }\n  if (isRotationExpected(this.options) && isResizeExpected(this.options)) {\n    this.options.rotateBefore = true;\n  }\n  return this;\n}\n\n/**\n * Extend / pad / extrude one or more edges of the image with either\n * the provided background colour or pixels derived from the image.\n * This operation will always occur after resizing and extraction, if any.\n *\n * @example\n * // Resize to 140 pixels wide, then add 10 transparent pixels\n * // to the top, left and right edges and 20 to the bottom edge\n * sharp(input)\n *   .resize(140)\n *   .extend({\n *     top: 10,\n *     bottom: 20,\n *     left: 10,\n *     right: 10,\n *     background: { r: 0, g: 0, b: 0, alpha: 0 }\n *   })\n *   ...\n *\n* @example\n * // Add a row of 10 red pixels to the bottom\n * sharp(input)\n *   .extend({\n *     bottom: 10,\n *     background: 'red'\n *   })\n *   ...\n *\n * @example\n * // Extrude image by 8 pixels to the right, mirroring existing right hand edge\n * sharp(input)\n *   .extend({\n *     right: 8,\n *     background: 'mirror'\n *   })\n *   ...\n *\n * @param {(number|Object)} extend - single pixel count to add to all edges or an Object with per-edge counts\n * @param {number} [extend.top=0]\n * @param {number} [extend.left=0]\n * @param {number} [extend.bottom=0]\n * @param {number} [extend.right=0]\n * @param {String} [extend.extendWith='background'] - populate new pixels using this method, one of: background, copy, repeat, mirror.\n * @param {String|Object} [extend.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n*/\nfunction extend (extend) {\n  if (is.integer(extend) && extend > 0) {\n    this.options.extendTop = extend;\n    this.options.extendBottom = extend;\n    this.options.extendLeft = extend;\n    this.options.extendRight = extend;\n  } else if (is.object(extend)) {\n    if (is.defined(extend.top)) {\n      if (is.integer(extend.top) && extend.top >= 0) {\n        this.options.extendTop = extend.top;\n      } else {\n        throw is.invalidParameterError('top', 'positive integer', extend.top);\n      }\n    }\n    if (is.defined(extend.bottom)) {\n      if (is.integer(extend.bottom) && extend.bottom >= 0) {\n        this.options.extendBottom = extend.bottom;\n      } else {\n        throw is.invalidParameterError('bottom', 'positive integer', extend.bottom);\n      }\n    }\n    if (is.defined(extend.left)) {\n      if (is.integer(extend.left) && extend.left >= 0) {\n        this.options.extendLeft = extend.left;\n      } else {\n        throw is.invalidParameterError('left', 'positive integer', extend.left);\n      }\n    }\n    if (is.defined(extend.right)) {\n      if (is.integer(extend.right) && extend.right >= 0) {\n        this.options.extendRight = extend.right;\n      } else {\n        throw is.invalidParameterError('right', 'positive integer', extend.right);\n      }\n    }\n    this._setBackgroundColourOption('extendBackground', extend.background);\n    if (is.defined(extend.extendWith)) {\n      if (is.string(extendWith[extend.extendWith])) {\n        this.options.extendWith = extendWith[extend.extendWith];\n      } else {\n        throw is.invalidParameterError('extendWith', 'one of: background, copy, repeat, mirror', extend.extendWith);\n      }\n    }\n  } else {\n    throw is.invalidParameterError('extend', 'integer or object', extend);\n  }\n  return this;\n}\n\n/**\n * Extract/crop a region of the image.\n *\n * - Use `extract` before `resize` for pre-resize extraction.\n * - Use `extract` after `resize` for post-resize extraction.\n * - Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order.\n *\n * @example\n * sharp(input)\n *   .extract({ left: left, top: top, width: width, height: height })\n *   .toFile(output, function(err) {\n *     // Extract a region of the input image, saving in the same format.\n *   });\n * @example\n * sharp(input)\n *   .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre })\n *   .resize(width, height)\n *   .extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost })\n *   .toFile(output, function(err) {\n *     // Extract a region, resize, then extract from the resized image\n *   });\n *\n * @param {Object} options - describes the region to extract using integral pixel values\n * @param {number} options.left - zero-indexed offset from left edge\n * @param {number} options.top - zero-indexed offset from top edge\n * @param {number} options.width - width of region to extract\n * @param {number} options.height - height of region to extract\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction extract (options) {\n  const suffix = isResizeExpected(this.options) || this.options.widthPre !== -1 ? 'Post' : 'Pre';\n  if (this.options[`width${suffix}`] !== -1) {\n    this.options.debuglog('ignoring previous extract options');\n  }\n  ['left', 'top', 'width', 'height'].forEach(function (name) {\n    const value = options[name];\n    if (is.integer(value) && value >= 0) {\n      this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value;\n    } else {\n      throw is.invalidParameterError(name, 'integer', value);\n    }\n  }, this);\n  // Ensure existing rotation occurs before pre-resize extraction\n  if (isRotationExpected(this.options) && !isResizeExpected(this.options)) {\n    if (this.options.widthPre === -1 || this.options.widthPost === -1) {\n      this.options.rotateBefore = true;\n    }\n  }\n  if (this.options.input.autoOrient) {\n    this.options.orientBefore = true;\n  }\n  return this;\n}\n\n/**\n * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.\n *\n * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.\n *\n * If the result of this operation would trim an image to nothing then no change is made.\n *\n * The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties.\n *\n * @example\n * // Trim pixels with a colour similar to that of the top-left pixel.\n * await sharp(input)\n *   .trim()\n *   .toFile(output);\n *\n * @example\n * // Trim pixels with the exact same colour as that of the top-left pixel.\n * await sharp(input)\n *   .trim({\n *     threshold: 0\n *   })\n *   .toFile(output);\n *\n * @example\n * // Assume input is line art and trim only pixels with a similar colour to red.\n * const output = await sharp(input)\n *   .trim({\n *     background: \"#FF0000\",\n *     lineArt: true\n *   })\n *   .toBuffer();\n *\n * @example\n * // Trim all \"yellow-ish\" pixels, being more lenient with the higher threshold.\n * const output = await sharp(input)\n *   .trim({\n *     background: \"yellow\",\n *     threshold: 42,\n *   })\n *   .toBuffer();\n *\n * @param {Object} [options]\n * @param {string|Object} [options.background='top-left pixel'] - Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel.\n * @param {number} [options.threshold=10] - Allowed difference from the above colour, a positive number.\n * @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic?\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction trim (options) {\n  this.options.trimThreshold = 10;\n  if (is.defined(options)) {\n    if (is.object(options)) {\n      if (is.defined(options.background)) {\n        this._setBackgroundColourOption('trimBackground', options.background);\n      }\n      if (is.defined(options.threshold)) {\n        if (is.number(options.threshold) && options.threshold >= 0) {\n          this.options.trimThreshold = options.threshold;\n        } else {\n          throw is.invalidParameterError('threshold', 'positive number', options.threshold);\n        }\n      }\n      if (is.defined(options.lineArt)) {\n        this._setBooleanOption('trimLineArt', options.lineArt);\n      }\n    } else {\n      throw is.invalidParameterError('trim', 'object', options);\n    }\n  }\n  if (isRotationExpected(this.options)) {\n    this.options.rotateBefore = true;\n  }\n  return this;\n}\n\n/**\n * Decorate the Sharp prototype with resize-related functions.\n * @module Sharp\n * @private\n */\nmodule.exports = (Sharp) => {\n  Object.assign(Sharp.prototype, {\n    resize,\n    extend,\n    extract,\n    trim\n  });\n  // Class attributes\n  Sharp.gravity = gravity;\n  Sharp.strategy = strategy;\n  Sharp.kernel = kernel;\n  Sharp.fit = fit;\n  Sharp.position = position;\n};\n"
  },
  {
    "path": "lib/sharp.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n// Inspects the runtime environment and exports the relevant sharp.node binary\n\nconst { familySync, versionSync } = require('detect-libc');\n\nconst { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips');\nconst runtimePlatform = runtimePlatformArch();\n\nconst paths = [\n  `../src/build/Release/sharp-${runtimePlatform}.node`,\n  '../src/build/Release/sharp-wasm32.node',\n  `@img/sharp-${runtimePlatform}/sharp.node`,\n  '@img/sharp-wasm32/sharp.node'\n];\n\n/* node:coverage disable */\n\nlet path, sharp;\nconst errors = [];\nfor (path of paths) {\n  try {\n    sharp = require(path);\n    break;\n  } catch (err) {\n    errors.push(err);\n  }\n}\n\nif (sharp && path.startsWith('@img/sharp-linux-x64') && !sharp._isUsingX64V2()) {\n  const err = new Error('Prebuilt binaries for linux-x64 require v2 microarchitecture');\n  err.code = 'Unsupported CPU';\n  errors.push(err);\n  sharp = null;\n}\n\nif (sharp) {\n  module.exports = sharp;\n} else {\n  const [isLinux, isMacOs, isWindows] = ['linux', 'darwin', 'win32'].map(os => runtimePlatform.startsWith(os));\n\n  const help = [`Could not load the \"sharp\" module using the ${runtimePlatform} runtime`];\n  errors.forEach(err => {\n    if (err.code !== 'MODULE_NOT_FOUND') {\n      help.push(`${err.code}: ${err.message}`);\n    }\n  });\n  const messages = errors.map(err => err.message).join(' ');\n  help.push('Possible solutions:');\n  // Common error messages\n  if (isUnsupportedNodeRuntime()) {\n    const { found, expected } = isUnsupportedNodeRuntime();\n    help.push(\n      '- Please upgrade Node.js:',\n      `    Found ${found}`,\n      `    Requires ${expected}`\n    );\n  } else if (prebuiltPlatforms.includes(runtimePlatform)) {\n    const [os, cpu] = runtimePlatform.split('-');\n    const libc = os.endsWith('musl') ? ' --libc=musl' : '';\n    help.push(\n      '- Ensure optional dependencies can be installed:',\n      '    npm install --include=optional sharp',\n      '- Ensure your package manager supports multi-platform installation:',\n      '    See https://sharp.pixelplumbing.com/install#cross-platform',\n      '- Add platform-specific dependencies:',\n      `    npm install --os=${os.replace('musl', '')}${libc} --cpu=${cpu} sharp`\n    );\n  } else {\n    help.push(\n      `- Manually install libvips >= ${minimumLibvipsVersion}`,\n      '- Add experimental WebAssembly-based dependencies:',\n      '    npm install --cpu=wasm32 sharp',\n      '    npm install @img/sharp-wasm32'\n    );\n  }\n  if (isLinux && /(symbol not found|CXXABI_)/i.test(messages)) {\n    try {\n      const { config } = require(`@img/sharp-libvips-${runtimePlatform}/package`);\n      const libcFound = `${familySync()} ${versionSync()}`;\n      const libcRequires = `${config.musl ? 'musl' : 'glibc'} ${config.musl || config.glibc}`;\n      help.push(\n        '- Update your OS:',\n        `    Found ${libcFound}`,\n        `    Requires ${libcRequires}`\n      );\n    } catch (_errEngines) {}\n  }\n  if (isLinux && /\\/snap\\/core[0-9]{2}/.test(messages)) {\n    help.push(\n      '- Remove the Node.js Snap, which does not support native modules',\n      '    snap remove node'\n    );\n  }\n  if (isMacOs && /Incompatible library version/.test(messages)) {\n    help.push(\n      '- Update Homebrew:',\n      '    brew update && brew upgrade vips'\n    );\n  }\n  if (errors.some(err => err.code === 'ERR_DLOPEN_DISABLED')) {\n    help.push('- Run Node.js without using the --no-addons flag');\n  }\n  // Link to installation docs\n  if (isWindows && /The specified procedure could not be found/.test(messages)) {\n    help.push(\n      '- Using the canvas package on Windows?',\n      '    See https://sharp.pixelplumbing.com/install#canvas-and-windows',\n      '- Check for outdated versions of sharp in the dependency tree:',\n      '    npm ls sharp'\n    );\n  }\n  help.push(\n    '- Consult the installation documentation:',\n    '    See https://sharp.pixelplumbing.com/install'\n  );\n  throw new Error(help.join('\\n'));\n}\n"
  },
  {
    "path": "lib/utility.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst events = require('node:events');\nconst detectLibc = require('detect-libc');\n\nconst is = require('./is');\nconst { runtimePlatformArch } = require('./libvips');\nconst sharp = require('./sharp');\n\nconst runtimePlatform = runtimePlatformArch();\nconst libvipsVersion = sharp.libvipsVersion();\n\n/**\n * An Object containing nested boolean values representing the available input and output formats/methods.\n * @member\n * @example\n * console.log(sharp.format);\n * @returns {Object}\n */\nconst format = sharp.format();\nformat.heif.output.alias = ['avif', 'heic'];\nformat.jpeg.output.alias = ['jpe', 'jpg'];\nformat.tiff.output.alias = ['tif'];\nformat.jp2k.output.alias = ['j2c', 'j2k', 'jp2', 'jpx'];\n\n/**\n * An Object containing the available interpolators and their proper values\n * @readonly\n * @enum {string}\n */\nconst interpolators = {\n  /** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */\n  nearest: 'nearest',\n  /** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */\n  bilinear: 'bilinear',\n  /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */\n  bicubic: 'bicubic',\n  /** [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some \"[acutance](http://en.wikipedia.org/wiki/Acutance)\" but typically reduces performance by a factor of 2. */\n  locallyBoundedBicubic: 'lbb',\n  /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */\n  nohalo: 'nohalo',\n  /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents \"staircasing\" when enlarging. */\n  vertexSplitQuadraticBasisSpline: 'vsqbs'\n};\n\n/**\n * An Object containing the version numbers of sharp, libvips\n * and (when using prebuilt binaries) its dependencies.\n *\n * @member\n * @example\n * console.log(sharp.versions);\n */\nlet versions = {\n  vips: libvipsVersion.semver\n};\n/* node:coverage ignore next 15 */\nif (!libvipsVersion.isGlobal) {\n  if (!libvipsVersion.isWasm) {\n    try {\n      versions = require(`@img/sharp-${runtimePlatform}/versions`);\n    } catch (_) {\n      try {\n        versions = require(`@img/sharp-libvips-${runtimePlatform}/versions`);\n      } catch (_) {}\n    }\n  } else {\n    try {\n      versions = require('@img/sharp-wasm32/versions');\n    } catch (_) {}\n  }\n}\nversions.sharp = require('../package.json').version;\n\n/* node:coverage ignore next 5 */\nif (versions.heif && format.heif) {\n  // Prebuilt binaries provide AV1\n  format.heif.input.fileSuffix = ['.avif'];\n  format.heif.output.alias = ['avif'];\n}\n\n/**\n * Gets or, when options are provided, sets the limits of _libvips'_ operation cache.\n * Existing entries in the cache will be trimmed after any change in limits.\n * This method always returns cache statistics,\n * useful for determining how much working memory is required for a particular task.\n *\n * @example\n * const stats = sharp.cache();\n * @example\n * sharp.cache( { items: 200 } );\n * sharp.cache( { files: 0 } );\n * sharp.cache(false);\n *\n * @param {Object|boolean} [options=true] - Object with the following attributes, or boolean where true uses default cache settings and false removes all caching\n * @param {number} [options.memory=50] - is the maximum memory in MB to use for this cache\n * @param {number} [options.files=20] - is the maximum number of files to hold open\n * @param {number} [options.items=100] - is the maximum number of operations to cache\n * @returns {Object}\n */\nfunction cache (options) {\n  if (is.bool(options)) {\n    if (options) {\n      // Default cache settings of 50MB, 20 files, 100 items\n      return sharp.cache(50, 20, 100);\n    } else {\n      return sharp.cache(0, 0, 0);\n    }\n  } else if (is.object(options)) {\n    return sharp.cache(options.memory, options.files, options.items);\n  } else {\n    return sharp.cache();\n  }\n}\ncache(true);\n\n/**\n * Gets or, when a concurrency is provided, sets\n * the maximum number of threads _libvips_ should use to process _each image_.\n * These are from a thread pool managed by glib,\n * which helps avoid the overhead of creating new threads.\n *\n * This method always returns the current concurrency.\n *\n * The default value is the number of CPU cores,\n * except when using glibc-based Linux without jemalloc,\n * where the default is `1` to help reduce memory fragmentation.\n *\n * A value of `0` will reset this to the number of CPU cores.\n *\n * Some image format libraries spawn additional threads,\n * e.g. libaom manages its own 4 threads when encoding AVIF images,\n * and these are independent of the value set here.\n *\n * :::note\n * Further {@link /performance/ control over performance} is available.\n * :::\n *\n * @example\n * const threads = sharp.concurrency(); // 4\n * sharp.concurrency(2); // 2\n * sharp.concurrency(0); // 4\n *\n * @param {number} [concurrency]\n * @returns {number} concurrency\n */\nfunction concurrency (concurrency) {\n  return sharp.concurrency(is.integer(concurrency) ? concurrency : null);\n}\n/* node:coverage ignore next 7 */\nif (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) {\n  // Reduce default concurrency to 1 when using glibc memory allocator\n  sharp.concurrency(1);\n} else if (detectLibc.familySync() === detectLibc.MUSL && sharp.concurrency() === 1024) {\n  // Reduce default concurrency when musl thread over-subscription detected\n  sharp.concurrency(require('node:os').availableParallelism());\n}\n\n/**\n * An EventEmitter that emits a `change` event when a task is either:\n * - queued, waiting for _libuv_ to provide a worker thread\n * - complete\n * @member\n * @example\n * sharp.queue.on('change', function(queueLength) {\n *   console.log('Queue contains ' + queueLength + ' task(s)');\n * });\n */\nconst queue = new events.EventEmitter();\n\n/**\n * Provides access to internal task counters.\n * - queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool.\n * - process is the number of resize tasks currently being processed.\n *\n * @example\n * const counters = sharp.counters(); // { queue: 2, process: 4 }\n *\n * @returns {Object}\n */\nfunction counters () {\n  return sharp.counters();\n}\n\n/**\n * Get and set use of SIMD vector unit instructions.\n * Requires libvips to have been compiled with highway support.\n *\n * Improves the performance of `resize`, `blur` and `sharpen` operations\n * by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.\n *\n * @example\n * const simd = sharp.simd();\n * // simd is `true` if the runtime use of highway is currently enabled\n * @example\n * const simd = sharp.simd(false);\n * // prevent libvips from using highway at runtime\n *\n * @param {boolean} [simd=true]\n * @returns {boolean}\n */\nfunction simd (simd) {\n  return sharp.simd(is.bool(simd) ? simd : null);\n}\n\n/**\n * Block libvips operations at runtime.\n *\n * This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable,\n * which when set will block all \"untrusted\" operations.\n *\n * @since 0.32.4\n *\n * @example <caption>Block all TIFF input.</caption>\n * sharp.block({\n *   operation: ['VipsForeignLoadTiff']\n * });\n *\n * @param {Object} options\n * @param {Array<string>} options.operation - List of libvips low-level operation names to block.\n */\nfunction block (options) {\n  if (is.object(options)) {\n    if (Array.isArray(options.operation) && options.operation.every(is.string)) {\n      sharp.block(options.operation, true);\n    } else {\n      throw is.invalidParameterError('operation', 'Array<string>', options.operation);\n    }\n  } else {\n    throw is.invalidParameterError('options', 'object', options);\n  }\n}\n\n/**\n * Unblock libvips operations at runtime.\n *\n * This is useful for defining a list of allowed operations.\n *\n * @since 0.32.4\n *\n * @example <caption>Block all input except WebP from the filesystem.</caption>\n * sharp.block({\n *   operation: ['VipsForeignLoad']\n * });\n * sharp.unblock({\n *   operation: ['VipsForeignLoadWebpFile']\n * });\n *\n * @example <caption>Block all input except JPEG and PNG from a Buffer or Stream.</caption>\n * sharp.block({\n *   operation: ['VipsForeignLoad']\n * });\n * sharp.unblock({\n *   operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer']\n * });\n *\n * @param {Object} options\n * @param {Array<string>} options.operation - List of libvips low-level operation names to unblock.\n */\nfunction unblock (options) {\n  if (is.object(options)) {\n    if (Array.isArray(options.operation) && options.operation.every(is.string)) {\n      sharp.block(options.operation, false);\n    } else {\n      throw is.invalidParameterError('operation', 'Array<string>', options.operation);\n    }\n  } else {\n    throw is.invalidParameterError('options', 'object', options);\n  }\n}\n\n/**\n * Decorate the Sharp class with utility-related functions.\n * @module Sharp\n * @private\n */\nmodule.exports = (Sharp) => {\n  Sharp.cache = cache;\n  Sharp.concurrency = concurrency;\n  Sharp.counters = counters;\n  Sharp.simd = simd;\n  Sharp.format = format;\n  Sharp.interpolators = interpolators;\n  Sharp.versions = versions;\n  Sharp.queue = queue;\n  Sharp.block = block;\n  Sharp.unblock = unblock;\n};\n"
  },
  {
    "path": "npm/darwin-arm64/package.json",
    "content": "{\n  \"name\": \"@img/sharp-darwin-arm64\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with macOS 64-bit ARM\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/darwin-arm64\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"optionalDependencies\": {\n    \"@img/sharp-libvips-darwin-arm64\": \"1.2.4\"\n  },\n  \"files\": [\n    \"lib\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-darwin-arm64.node\",\n    \"./package\": \"./package.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"os\": [\n    \"darwin\"\n  ],\n  \"cpu\": [\n    \"arm64\"\n  ]\n}\n"
  },
  {
    "path": "npm/darwin-x64/package.json",
    "content": "{\n  \"name\": \"@img/sharp-darwin-x64\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with macOS x64\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/darwin-x64\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"optionalDependencies\": {\n    \"@img/sharp-libvips-darwin-x64\": \"1.2.4\"\n  },\n  \"files\": [\n    \"lib\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-darwin-x64.node\",\n    \"./package\": \"./package.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"os\": [\n    \"darwin\"\n  ],\n  \"cpu\": [\n    \"x64\"\n  ]\n}\n"
  },
  {
    "path": "npm/from-local-build.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n// Populate the npm package for the current platform with the local build\n\nconst { copyFileSync, cpSync, readFileSync, writeFileSync, appendFileSync } = require('node:fs');\nconst { basename, join } = require('node:path');\n\nconst { buildPlatformArch } = require('../lib/libvips');\n\nconst licensing = `\n## Licensing\n\nCopyright 2013 Lovell Fuller and others.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n`;\n\nconst platform = buildPlatformArch();\nconst destDir = join(__dirname, platform);\nconsole.log(`Populating npm package for platform: ${platform}`);\n\n// Copy binaries\nconst releaseDir = join(__dirname, '..', 'src', 'build', 'Release');\nconst libDir = join(destDir, 'lib');\ncpSync(releaseDir, libDir, {\n  recursive: true,\n  filter: (file) => {\n    const name = basename(file);\n    return name === 'Release' ||\n      (name.startsWith('sharp-') && name.includes('.node')) ||\n      (name.startsWith('libvips-') && name.endsWith('.dll'));\n  }\n});\n\n// Generate README\nconst { name, description } = require(`./${platform}/package.json`);\nwriteFileSync(join(destDir, 'README.md'), `# \\`${name}\\`\\n\\n${description}.\\n${licensing}`);\n\n// Copy Apache-2.0 LICENSE\ncopyFileSync(join(__dirname, '..', 'LICENSE'), join(destDir, 'LICENSE'));\n\n// Copy files for packages without an explicit sharp-libvips dependency (Windows, wasm)\nif (platform.startsWith('win') || platform.startsWith('wasm')) {\n  const libvipsPlatform = platform === 'wasm32' ? 'dev-wasm32' : platform;\n  const sharpLibvipsDir = join(require(`@img/sharp-libvips-${libvipsPlatform}/lib`), '..');\n  // Copy versions.json\n  copyFileSync(join(sharpLibvipsDir, 'versions.json'), join(destDir, 'versions.json'));\n  // Append third party licensing to README\n  const readme = readFileSync(join(sharpLibvipsDir, 'README.md'), { encoding: 'utf-8' });\n  const thirdParty = readme.substring(readme.indexOf('\\nThis software contains'));\n  appendFileSync(join(destDir, 'README.md'), thirdParty);\n}\n"
  },
  {
    "path": "npm/linux-arm/package.json",
    "content": "{\n  \"name\": \"@img/sharp-linux-arm\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with Linux (glibc) ARM (32-bit)\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/linux-arm\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"optionalDependencies\": {\n    \"@img/sharp-libvips-linux-arm\": \"1.2.4\"\n  },\n  \"files\": [\n    \"lib\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-linux-arm.node\",\n    \"./package\": \"./package.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"config\": {\n    \"glibc\": \">=2.31\"\n  },\n  \"os\": [\n    \"linux\"\n  ],\n  \"libc\": [\n    \"glibc\"\n  ],\n  \"cpu\": [\n    \"arm\"\n  ]\n}\n"
  },
  {
    "path": "npm/linux-arm64/package.json",
    "content": "{\n  \"name\": \"@img/sharp-linux-arm64\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with Linux (glibc) 64-bit ARM\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/linux-arm64\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"optionalDependencies\": {\n    \"@img/sharp-libvips-linux-arm64\": \"1.2.4\"\n  },\n  \"files\": [\n    \"lib\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-linux-arm64.node\",\n    \"./package\": \"./package.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"config\": {\n    \"glibc\": \">=2.26\"\n  },\n  \"os\": [\n    \"linux\"\n  ],\n  \"libc\": [\n    \"glibc\"\n  ],\n  \"cpu\": [\n    \"arm64\"\n  ]\n}\n"
  },
  {
    "path": "npm/linux-ppc64/package.json",
    "content": "{\n  \"name\": \"@img/sharp-linux-ppc64\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with Linux (glibc) ppc64\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/linux-ppc64\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"optionalDependencies\": {\n    \"@img/sharp-libvips-linux-ppc64\": \"1.2.4\"\n  },\n  \"files\": [\n    \"lib\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-linux-ppc64.node\",\n    \"./package\": \"./package.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"config\": {\n    \"glibc\": \">=2.36\"\n  },\n  \"os\": [\n    \"linux\"\n  ],\n  \"libc\": [\n    \"glibc\"\n  ],\n  \"cpu\": [\n    \"ppc64\"\n  ]\n}\n"
  },
  {
    "path": "npm/linux-riscv64/package.json",
    "content": "{\n  \"name\": \"@img/sharp-linux-riscv64\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with Linux (glibc) RISC-V 64-bit\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/linux-riscv64\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"optionalDependencies\": {\n    \"@img/sharp-libvips-linux-riscv64\": \"1.2.4\"\n  },\n  \"files\": [\n    \"lib\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-linux-riscv64.node\",\n    \"./package\": \"./package.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"config\": {\n    \"glibc\": \">=2.41\"\n  },\n  \"os\": [\n    \"linux\"\n  ],\n  \"libc\": [\n    \"glibc\"\n  ],\n  \"cpu\": [\n    \"riscv64\"\n  ]\n}\n"
  },
  {
    "path": "npm/linux-s390x/package.json",
    "content": "{\n  \"name\": \"@img/sharp-linux-s390x\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with Linux (glibc) s390x\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/linux-s390x\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"optionalDependencies\": {\n    \"@img/sharp-libvips-linux-s390x\": \"1.2.4\"\n  },\n  \"files\": [\n    \"lib\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-linux-s390x.node\",\n    \"./package\": \"./package.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"config\": {\n    \"glibc\": \">=2.36\"\n  },\n  \"os\": [\n    \"linux\"\n  ],\n  \"libc\": [\n    \"glibc\"\n  ],\n  \"cpu\": [\n    \"s390x\"\n  ]\n}\n"
  },
  {
    "path": "npm/linux-x64/package.json",
    "content": "{\n  \"name\": \"@img/sharp-linux-x64\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with Linux (glibc) x64\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/linux-x64\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"optionalDependencies\": {\n    \"@img/sharp-libvips-linux-x64\": \"1.2.4\"\n  },\n  \"files\": [\n    \"lib\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-linux-x64.node\",\n    \"./package\": \"./package.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"config\": {\n    \"glibc\": \">=2.26\"\n  },\n  \"os\": [\n    \"linux\"\n  ],\n  \"libc\": [\n    \"glibc\"\n  ],\n  \"cpu\": [\n    \"x64\"\n  ]\n}\n"
  },
  {
    "path": "npm/linuxmusl-arm64/package.json",
    "content": "{\n  \"name\": \"@img/sharp-linuxmusl-arm64\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with Linux (musl) 64-bit ARM\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/linuxmusl-arm64\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"optionalDependencies\": {\n    \"@img/sharp-libvips-linuxmusl-arm64\": \"1.2.4\"\n  },\n  \"files\": [\n    \"lib\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-linuxmusl-arm64.node\",\n    \"./package\": \"./package.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"config\": {\n    \"musl\": \">=1.2.2\"\n  },\n  \"os\": [\n    \"linux\"\n  ],\n  \"libc\": [\n    \"musl\"\n  ],\n  \"cpu\": [\n    \"arm64\"\n  ]\n}\n"
  },
  {
    "path": "npm/linuxmusl-x64/package.json",
    "content": "{\n  \"name\": \"@img/sharp-linuxmusl-x64\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with Linux (musl) x64\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/linuxmusl-x64\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"optionalDependencies\": {\n    \"@img/sharp-libvips-linuxmusl-x64\": \"1.2.4\"\n  },\n  \"files\": [\n    \"lib\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-linuxmusl-x64.node\",\n    \"./package\": \"./package.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"config\": {\n    \"musl\": \">=1.2.2\"\n  },\n  \"os\": [\n    \"linux\"\n  ],\n  \"libc\": [\n    \"musl\"\n  ],\n  \"cpu\": [\n    \"x64\"\n  ]\n}\n"
  },
  {
    "path": "npm/package.json",
    "content": "{\n  \"name\": \"@img/sharp\",\n  \"version\": \"0.34.5\",\n  \"private\": \"true\",\n  \"workspaces\": [\n    \"darwin-arm64\",\n    \"darwin-x64\",\n    \"linux-arm\",\n    \"linux-arm64\",\n    \"linux-ppc64\",\n    \"linux-riscv64\",\n    \"linux-s390x\",\n    \"linux-x64\",\n    \"linuxmusl-arm64\",\n    \"linuxmusl-x64\",\n    \"wasm32\",\n    \"win32-arm64\",\n    \"win32-ia32\",\n    \"win32-x64\"\n  ]\n}\n"
  },
  {
    "path": "npm/release-notes.js",
    "content": "const { readFileSync, writeFileSync } = require('node:fs');\n\nconst { version } = require('./package.json');\nconst versionWithoutPreRelease = version.replace(/-rc\\.\\d+$/, '');\n\nconst markdown = readFileSync(`./docs/src/content/docs/changelog/v${versionWithoutPreRelease}.md`, 'utf8');\nconst markdownWithoutFrontmatter = markdown.replace(/---\\n.*?\\n---\\n+/s, '');\n\nwriteFileSync('./release-notes.md', markdownWithoutFrontmatter);\n"
  },
  {
    "path": "npm/wasm32/package.json",
    "content": "{\n  \"name\": \"@img/sharp-wasm32\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with wasm32\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/wasm32\"\n  },\n  \"license\": \"Apache-2.0 AND LGPL-3.0-or-later AND MIT\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"files\": [\n    \"lib\",\n    \"versions.json\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-wasm32.node.js\",\n    \"./package\": \"./package.json\",\n    \"./versions\": \"./versions.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"dependencies\": {\n    \"@emnapi/runtime\": \"^1.7.0\"\n  },\n  \"cpu\": [\n    \"wasm32\"\n  ]\n}\n"
  },
  {
    "path": "npm/win32-arm64/package.json",
    "content": "{\n  \"name\": \"@img/sharp-win32-arm64\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with Windows 64-bit ARM\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/win32-arm64\"\n  },\n  \"license\": \"Apache-2.0 AND LGPL-3.0-or-later\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"files\": [\n    \"lib\",\n    \"versions.json\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-win32-arm64.node\",\n    \"./package\": \"./package.json\",\n    \"./versions\": \"./versions.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"os\": [\n    \"win32\"\n  ],\n  \"cpu\": [\n    \"arm64\"\n  ]\n}\n"
  },
  {
    "path": "npm/win32-ia32/package.json",
    "content": "{\n  \"name\": \"@img/sharp-win32-ia32\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with Windows x86 (32-bit)\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/win32-ia32\"\n  },\n  \"license\": \"Apache-2.0 AND LGPL-3.0-or-later\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"files\": [\n    \"lib\",\n    \"versions.json\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-win32-ia32.node\",\n    \"./package\": \"./package.json\",\n    \"./versions\": \"./versions.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"os\": [\n    \"win32\"\n  ],\n  \"cpu\": [\n    \"ia32\"\n  ]\n}\n"
  },
  {
    "path": "npm/win32-x64/package.json",
    "content": "{\n  \"name\": \"@img/sharp-win32-x64\",\n  \"version\": \"0.34.5\",\n  \"description\": \"Prebuilt sharp for use with Windows x64\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/lovell/sharp.git\",\n    \"directory\": \"npm/win32-x64\"\n  },\n  \"license\": \"Apache-2.0 AND LGPL-3.0-or-later\",\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  },\n  \"preferUnplugged\": true,\n  \"files\": [\n    \"lib\",\n    \"versions.json\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"type\": \"commonjs\",\n  \"exports\": {\n    \"./sharp.node\": \"./lib/sharp-win32-x64.node\",\n    \"./package\": \"./package.json\",\n    \"./versions\": \"./versions.json\"\n  },\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"os\": [\n    \"win32\"\n  ],\n  \"cpu\": [\n    \"x64\"\n  ]\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"sharp\",\n  \"description\": \"High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images\",\n  \"version\": \"0.34.5\",\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"homepage\": \"https://sharp.pixelplumbing.com\",\n  \"contributors\": [\n    \"Pierre Inglebert <pierre.inglebert@gmail.com>\",\n    \"Jonathan Ong <jonathanrichardong@gmail.com>\",\n    \"Chanon Sajjamanochai <chanon.s@gmail.com>\",\n    \"Juliano Julio <julianojulio@gmail.com>\",\n    \"Daniel Gasienica <daniel@gasienica.ch>\",\n    \"Julian Walker <julian@fiftythree.com>\",\n    \"Amit Pitaru <pitaru.amit@gmail.com>\",\n    \"Brandon Aaron <hello.brandon@aaron.sh>\",\n    \"Andreas Lind <andreas@one.com>\",\n    \"Maurus Cuelenaere <mcuelenaere@gmail.com>\",\n    \"Linus Unnebäck <linus@folkdatorn.se>\",\n    \"Victor Mateevitsi <mvictoras@gmail.com>\",\n    \"Alaric Holloway <alaric.holloway@gmail.com>\",\n    \"Bernhard K. Weisshuhn <bkw@codingforce.com>\",\n    \"Chris Riley <criley@primedia.com>\",\n    \"David Carley <dacarley@gmail.com>\",\n    \"John Tobin <john@limelightmobileinc.com>\",\n    \"Kenton Gray <kentongray@gmail.com>\",\n    \"Felix Bünemann <Felix.Buenemann@gmail.com>\",\n    \"Samy Al Zahrani <samyalzahrany@gmail.com>\",\n    \"Chintan Thakkar <lemnisk8@gmail.com>\",\n    \"F. Orlando Galashan <frulo@gmx.de>\",\n    \"Kleis Auke Wolthuizen <info@kleisauke.nl>\",\n    \"Matt Hirsch <mhirsch@media.mit.edu>\",\n    \"Matthias Thoemmes <thoemmes@gmail.com>\",\n    \"Patrick Paskaris <patrick@paskaris.gr>\",\n    \"Jérémy Lal <kapouer@melix.org>\",\n    \"Rahul Nanwani <r.nanwani@gmail.com>\",\n    \"Alice Monday <alice0meta@gmail.com>\",\n    \"Kristo Jorgenson <kristo.jorgenson@gmail.com>\",\n    \"YvesBos <yves_bos@outlook.com>\",\n    \"Guy Maliar <guy@tailorbrands.com>\",\n    \"Nicolas Coden <nicolas@ncoden.fr>\",\n    \"Matt Parrish <matt.r.parrish@gmail.com>\",\n    \"Marcel Bretschneider <marcel.bretschneider@gmail.com>\",\n    \"Matthew McEachen <matthew+github@mceachen.org>\",\n    \"Jarda Kotěšovec <jarda.kotesovec@gmail.com>\",\n    \"Kenric D'Souza <kenric.dsouza@gmail.com>\",\n    \"Oleh Aleinyk <oleg.aleynik@gmail.com>\",\n    \"Marcel Bretschneider <marcel.bretschneider@gmail.com>\",\n    \"Andrea Bianco <andrea.bianco@unibas.ch>\",\n    \"Rik Heywood <rik@rik.org>\",\n    \"Thomas Parisot <hi@oncletom.io>\",\n    \"Nathan Graves <nathanrgraves+github@gmail.com>\",\n    \"Tom Lokhorst <tom@lokhorst.eu>\",\n    \"Espen Hovlandsdal <espen@hovlandsdal.com>\",\n    \"Sylvain Dumont <sylvain.dumont35@gmail.com>\",\n    \"Alun Davies <alun.owain.davies@googlemail.com>\",\n    \"Aidan Hoolachan <ajhoolachan21@gmail.com>\",\n    \"Axel Eirola <axel.eirola@iki.fi>\",\n    \"Freezy <freezy@xbmc.org>\",\n    \"Daiz <taneli.vatanen@gmail.com>\",\n    \"Julian Aubourg <j@ubourg.net>\",\n    \"Keith Belovay <keith@picthrive.com>\",\n    \"Michael B. Klein <mbklein@gmail.com>\",\n    \"Jordan Prudhomme <jordan@raboland.fr>\",\n    \"Ilya Ovdin <iovdin@gmail.com>\",\n    \"Andargor <andargor@yahoo.com>\",\n    \"Paul Neave <paul.neave@gmail.com>\",\n    \"Brendan Kennedy <brenwken@gmail.com>\",\n    \"Brychan Bennett-Odlum <git@brychan.io>\",\n    \"Edward Silverton <e.silverton@gmail.com>\",\n    \"Roman Malieiev <aromaleev@gmail.com>\",\n    \"Tomas Szabo <tomas.szabo@deftomat.com>\",\n    \"Robert O'Rourke <robert@o-rourke.org>\",\n    \"Guillermo Alfonso Varela Chouciño <guillevch@gmail.com>\",\n    \"Christian Flintrup <chr@gigahost.dk>\",\n    \"Manan Jadhav <manan@motionden.com>\",\n    \"Leon Radley <leon@radley.se>\",\n    \"alza54 <alza54@thiocod.in>\",\n    \"Jacob Smith <jacob@frende.me>\",\n    \"Michael Nutt <michael@nutt.im>\",\n    \"Brad Parham <baparham@gmail.com>\",\n    \"Taneli Vatanen <taneli.vatanen@gmail.com>\",\n    \"Joris Dugué <zaruike10@gmail.com>\",\n    \"Chris Banks <christopher.bradley.banks@gmail.com>\",\n    \"Ompal Singh <ompal.hitm09@gmail.com>\",\n    \"Brodan <christopher.hranj@gmail.com>\",\n    \"Ankur Parihar <ankur.github@gmail.com>\",\n    \"Brahim Ait elhaj <brahima@gmail.com>\",\n    \"Mart Jansink <m.jansink@gmail.com>\",\n    \"Lachlan Newman <lachnewman007@gmail.com>\",\n    \"Dennis Beatty <dennis@dcbeatty.com>\",\n    \"Ingvar Stepanyan <me@rreverser.com>\",\n    \"Don Denton <don@happycollision.com>\"\n  ],\n  \"scripts\": {\n    \"build\": \"node install/build.js\",\n    \"install\": \"node install/check.js || npm run build\",\n    \"clean\": \"rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*\",\n    \"test\": \"npm run lint && npm run test-unit\",\n    \"lint\": \"npm run lint-cpp && npm run lint-js && npm run lint-types\",\n    \"lint-cpp\": \"cpplint --quiet src/*.h src/*.cc\",\n    \"lint-js\": \"biome lint\",\n    \"lint-types\": \"tsd --files ./test/types/sharp.test-d.ts\",\n    \"test-leak\": \"./test/leak/leak.sh\",\n    \"test-unit\": \"node --experimental-test-coverage test/unit.mjs\",\n    \"package-from-local-build\": \"node npm/from-local-build.js\",\n    \"package-release-notes\": \"node npm/release-notes.js\",\n    \"docs-build\": \"node docs/build.mjs\",\n    \"docs-serve\": \"cd docs && npm start\",\n    \"docs-publish\": \"cd docs && npm run build && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp\"\n  },\n  \"type\": \"commonjs\",\n  \"main\": \"lib/index.js\",\n  \"types\": \"lib/index.d.ts\",\n  \"files\": [\n    \"install\",\n    \"lib\",\n    \"src/*.{cc,h,gyp}\"\n  ],\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git://github.com/lovell/sharp.git\"\n  },\n  \"keywords\": [\n    \"jpeg\",\n    \"png\",\n    \"webp\",\n    \"avif\",\n    \"tiff\",\n    \"gif\",\n    \"svg\",\n    \"jp2\",\n    \"dzi\",\n    \"image\",\n    \"resize\",\n    \"thumbnail\",\n    \"crop\",\n    \"embed\",\n    \"libvips\",\n    \"vips\"\n  ],\n  \"dependencies\": {\n    \"@img/colour\": \"^1.0.0\",\n    \"detect-libc\": \"^2.1.2\",\n    \"semver\": \"^7.7.3\"\n  },\n  \"optionalDependencies\": {\n    \"@img/sharp-darwin-arm64\": \"0.34.5\",\n    \"@img/sharp-darwin-x64\": \"0.34.5\",\n    \"@img/sharp-libvips-darwin-arm64\": \"1.2.4\",\n    \"@img/sharp-libvips-darwin-x64\": \"1.2.4\",\n    \"@img/sharp-libvips-linux-arm\": \"1.2.4\",\n    \"@img/sharp-libvips-linux-arm64\": \"1.2.4\",\n    \"@img/sharp-libvips-linux-ppc64\": \"1.2.4\",\n    \"@img/sharp-libvips-linux-riscv64\": \"1.2.4\",\n    \"@img/sharp-libvips-linux-s390x\": \"1.2.4\",\n    \"@img/sharp-libvips-linux-x64\": \"1.2.4\",\n    \"@img/sharp-libvips-linuxmusl-arm64\": \"1.2.4\",\n    \"@img/sharp-libvips-linuxmusl-x64\": \"1.2.4\",\n    \"@img/sharp-linux-arm\": \"0.34.5\",\n    \"@img/sharp-linux-arm64\": \"0.34.5\",\n    \"@img/sharp-linux-ppc64\": \"0.34.5\",\n    \"@img/sharp-linux-riscv64\": \"0.34.5\",\n    \"@img/sharp-linux-s390x\": \"0.34.5\",\n    \"@img/sharp-linux-x64\": \"0.34.5\",\n    \"@img/sharp-linuxmusl-arm64\": \"0.34.5\",\n    \"@img/sharp-linuxmusl-x64\": \"0.34.5\",\n    \"@img/sharp-wasm32\": \"0.34.5\",\n    \"@img/sharp-win32-arm64\": \"0.34.5\",\n    \"@img/sharp-win32-ia32\": \"0.34.5\",\n    \"@img/sharp-win32-x64\": \"0.34.5\"\n  },\n  \"devDependencies\": {\n    \"@biomejs/biome\": \"^2.3.4\",\n    \"@cpplint/cli\": \"^0.1.0\",\n    \"@emnapi/runtime\": \"^1.7.0\",\n    \"@img/sharp-libvips-dev\": \"1.2.4\",\n    \"@img/sharp-libvips-dev-wasm32\": \"1.2.4\",\n    \"@img/sharp-libvips-win32-arm64\": \"1.2.4\",\n    \"@img/sharp-libvips-win32-ia32\": \"1.2.4\",\n    \"@img/sharp-libvips-win32-x64\": \"1.2.4\",\n    \"@types/node\": \"*\",\n    \"emnapi\": \"^1.7.0\",\n    \"exif-reader\": \"^2.0.2\",\n    \"extract-zip\": \"^2.0.1\",\n    \"icc\": \"^3.0.0\",\n    \"jsdoc-to-markdown\": \"^9.1.3\",\n    \"node-addon-api\": \"^8.5.0\",\n    \"node-gyp\": \"^11.5.0\",\n    \"tar-fs\": \"^3.1.1\",\n    \"tsd\": \"^0.33.0\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"engines\": {\n    \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n  },\n  \"config\": {\n    \"libvips\": \">=8.17.3\"\n  },\n  \"funding\": {\n    \"url\": \"https://opencollective.com/libvips\"\n  }\n}\n"
  },
  {
    "path": "src/CPPLINT.cfg",
    "content": "set noparent\n\nlinelength=120\n\nfilter=-build/include\nfilter=+build/include_alpha\nfilter=+build/include_subdir\nfilter=+build/include_what_you_use\n\nfilter=-whitespace/indent_namespace\n"
  },
  {
    "path": "src/binding.gyp",
    "content": "# Copyright 2013 Lovell Fuller and others.\n# SPDX-License-Identifier: Apache-2.0\n\n{\n  'variables': {\n    'vips_version': '<!(node -p \"require(\\'../lib/libvips\\').minimumLibvipsVersion\")',\n    'platform_and_arch': '<!(node -p \"require(\\'../lib/libvips\\').buildPlatformArch()\")',\n    'sharp_libvips_version': '<!(node -p \"require(\\'../package.json\\').optionalDependencies[\\'@img/sharp-libvips-<(platform_and_arch)\\']\")',\n    'sharp_libvips_yarn_locator': '<!(node -p \"require(\\'../lib/libvips\\').yarnLocator()\")',\n    'sharp_libvips_include_dir': '<!(node -p \"require(\\'../lib/libvips\\').buildSharpLibvipsIncludeDir()\")',\n    'sharp_libvips_cplusplus_dir': '<!(node -p \"require(\\'../lib/libvips\\').buildSharpLibvipsCPlusPlusDir()\")',\n    'sharp_libvips_lib_dir': '<!(node -p \"require(\\'../lib/libvips\\').buildSharpLibvipsLibDir()\")'\n  },\n  'targets': [{\n    'target_name': 'libvips-cpp-<(vips_version)',\n    'conditions': [\n      ['OS == \"win\"', {\n        # Build libvips C++ binding for Windows due to MSVC std library ABI changes\n        'type': 'shared_library',\n        'defines': [\n          '_VIPS_PUBLIC=__declspec(dllexport)',\n          '_ALLOW_KEYWORD_MACROS',\n          'G_DISABLE_ASSERT',\n          'G_DISABLE_CAST_CHECKS',\n          'G_DISABLE_CHECKS'\n        ],\n        'sources': [\n          '<(sharp_libvips_cplusplus_dir)/VConnection.cpp',\n          '<(sharp_libvips_cplusplus_dir)/VError.cpp',\n          '<(sharp_libvips_cplusplus_dir)/VImage.cpp',\n          '<(sharp_libvips_cplusplus_dir)/VInterpolate.cpp',\n          '<(sharp_libvips_cplusplus_dir)/VRegion.cpp'\n        ],\n        'include_dirs': [\n          '<(sharp_libvips_include_dir)',\n          '<(sharp_libvips_include_dir)/glib-2.0',\n          '<(sharp_libvips_lib_dir)/glib-2.0/include'\n        ],\n        'link_settings': {\n          'library_dirs': [\n            '<(sharp_libvips_lib_dir)'\n          ],\n          'libraries': [\n            'libvips.lib'\n          ],\n        },\n        'configurations': {\n          'Release': {\n            'msvs_settings': {\n              'VCCLCompilerTool': {\n                \"AdditionalOptions\": [\n                  \"/std:c++17\"\n                ],\n                'ExceptionHandling': 1,\n                'Optimization': 1,\n                'WholeProgramOptimization': 'true'\n              },\n              'VCLibrarianTool': {\n                'AdditionalOptions': [\n                  '/LTCG:INCREMENTAL'\n                ]\n              },\n              'VCLinkerTool': {\n                'ImageHasSafeExceptionHandlers': 'false',\n                'OptimizeReferences': 2,\n                'EnableCOMDATFolding': 2,\n                'LinkIncremental': 1,\n                'AdditionalOptions': [\n                  '/LTCG:INCREMENTAL'\n                ]\n              }\n            },\n            'msvs_disabled_warnings': [\n              4275\n            ]\n          }\n        }\n      }, {\n        # Ignore this target for non-Windows\n        'type': 'none'\n      }]\n    ]\n  }, {\n    'target_name': 'sharp-<(platform_and_arch)',\n    'defines': [\n      'G_DISABLE_ASSERT',\n      'G_DISABLE_CAST_CHECKS',\n      'G_DISABLE_CHECKS',\n      'NAPI_VERSION=9',\n      'NODE_ADDON_API_DISABLE_DEPRECATED',\n      'NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS'\n    ],\n    'dependencies': [\n      '<!(node -p \"require(\\'node-addon-api\\').gyp\")',\n      'libvips-cpp-<(vips_version)'\n    ],\n    'variables': {\n      'conditions': [\n        ['OS != \"win\"', {\n          'pkg_config_path': '<!(node -p \"require(\\'../lib/libvips\\').pkgConfigPath()\")',\n          'use_global_libvips': '<!(node -p \"Boolean(require(\\'../lib/libvips\\').useGlobalLibvips()).toString()\")'\n        }, {\n          'pkg_config_path': '',\n          'use_global_libvips': ''\n        }]\n      ]\n    },\n    'sources': [\n      'common.cc',\n      'metadata.cc',\n      'stats.cc',\n      'operations.cc',\n      'pipeline.cc',\n      'utilities.cc',\n      'sharp.cc'\n    ],\n    'include_dirs': [\n      '<!(node -p \"require(\\'node-addon-api\\').include_dir\")',\n    ],\n    'conditions': [\n      ['use_global_libvips == \"true\"', {\n        # Use pkg-config for include and lib\n        'include_dirs': ['<!@(PKG_CONFIG_PATH=\"<(pkg_config_path)\" pkg-config --cflags-only-I vips-cpp vips glib-2.0 | sed s/-I//g)'],\n        'libraries': ['<!@(PKG_CONFIG_PATH=\"<(pkg_config_path)\" pkg-config --libs vips-cpp)'],\n        'defines': [\n          'SHARP_USE_GLOBAL_LIBVIPS'\n        ],\n        'conditions': [\n          ['OS == \"linux\"', {\n            'defines': [\n              # Inspect libvips-cpp.so to determine which C++11 ABI version was used and set _GLIBCXX_USE_CXX11_ABI accordingly. This is quite horrible.\n              '_GLIBCXX_USE_CXX11_ABI=<!(if readelf -Ws \"$(PKG_CONFIG_PATH=\"<(pkg_config_path)\" pkg-config --variable libdir vips-cpp)/libvips-cpp.so\" | c++filt | grep -qF __cxx11;then echo \"1\";else echo \"0\";fi)'\n            ]\n          }]\n        ]\n      }, {\n        # Use pre-built libvips stored locally within node_modules\n        'include_dirs': [\n          '<(sharp_libvips_include_dir)',\n          '<(sharp_libvips_include_dir)/glib-2.0',\n          '<(sharp_libvips_lib_dir)/glib-2.0/include'\n        ],\n        'library_dirs': [\n          '<(sharp_libvips_lib_dir)'\n        ],\n        'conditions': [\n          ['OS == \"win\"', {\n            'defines': [\n              '_ALLOW_KEYWORD_MACROS',\n              '_FILE_OFFSET_BITS=64'\n            ],\n            'link_settings': {\n              'libraries': [\n                'libvips.lib'\n              ]\n            }\n          }],\n          ['OS == \"mac\"', {\n            'link_settings': {\n              'libraries': [\n                'libvips-cpp.<(vips_version).dylib'\n              ]\n            },\n            'xcode_settings': {\n              'OTHER_LDFLAGS': [\n                '-Wl,-s',\n                '-Wl,-dead_strip',\n                # Ensure runtime linking is relative to sharp.node\n                '-Wl,-rpath,\\'@loader_path/../../sharp-libvips-<(platform_and_arch)/lib\\'',\n                '-Wl,-rpath,\\'@loader_path/../../../sharp-libvips-<(platform_and_arch)/<(sharp_libvips_version)/lib\\'',\n                '-Wl,-rpath,\\'@loader_path/../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\\'',\n                '-Wl,-rpath,\\'@loader_path/../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\\'',\n                '-Wl,-rpath,\\'@loader_path/../../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\\'',\n                '-Wl,-rpath,\\'@loader_path/../../../../../@img-sharp-libvips-<(platform_and_arch)-npm-<(sharp_libvips_version)-<(sharp_libvips_yarn_locator)/node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\\''\n              ]\n            }\n          }],\n          ['OS == \"linux\"', {\n            'defines': [\n              '_GLIBCXX_USE_CXX11_ABI=1'\n            ],\n            'cflags_cc': [\n              '<!(node -p \"require(\\'detect-libc\\').isNonGlibcLinuxSync() ? \\'\\' : \\'-flto=auto\\'\")'\n            ],\n            'link_settings': {\n              'libraries': [\n                '-l:libvips-cpp.so.<(vips_version)'\n              ],\n              'ldflags': [\n                '-lstdc++fs',\n                '-Wl,-s',\n                '-Wl,--disable-new-dtags',\n                '-Wl,-z,nodelete',\n                '-Wl,-Bsymbolic-functions',\n                '-Wl,-rpath=\\'$$ORIGIN/../../sharp-libvips-<(platform_and_arch)/lib\\'',\n                '-Wl,-rpath=\\'$$ORIGIN/../../../sharp-libvips-<(platform_and_arch)/<(sharp_libvips_version)/lib\\'',\n                '-Wl,-rpath=\\'$$ORIGIN/../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\\'',\n                '-Wl,-rpath=\\'$$ORIGIN/../../../node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\\'',\n                '-Wl,-rpath,\\'$$ORIGIN/../../../../../@img-sharp-libvips-<(platform_and_arch)-npm-<(sharp_libvips_version)-<(sharp_libvips_yarn_locator)/node_modules/@img/sharp-libvips-<(platform_and_arch)/lib\\''\n              ]\n            }\n          }],\n          ['OS == \"emscripten\"', {\n            'product_extension': 'node.js',\n            'link_settings': {\n              'ldflags': [\n                '-fexceptions',\n                '--pre-js=<!(node -p \"require.resolve(\\'./emscripten/pre.js\\')\")',\n                '-Oz',\n                '-sALLOW_MEMORY_GROWTH',\n                '-sENVIRONMENT=node',\n                '-sEXPORTED_FUNCTIONS=emnapiInit,_vips_shutdown,_uv_library_shutdown',\n                '-sNODERAWFS',\n                '-sWASM_ASYNC_COMPILATION=0'\n              ],\n              'libraries': [\n                '<!@(PKG_CONFIG_PATH=\"<!(node -p \"require(\\'@img/sharp-libvips-dev-wasm32/lib\\')\")/pkgconfig\" pkg-config --static --libs vips-cpp)'\n              ],\n            }\n          }]\n        ]\n      }]\n    ],\n    'cflags_cc': [\n      '-std=c++17',\n      '-fexceptions',\n      '-Wall',\n      '-Os'\n    ],\n    'xcode_settings': {\n      'CLANG_CXX_LANGUAGE_STANDARD': 'c++17',\n      'MACOSX_DEPLOYMENT_TARGET': '10.15',\n      'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',\n      'GCC_ENABLE_CPP_RTTI': 'YES',\n      'OTHER_CPLUSPLUSFLAGS': [\n        '-fexceptions',\n        '-Wall',\n        '-Oz'\n      ]\n    },\n    'configurations': {\n      'Release': {\n        'conditions': [\n          ['target_arch == \"arm\"', {\n            'cflags_cc': [\n              '-Wno-psabi'\n            ]\n          }],\n          ['OS == \"win\"', {\n            'msvs_settings': {\n              'VCCLCompilerTool': {\n                \"AdditionalOptions\": [\n                  \"/std:c++17\"\n                ],\n                'ExceptionHandling': 1,\n                'Optimization': 1,\n                'WholeProgramOptimization': 'true'\n              },\n              'VCLibrarianTool': {\n                'AdditionalOptions': [\n                  '/LTCG:INCREMENTAL'\n                ]\n              },\n              'VCLinkerTool': {\n                'ImageHasSafeExceptionHandlers': 'false',\n                'OptimizeReferences': 2,\n                'EnableCOMDATFolding': 2,\n                'LinkIncremental': 1,\n                'AdditionalOptions': [\n                  '/LTCG:INCREMENTAL'\n                ]\n              }\n            },\n            'msvs_disabled_warnings': [\n              4275\n            ]\n          }]\n        ]\n      }\n    },\n  }, {\n    'target_name': 'copy-dll',\n    'type': 'none',\n    'dependencies': [\n      'sharp-<(platform_and_arch)'\n    ],\n    'conditions': [\n      ['OS == \"win\"', {\n        'copies': [{\n          'destination': 'build/Release',\n          'files': [\n            '<(sharp_libvips_lib_dir)/libvips-42.dll'\n          ]\n        }]\n      }]\n    ]\n  }]\n}\n"
  },
  {
    "path": "src/common.cc",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#include <algorithm>\n#include <cstdlib>\n#include <map>\n#include <mutex>\n#include <queue>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include <napi.h>\n#include <vips/vips8>\n\n#include \"./common.h\"\n\nusing vips::VImage;\n\nnamespace sharp {\n\n  // Convenience methods to access the attributes of a Napi::Object\n  bool HasAttr(Napi::Object obj, std::string attr) {\n    return obj.Has(attr);\n  }\n  std::string AttrAsStr(Napi::Object obj, std::string attr) {\n    return obj.Get(attr).As<Napi::String>();\n  }\n  std::string AttrAsStr(Napi::Object obj, unsigned int const attr) {\n    return obj.Get(attr).As<Napi::String>();\n  }\n  uint32_t AttrAsUint32(Napi::Object obj, std::string attr) {\n    return obj.Get(attr).As<Napi::Number>().Uint32Value();\n  }\n  int32_t AttrAsInt32(Napi::Object obj, std::string attr) {\n    return obj.Get(attr).As<Napi::Number>().Int32Value();\n  }\n  int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr) {\n    return obj.Get(attr).As<Napi::Number>().Int32Value();\n  }\n  int64_t AttrAsInt64(Napi::Object obj, std::string attr) {\n    return obj.Get(attr).As<Napi::Number>().Int64Value();\n  }\n  double AttrAsDouble(Napi::Object obj, std::string attr) {\n    return obj.Get(attr).As<Napi::Number>().DoubleValue();\n  }\n  double AttrAsDouble(Napi::Object obj, unsigned int const attr) {\n    return obj.Get(attr).As<Napi::Number>().DoubleValue();\n  }\n  bool AttrAsBool(Napi::Object obj, std::string attr) {\n    return obj.Get(attr).As<Napi::Boolean>().Value();\n  }\n  std::vector<double> AttrAsVectorOfDouble(Napi::Object obj, std::string attr) {\n    Napi::Array napiArray = obj.Get(attr).As<Napi::Array>();\n    std::vector<double> vectorOfDouble(napiArray.Length());\n    for (unsigned int i = 0; i < napiArray.Length(); i++) {\n      vectorOfDouble[i] = AttrAsDouble(napiArray, i);\n    }\n    return vectorOfDouble;\n  }\n  std::vector<int32_t> AttrAsInt32Vector(Napi::Object obj, std::string attr) {\n    Napi::Array array = obj.Get(attr).As<Napi::Array>();\n    std::vector<int32_t> vector(array.Length());\n    for (unsigned int i = 0; i < array.Length(); i++) {\n      vector[i] = AttrAsInt32(array, i);\n    }\n    return vector;\n  }\n\n  // Create an InputDescriptor instance from a Napi::Object describing an input image\n  InputDescriptor* CreateInputDescriptor(Napi::Object input) {\n    InputDescriptor *descriptor = new InputDescriptor;\n    if (HasAttr(input, \"file\")) {\n      descriptor->file = AttrAsStr(input, \"file\");\n    } else if (HasAttr(input, \"buffer\")) {\n      Napi::Buffer<char> buffer = input.Get(\"buffer\").As<Napi::Buffer<char>>();\n      descriptor->bufferLength = buffer.Length();\n      descriptor->buffer = buffer.Data();\n      descriptor->isBuffer = true;\n    }\n    descriptor->failOn = AttrAsEnum<VipsFailOn>(input, \"failOn\", VIPS_TYPE_FAIL_ON);\n    // Density for vector-based input\n    if (HasAttr(input, \"density\")) {\n      descriptor->density = AttrAsDouble(input, \"density\");\n    }\n    // Should we ignore any embedded ICC profile\n    if (HasAttr(input, \"ignoreIcc\")) {\n      descriptor->ignoreIcc = AttrAsBool(input, \"ignoreIcc\");\n    }\n    // Raw pixel input\n    if (HasAttr(input, \"rawChannels\")) {\n      descriptor->rawDepth = AttrAsEnum<VipsBandFormat>(input, \"rawDepth\", VIPS_TYPE_BAND_FORMAT);\n      descriptor->rawChannels = AttrAsUint32(input, \"rawChannels\");\n      descriptor->rawWidth = AttrAsUint32(input, \"rawWidth\");\n      descriptor->rawHeight = AttrAsUint32(input, \"rawHeight\");\n      descriptor->rawPremultiplied = AttrAsBool(input, \"rawPremultiplied\");\n      descriptor->rawPageHeight = AttrAsUint32(input, \"rawPageHeight\");\n    }\n    // Multi-page input (GIF, TIFF, PDF)\n    if (HasAttr(input, \"pages\")) {\n      descriptor->pages = AttrAsInt32(input, \"pages\");\n    }\n    if (HasAttr(input, \"page\")) {\n      descriptor->page = AttrAsUint32(input, \"page\");\n    }\n    // SVG\n    if (HasAttr(input, \"svgStylesheet\")) {\n      descriptor->svgStylesheet = AttrAsStr(input, \"svgStylesheet\");\n    }\n    if (HasAttr(input, \"svgHighBitdepth\")) {\n      descriptor->svgHighBitdepth = AttrAsBool(input, \"svgHighBitdepth\");\n    }\n    // Multi-level input (OpenSlide)\n    if (HasAttr(input, \"openSlideLevel\")) {\n      descriptor->openSlideLevel = AttrAsUint32(input, \"openSlideLevel\");\n    }\n    // subIFD (OME-TIFF)\n    if (HasAttr(input, \"subifd\")) {\n      descriptor->tiffSubifd = AttrAsInt32(input, \"tiffSubifd\");\n    }\n    // // PDF background color\n    if (HasAttr(input, \"pdfBackground\")) {\n      descriptor->pdfBackground = AttrAsVectorOfDouble(input, \"pdfBackground\");\n    }\n    // Use JPEG 2000 oneshot mode?\n    if (HasAttr(input, \"jp2Oneshot\")) {\n      descriptor->jp2Oneshot = AttrAsBool(input, \"jp2Oneshot\");\n    }\n    // Create new image\n    if (HasAttr(input, \"createChannels\")) {\n      descriptor->createChannels = AttrAsUint32(input, \"createChannels\");\n      descriptor->createWidth = AttrAsUint32(input, \"createWidth\");\n      descriptor->createHeight = AttrAsUint32(input, \"createHeight\");\n      descriptor->createPageHeight = AttrAsUint32(input, \"createPageHeight\");\n      if (HasAttr(input, \"createNoiseType\")) {\n        descriptor->createNoiseType = AttrAsStr(input, \"createNoiseType\");\n        descriptor->createNoiseMean = AttrAsDouble(input, \"createNoiseMean\");\n        descriptor->createNoiseSigma = AttrAsDouble(input, \"createNoiseSigma\");\n      } else {\n        descriptor->createBackground = AttrAsVectorOfDouble(input, \"createBackground\");\n      }\n    }\n    // Create new image with text\n    if (HasAttr(input, \"textValue\")) {\n      descriptor->textValue = AttrAsStr(input, \"textValue\");\n      if (HasAttr(input, \"textFont\")) {\n        descriptor->textFont = AttrAsStr(input, \"textFont\");\n      }\n      if (HasAttr(input, \"textFontfile\")) {\n        descriptor->textFontfile = AttrAsStr(input, \"textFontfile\");\n      }\n      if (HasAttr(input, \"textWidth\")) {\n        descriptor->textWidth = AttrAsUint32(input, \"textWidth\");\n      }\n      if (HasAttr(input, \"textHeight\")) {\n        descriptor->textHeight = AttrAsUint32(input, \"textHeight\");\n      }\n      if (HasAttr(input, \"textAlign\")) {\n        descriptor->textAlign = AttrAsEnum<VipsAlign>(input, \"textAlign\", VIPS_TYPE_ALIGN);\n      }\n      if (HasAttr(input, \"textJustify\")) {\n        descriptor->textJustify = AttrAsBool(input, \"textJustify\");\n      }\n      if (HasAttr(input, \"textDpi\")) {\n        descriptor->textDpi = AttrAsUint32(input, \"textDpi\");\n      }\n      if (HasAttr(input, \"textRgba\")) {\n        descriptor->textRgba = AttrAsBool(input, \"textRgba\");\n      }\n      if (HasAttr(input, \"textSpacing\")) {\n        descriptor->textSpacing = AttrAsUint32(input, \"textSpacing\");\n      }\n      if (HasAttr(input, \"textWrap\")) {\n        descriptor->textWrap = AttrAsEnum<VipsTextWrap>(input, \"textWrap\", VIPS_TYPE_TEXT_WRAP);\n      }\n    }\n    // Join images together\n    if (HasAttr(input, \"joinAnimated\")) {\n      descriptor->joinAnimated = AttrAsBool(input, \"joinAnimated\");\n    }\n    if (HasAttr(input, \"joinAcross\")) {\n      descriptor->joinAcross = AttrAsUint32(input, \"joinAcross\");\n    }\n    if (HasAttr(input, \"joinShim\")) {\n      descriptor->joinShim = AttrAsUint32(input, \"joinShim\");\n    }\n    if (HasAttr(input, \"joinBackground\")) {\n      descriptor->joinBackground = AttrAsVectorOfDouble(input, \"joinBackground\");\n    }\n    if (HasAttr(input, \"joinHalign\")) {\n      descriptor->joinHalign = AttrAsEnum<VipsAlign>(input, \"joinHalign\", VIPS_TYPE_ALIGN);\n    }\n    if (HasAttr(input, \"joinValign\")) {\n      descriptor->joinValign = AttrAsEnum<VipsAlign>(input, \"joinValign\", VIPS_TYPE_ALIGN);\n    }\n    // Limit input images to a given number of pixels, where pixels = width * height\n    descriptor->limitInputPixels = static_cast<uint64_t>(AttrAsInt64(input, \"limitInputPixels\"));\n    if (HasAttr(input, \"access\")) {\n      descriptor->access = AttrAsBool(input, \"sequentialRead\") ? VIPS_ACCESS_SEQUENTIAL : VIPS_ACCESS_RANDOM;\n    }\n    // Remove safety features and allow unlimited input\n    descriptor->unlimited = AttrAsBool(input, \"unlimited\");\n    // Use the EXIF orientation to auto orient the image\n    descriptor->autoOrient = AttrAsBool(input, \"autoOrient\");\n    return descriptor;\n  }\n\n  // How many tasks are in the queue?\n  std::atomic<int> counterQueue{0};\n\n  // How many tasks are being processed?\n  std::atomic<int> counterProcess{0};\n\n  // Filename extension checkers\n  static bool EndsWith(std::string const &str, std::string const &end) {\n    return str.length() >= end.length() && 0 == str.compare(str.length() - end.length(), end.length(), end);\n  }\n  bool IsJpeg(std::string const &str) {\n    return EndsWith(str, \".jpg\") || EndsWith(str, \".jpeg\") || EndsWith(str, \".JPG\") || EndsWith(str, \".JPEG\");\n  }\n  bool IsPng(std::string const &str) {\n    return EndsWith(str, \".png\") || EndsWith(str, \".PNG\");\n  }\n  bool IsWebp(std::string const &str) {\n    return EndsWith(str, \".webp\") || EndsWith(str, \".WEBP\");\n  }\n  bool IsGif(std::string const &str) {\n    return EndsWith(str, \".gif\") || EndsWith(str, \".GIF\");\n  }\n  bool IsJp2(std::string const &str) {\n    return EndsWith(str, \".jp2\") || EndsWith(str, \".jpx\") || EndsWith(str, \".j2k\") || EndsWith(str, \".j2c\")\n      || EndsWith(str, \".JP2\") || EndsWith(str, \".JPX\") || EndsWith(str, \".J2K\") || EndsWith(str, \".J2C\");\n  }\n  bool IsTiff(std::string const &str) {\n    return EndsWith(str, \".tif\") || EndsWith(str, \".tiff\") || EndsWith(str, \".TIF\") || EndsWith(str, \".TIFF\");\n  }\n  bool IsHeic(std::string const &str) {\n    return EndsWith(str, \".heic\") || EndsWith(str, \".HEIC\");\n  }\n  bool IsHeif(std::string const &str) {\n    return EndsWith(str, \".heif\") || EndsWith(str, \".HEIF\") || IsHeic(str) || IsAvif(str);\n  }\n  bool IsAvif(std::string const &str) {\n    return EndsWith(str, \".avif\") || EndsWith(str, \".AVIF\");\n  }\n  bool IsJxl(std::string const &str) {\n    return EndsWith(str, \".jxl\") || EndsWith(str, \".JXL\");\n  }\n  bool IsDz(std::string const &str) {\n    return EndsWith(str, \".dzi\") || EndsWith(str, \".DZI\");\n  }\n  bool IsDzZip(std::string const &str) {\n    return EndsWith(str, \".zip\") || EndsWith(str, \".ZIP\") || EndsWith(str, \".szi\") || EndsWith(str, \".SZI\");\n  }\n  bool IsV(std::string const &str) {\n    return EndsWith(str, \".v\") || EndsWith(str, \".V\") || EndsWith(str, \".vips\") || EndsWith(str, \".VIPS\");\n  }\n\n  /*\n    Trim space from end of string.\n  */\n  std::string TrimEnd(std::string const &str) {\n    return str.substr(0, str.find_last_not_of(\" \\n\\r\\f\") + 1);\n  }\n\n  /*\n    Provide a string identifier for the given image type.\n  */\n  std::string ImageTypeId(ImageType const imageType) {\n    std::string id;\n    switch (imageType) {\n      case ImageType::JPEG: id = \"jpeg\"; break;\n      case ImageType::PNG: id = \"png\"; break;\n      case ImageType::WEBP: id = \"webp\"; break;\n      case ImageType::TIFF: id = \"tiff\"; break;\n      case ImageType::GIF: id = \"gif\"; break;\n      case ImageType::JP2: id = \"jp2\"; break;\n      case ImageType::SVG: id = \"svg\"; break;\n      case ImageType::HEIF: id = \"heif\"; break;\n      case ImageType::PDF: id = \"pdf\"; break;\n      case ImageType::MAGICK: id = \"magick\"; break;\n      case ImageType::OPENSLIDE: id = \"openslide\"; break;\n      case ImageType::PPM: id = \"ppm\"; break;\n      case ImageType::FITS: id = \"fits\"; break;\n      case ImageType::EXR: id = \"exr\"; break;\n      case ImageType::JXL: id = \"jxl\"; break;\n      case ImageType::RAD: id = \"rad\"; break;\n      case ImageType::DCRAW: id = \"dcraw\"; break;\n      case ImageType::VIPS: id = \"vips\"; break;\n      case ImageType::RAW: id = \"raw\"; break;\n      case ImageType::UNKNOWN: id = \"unknown\"; break;\n      case ImageType::MISSING: id = \"missing\"; break;\n    }\n    return id;\n  }\n\n  /**\n   * Regenerate this table with something like:\n   *\n   * $ vips -l foreign | grep -i load | awk '{ print $2, $1; }'\n   *\n   * Plus a bit of editing.\n   */\n  std::map<std::string, ImageType> loaderToType = {\n    { \"VipsForeignLoadJpegFile\", ImageType::JPEG },\n    { \"VipsForeignLoadJpegBuffer\", ImageType::JPEG },\n    { \"VipsForeignLoadPngFile\", ImageType::PNG },\n    { \"VipsForeignLoadPngBuffer\", ImageType::PNG },\n    { \"VipsForeignLoadWebpFile\", ImageType::WEBP },\n    { \"VipsForeignLoadWebpBuffer\", ImageType::WEBP },\n    { \"VipsForeignLoadTiffFile\", ImageType::TIFF },\n    { \"VipsForeignLoadTiffBuffer\", ImageType::TIFF },\n    { \"VipsForeignLoadGifFile\", ImageType::GIF },\n    { \"VipsForeignLoadGifBuffer\", ImageType::GIF },\n    { \"VipsForeignLoadNsgifFile\", ImageType::GIF },\n    { \"VipsForeignLoadNsgifBuffer\", ImageType::GIF },\n    { \"VipsForeignLoadJp2kBuffer\", ImageType::JP2 },\n    { \"VipsForeignLoadJp2kFile\", ImageType::JP2 },\n    { \"VipsForeignLoadSvgFile\", ImageType::SVG },\n    { \"VipsForeignLoadSvgBuffer\", ImageType::SVG },\n    { \"VipsForeignLoadHeifFile\", ImageType::HEIF },\n    { \"VipsForeignLoadHeifBuffer\", ImageType::HEIF },\n    { \"VipsForeignLoadPdfFile\", ImageType::PDF },\n    { \"VipsForeignLoadPdfBuffer\", ImageType::PDF },\n    { \"VipsForeignLoadMagickFile\", ImageType::MAGICK },\n    { \"VipsForeignLoadMagickBuffer\", ImageType::MAGICK },\n    { \"VipsForeignLoadMagick7File\", ImageType::MAGICK },\n    { \"VipsForeignLoadMagick7Buffer\", ImageType::MAGICK },\n    { \"VipsForeignLoadOpenslideFile\", ImageType::OPENSLIDE },\n    { \"VipsForeignLoadPpmFile\", ImageType::PPM },\n    { \"VipsForeignLoadFitsFile\", ImageType::FITS },\n    { \"VipsForeignLoadOpenexr\", ImageType::EXR },\n    { \"VipsForeignLoadJxlFile\", ImageType::JXL },\n    { \"VipsForeignLoadJxlBuffer\", ImageType::JXL },\n    { \"VipsForeignLoadRadFile\", ImageType::RAD },\n    { \"VipsForeignLoadRadBuffer\", ImageType::RAD },\n    { \"VipsForeignLoadDcRawFile\", ImageType::DCRAW },\n    { \"VipsForeignLoadDcRawBuffer\", ImageType::DCRAW },\n    { \"VipsForeignLoadVips\", ImageType::VIPS },\n    { \"VipsForeignLoadVipsFile\", ImageType::VIPS },\n    { \"VipsForeignLoadRaw\", ImageType::RAW }\n  };\n\n  /*\n    Determine image format of a buffer.\n  */\n  ImageType DetermineImageType(void *buffer, size_t const length) {\n    ImageType imageType = ImageType::UNKNOWN;\n    char const *load = vips_foreign_find_load_buffer(buffer, length);\n    if (load != nullptr) {\n      auto it = loaderToType.find(load);\n      if (it != loaderToType.end()) {\n        imageType = it->second;\n      }\n    }\n    return imageType;\n  }\n\n  /*\n    Determine image format, reads the first few bytes of the file\n  */\n  ImageType DetermineImageType(char const *file) {\n    ImageType imageType = ImageType::UNKNOWN;\n    char const *load = vips_foreign_find_load(file);\n    if (load != nullptr) {\n      auto it = loaderToType.find(load);\n      if (it != loaderToType.end()) {\n        imageType = it->second;\n      }\n    } else {\n      if (EndsWith(vips::VError().what(), \" does not exist\\n\")) {\n        imageType = ImageType::MISSING;\n      }\n    }\n    return imageType;\n  }\n\n  /*\n    Does this image type support multiple pages?\n  */\n  bool ImageTypeSupportsPage(ImageType imageType) {\n    return\n      imageType == ImageType::WEBP ||\n      imageType == ImageType::MAGICK ||\n      imageType == ImageType::GIF ||\n      imageType == ImageType::JP2 ||\n      imageType == ImageType::TIFF ||\n      imageType == ImageType::HEIF ||\n      imageType == ImageType::PDF;\n  }\n\n  /*\n    Does this image type support removal of safety limits?\n  */\n  bool ImageTypeSupportsUnlimited(ImageType imageType) {\n    return\n      imageType == ImageType::JPEG ||\n      imageType == ImageType::PNG ||\n      imageType == ImageType::SVG ||\n      imageType == ImageType::TIFF ||\n      imageType == ImageType::HEIF;\n  }\n\n  /*\n    Format-specific options builder\n  */\n  vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor) {\n    vips::VOption *option = VImage::option()\n      ->set(\"access\", descriptor->access)\n      ->set(\"fail_on\", descriptor->failOn);\n    if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) {\n      option->set(\"unlimited\", true);\n    }\n    if (ImageTypeSupportsPage(imageType)) {\n      option->set(\"n\", descriptor->pages);\n      option->set(\"page\", descriptor->page);\n    }\n    switch (imageType) {\n      case ImageType::SVG:\n        option->set(\"dpi\", descriptor->density)\n              ->set(\"stylesheet\", descriptor->svgStylesheet.data())\n              ->set(\"high_bitdepth\", descriptor->svgHighBitdepth);\n        break;\n      case ImageType::TIFF:\n        option->set(\"subifd\", descriptor->tiffSubifd);\n        break;\n      case ImageType::PDF:\n        option->set(\"dpi\", descriptor->density)\n              ->set(\"background\", descriptor->pdfBackground);\n        break;\n      case ImageType::OPENSLIDE:\n        option->set(\"level\", descriptor->openSlideLevel);\n        break;\n      case ImageType::JP2:\n        option->set(\"oneshot\", descriptor->jp2Oneshot);\n        break;\n      case ImageType::MAGICK:\n        option->set(\"density\", std::to_string(descriptor->density).data());\n        break;\n      default:\n        break;\n    }\n    return option;\n  }\n\n  /*\n    Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)\n  */\n  std::tuple<VImage, ImageType> OpenInput(InputDescriptor *descriptor) {\n    VImage image;\n    ImageType imageType;\n    if (descriptor->isBuffer) {\n      if (descriptor->rawChannels > 0) {\n        // Raw, uncompressed pixel data\n        bool const is8bit = vips_band_format_is8bit(descriptor->rawDepth);\n        image = VImage::new_from_memory(descriptor->buffer, descriptor->bufferLength,\n          descriptor->rawWidth, descriptor->rawHeight, descriptor->rawChannels, descriptor->rawDepth);\n        if (descriptor->rawChannels < 3) {\n          image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_GREY16;\n        } else {\n          image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_sRGB : VIPS_INTERPRETATION_RGB16;\n        }\n        if (descriptor->rawPageHeight > 0) {\n          image.set(VIPS_META_PAGE_HEIGHT, descriptor->rawPageHeight);\n          image.set(VIPS_META_N_PAGES, static_cast<int>(descriptor->rawHeight / descriptor->rawPageHeight));\n        }\n        if (descriptor->rawPremultiplied) {\n          image = image.unpremultiply();\n        }\n        imageType = ImageType::RAW;\n      } else {\n        // Compressed data\n        imageType = DetermineImageType(descriptor->buffer, descriptor->bufferLength);\n        if (imageType != ImageType::UNKNOWN) {\n          try {\n            vips::VOption *option = GetOptionsForImageType(imageType, descriptor);\n            image = VImage::new_from_buffer(descriptor->buffer, descriptor->bufferLength, nullptr, option);\n            if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {\n              image = SetDensity(image, descriptor->density);\n            }\n          } catch (vips::VError const &err) {\n            throw vips::VError(std::string(\"Input buffer has corrupt header: \") + err.what());\n          }\n        } else {\n          throw vips::VError(\"Input buffer contains unsupported image format\");\n        }\n      }\n    } else {\n      int const channels = descriptor->createChannels;\n      if (channels > 0) {\n        // Create new image\n        if (descriptor->createNoiseType == \"gaussian\") {\n          std::vector<VImage> bands = {};\n          bands.reserve(channels);\n          for (int _band = 0; _band < channels; _band++) {\n            bands.push_back(VImage::gaussnoise(descriptor->createWidth, descriptor->createHeight, VImage::option()\n              ->set(\"mean\", descriptor->createNoiseMean)\n              ->set(\"sigma\", descriptor->createNoiseSigma)));\n          }\n          image = VImage::bandjoin(bands).copy(VImage::option()->set(\"interpretation\",\n            channels < 3 ? VIPS_INTERPRETATION_B_W: VIPS_INTERPRETATION_sRGB));\n        } else {\n          std::vector<double> background = {\n            descriptor->createBackground[0],\n            descriptor->createBackground[1],\n            descriptor->createBackground[2]\n          };\n          if (channels == 4) {\n            background.push_back(descriptor->createBackground[3]);\n          }\n          image = VImage::new_matrix(descriptor->createWidth, descriptor->createHeight)\n            .copy(VImage::option()->set(\"interpretation\",\n              channels < 3 ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_sRGB))\n            .new_from_image(background);\n        }\n        if (descriptor->createPageHeight > 0) {\n          image.set(VIPS_META_PAGE_HEIGHT, descriptor->createPageHeight);\n          image.set(VIPS_META_N_PAGES, static_cast<int>(descriptor->createHeight / descriptor->createPageHeight));\n        }\n        image = image.cast(VIPS_FORMAT_UCHAR);\n        imageType = ImageType::RAW;\n      } else if (descriptor->textValue.length() > 0) {\n        // Create a new image with text\n        vips::VOption *textOptions = VImage::option()\n          ->set(\"align\", descriptor->textAlign)\n          ->set(\"justify\", descriptor->textJustify)\n          ->set(\"rgba\", descriptor->textRgba)\n          ->set(\"spacing\", descriptor->textSpacing)\n          ->set(\"wrap\", descriptor->textWrap)\n          ->set(\"autofit_dpi\", &descriptor->textAutofitDpi);\n        if (descriptor->textWidth > 0) {\n          textOptions->set(\"width\", descriptor->textWidth);\n        }\n        // Ignore dpi if height is set\n        if (descriptor->textWidth > 0 && descriptor->textHeight > 0) {\n          textOptions->set(\"height\", descriptor->textHeight);\n        } else if (descriptor->textDpi > 0) {\n          textOptions->set(\"dpi\", descriptor->textDpi);\n        }\n        if (descriptor->textFont.length() > 0) {\n          textOptions->set(\"font\", const_cast<char*>(descriptor->textFont.data()));\n        }\n        if (descriptor->textFontfile.length() > 0) {\n          textOptions->set(\"fontfile\", const_cast<char*>(descriptor->textFontfile.data()));\n        }\n        image = VImage::text(const_cast<char *>(descriptor->textValue.data()), textOptions);\n        if (!descriptor->textRgba) {\n          image = image.copy(VImage::option()->set(\"interpretation\", VIPS_INTERPRETATION_B_W));\n        }\n        imageType = ImageType::RAW;\n      } else {\n        // From filesystem\n        imageType = DetermineImageType(descriptor->file.data());\n        if (imageType == ImageType::MISSING) {\n          if (descriptor->file.find(\"<svg\") != std::string::npos) {\n            throw vips::VError(\"Input file is missing, did you mean \"\n              \"sharp(Buffer.from('\" + descriptor->file.substr(0, 8) + \"...')?\");\n          }\n          throw vips::VError(\"Input file is missing: \" + descriptor->file);\n        }\n        if (imageType != ImageType::UNKNOWN) {\n          try {\n            vips::VOption *option = GetOptionsForImageType(imageType, descriptor);\n            image = VImage::new_from_file(descriptor->file.data(), option);\n            if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) {\n              image = SetDensity(image, descriptor->density);\n            }\n          } catch (vips::VError const &err) {\n            throw vips::VError(std::string(\"Input file has corrupt header: \") + err.what());\n          }\n        } else {\n          throw vips::VError(\"Input file contains unsupported image format\");\n        }\n      }\n    }\n\n    // Limit input images to a given number of pixels, where pixels = width * height\n    if (descriptor->limitInputPixels > 0 &&\n      static_cast<uint64_t>(image.width()) * image.height() > descriptor->limitInputPixels) {\n      throw vips::VError(\"Input image exceeds pixel limit\");\n    }\n    return std::make_tuple(image, imageType);\n  }\n\n  /*\n    Does this image have an embedded profile?\n  */\n  bool HasProfile(VImage image) {\n    return image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB;\n  }\n\n  /*\n    Get copy of embedded profile.\n  */\n  std::pair<char*, size_t> GetProfile(VImage image) {\n    std::pair<char*, size_t> icc(nullptr, 0);\n    if (HasProfile(image)) {\n      size_t length;\n      const void *data = image.get_blob(VIPS_META_ICC_NAME, &length);\n      icc.first = static_cast<char*>(g_malloc(length));\n      icc.second = length;\n      memcpy(icc.first, data, length);\n    }\n    return icc;\n  }\n\n  /*\n    Set embedded profile.\n  */\n  VImage SetProfile(VImage image, std::pair<char*, size_t> icc) {\n    if (icc.first != nullptr) {\n      image = image.copy();\n      image.set(VIPS_META_ICC_NAME, reinterpret_cast<VipsCallbackFn>(vips_area_free_cb), icc.first, icc.second);\n    }\n    return image;\n  }\n\n  static void* RemoveExifCallback(VipsImage *image, char const *field, GValue *value, void *data) {\n    std::vector<std::string> *fieldNames = static_cast<std::vector<std::string> *>(data);\n    std::string fieldName(field);\n    if (fieldName.substr(0, 8) == (\"exif-ifd\")) {\n      fieldNames->push_back(fieldName);\n    }\n    return nullptr;\n  }\n\n  /*\n    Remove all EXIF-related image fields.\n  */\n  VImage RemoveExif(VImage image) {\n    std::vector<std::string> fieldNames;\n    vips_image_map(image.get_image(), static_cast<VipsImageMapFn>(RemoveExifCallback), &fieldNames);\n    for (const auto& f : fieldNames) {\n      image.remove(f.data());\n    }\n    return image;\n  }\n\n  /*\n    Get EXIF Orientation of image, if any.\n  */\n  int ExifOrientation(VImage image) {\n    int orientation = 0;\n    if (image.get_typeof(VIPS_META_ORIENTATION) != 0) {\n      orientation = image.get_int(VIPS_META_ORIENTATION);\n    }\n    return orientation;\n  }\n\n  /*\n    Set EXIF Orientation of image.\n  */\n  VImage SetExifOrientation(VImage image, int const orientation) {\n    VImage copy = image.copy();\n    copy.set(VIPS_META_ORIENTATION, orientation);\n    return copy;\n  }\n\n  /*\n    Remove EXIF Orientation from image.\n  */\n  VImage RemoveExifOrientation(VImage image) {\n    VImage copy = image.copy();\n    copy.remove(VIPS_META_ORIENTATION);\n    copy.remove(\"exif-ifd0-Orientation\");\n    return copy;\n  }\n\n  /*\n    Set animation properties if necessary.\n  */\n  VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector<int> delay, int loop) {\n    bool hasDelay = !delay.empty();\n    VImage copy = image.copy();\n\n    // Only set page-height if we have more than one page, or this could\n    // accidentally turn into an animated image later.\n    if (nPages > 1) copy.set(VIPS_META_PAGE_HEIGHT, pageHeight);\n    if (hasDelay) {\n      if (delay.size() == 1) {\n        // We have just one delay, repeat that value for all frames.\n        delay.insert(delay.end(), nPages - 1, delay[0]);\n      }\n      copy.set(\"delay\", delay);\n    }\n    if (nPages == 1 && !hasDelay && loop == -1) {\n      loop = 1;\n    }\n    if (loop != -1) copy.set(\"loop\", loop);\n\n    return copy;\n  }\n\n  /*\n    Remove animation properties from image.\n  */\n  VImage RemoveAnimationProperties(VImage image) {\n    VImage copy = image.copy();\n    copy.remove(VIPS_META_PAGE_HEIGHT);\n    copy.remove(\"delay\");\n    copy.remove(\"loop\");\n    return copy;\n  }\n\n  /*\n    Remove GIF palette from image.\n  */\n  VImage RemoveGifPalette(VImage image) {\n    VImage copy = image.copy();\n    copy.remove(\"gif-palette\");\n    return copy;\n  }\n\n  /*\n    Does this image have a non-default density?\n  */\n  bool HasDensity(VImage image) {\n    return image.xres() > 1.0;\n  }\n\n  /*\n    Get pixels/mm resolution as pixels/inch density.\n  */\n  int GetDensity(VImage image) {\n    return static_cast<int>(round(image.xres() * 25.4));\n  }\n\n  /*\n    Set pixels/mm resolution based on a pixels/inch density.\n  */\n  VImage SetDensity(VImage image, const double density) {\n    const double pixelsPerMm = density / 25.4;\n    VImage copy = image.copy();\n    copy.get_image()->Xres = pixelsPerMm;\n    copy.get_image()->Yres = pixelsPerMm;\n    return copy;\n  }\n\n  /*\n    Multi-page images can have a page height. Fetch it, and sanity check it.\n    If page-height is not set, it defaults to the image height\n  */\n  int GetPageHeight(VImage image) {\n    return vips_image_get_page_height(image.get_image());\n  }\n\n  /*\n    Check the proposed format supports the current dimensions.\n  */\n  void AssertImageTypeDimensions(VImage image, ImageType const imageType) {\n    const int height = image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT\n      ? image.get_int(VIPS_META_PAGE_HEIGHT)\n      : image.height();\n    if (imageType == ImageType::JPEG) {\n      if (image.width() > 65535 || height > 65535) {\n        throw vips::VError(\"Processed image is too large for the JPEG format\");\n      }\n    } else if (imageType == ImageType::WEBP) {\n      if (image.width() > 16383 || height > 16383) {\n        throw vips::VError(\"Processed image is too large for the WebP format\");\n      }\n    } else if (imageType == ImageType::GIF) {\n      if (image.width() > 65535 || height > 65535) {\n        throw vips::VError(\"Processed image is too large for the GIF format\");\n      }\n    } else if (imageType == ImageType::HEIF) {\n      if (image.width() > 16384 || height > 16384) {\n        throw vips::VError(\"Processed image is too large for the HEIF format\");\n      }\n    }\n  }\n\n  /*\n    Called when a Buffer undergoes GC, required to support mixed runtime libraries in Windows\n  */\n  std::function<void(void*, char*)> FreeCallback = [](void*, char* data) {\n    g_free(data);\n  };\n\n  /*\n    Temporary buffer of warnings\n  */\n  std::queue<std::string> vipsWarnings;\n  std::mutex vipsWarningsMutex;\n\n  /*\n    Called with warnings from the glib-registered \"VIPS\" domain\n  */\n  void VipsWarningCallback(char const* log_domain, GLogLevelFlags log_level, char const* message, void* ignore) {\n    std::lock_guard<std::mutex> lock(vipsWarningsMutex);\n    vipsWarnings.emplace(message);\n  }\n\n  /*\n    Pop the oldest warning message from the queue\n  */\n  std::string VipsWarningPop() {\n    std::string warning;\n    std::lock_guard<std::mutex> lock(vipsWarningsMutex);\n    if (!vipsWarnings.empty()) {\n      warning = vipsWarnings.front();\n      vipsWarnings.pop();\n    }\n    return warning;\n  }\n\n  /*\n    Attach an event listener for progress updates, used to detect timeout\n  */\n  void SetTimeout(VImage image, int const seconds) {\n    if (seconds > 0) {\n      VipsImage *im = image.get_image();\n      if (im->progress_signal == NULL) {\n        int *timeout = VIPS_NEW(im, int);\n        *timeout = seconds;\n        g_signal_connect(im, \"eval\", G_CALLBACK(VipsProgressCallBack), timeout);\n        vips_image_set_progress(im, true);\n      }\n    }\n  }\n\n  /*\n    Event listener for progress updates, used to detect timeout\n  */\n  void VipsProgressCallBack(VipsImage *im, VipsProgress *progress, int *timeout) {\n    if (*timeout > 0 && progress->run >= *timeout) {\n      vips_image_set_kill(im, true);\n      vips_error(\"timeout\", \"%d%% complete\", progress->percent);\n      *timeout = 0;\n    }\n  }\n\n  /*\n    Calculate the (left, top) coordinates of the output image\n    within the input image, applying the given gravity during an embed.\n\n    @Azurebyte: We are basically swapping the inWidth and outWidth, inHeight and outHeight from the CalculateCrop function.\n  */\n  std::tuple<int, int> CalculateEmbedPosition(int const inWidth, int const inHeight,\n    int const outWidth, int const outHeight, int const gravity) {\n\n    int left = 0;\n    int top = 0;\n    switch (gravity) {\n      case 1:\n        // North\n        left = (outWidth - inWidth) / 2;\n        break;\n      case 2:\n        // East\n        left = outWidth - inWidth;\n        top = (outHeight - inHeight) / 2;\n        break;\n      case 3:\n        // South\n        left = (outWidth - inWidth) / 2;\n        top = outHeight - inHeight;\n        break;\n      case 4:\n        // West\n        top = (outHeight - inHeight) / 2;\n        break;\n      case 5:\n        // Northeast\n        left = outWidth - inWidth;\n        break;\n      case 6:\n        // Southeast\n        left = outWidth - inWidth;\n        top = outHeight - inHeight;\n        break;\n      case 7:\n        // Southwest\n        top = outHeight - inHeight;\n        break;\n      case 8:\n        // Northwest\n        // Which is the default is 0,0 so we do not assign anything here.\n        break;\n      default:\n        // Centre\n        left = (outWidth - inWidth) / 2;\n        top = (outHeight - inHeight) / 2;\n    }\n    return std::make_tuple(left, top);\n  }\n\n  /*\n    Calculate the (left, top) coordinates of the output image\n    within the input image, applying the given gravity during a crop.\n  */\n  std::tuple<int, int> CalculateCrop(int const inWidth, int const inHeight,\n    int const outWidth, int const outHeight, int const gravity) {\n\n    int left = 0;\n    int top = 0;\n    switch (gravity) {\n      case 1:\n        // North\n        left = (inWidth - outWidth + 1) / 2;\n        break;\n      case 2:\n        // East\n        left = inWidth - outWidth;\n        top = (inHeight - outHeight + 1) / 2;\n        break;\n      case 3:\n        // South\n        left = (inWidth - outWidth + 1) / 2;\n        top = inHeight - outHeight;\n        break;\n      case 4:\n        // West\n        top = (inHeight - outHeight + 1) / 2;\n        break;\n      case 5:\n        // Northeast\n        left = inWidth - outWidth;\n        break;\n      case 6:\n        // Southeast\n        left = inWidth - outWidth;\n        top = inHeight - outHeight;\n        break;\n      case 7:\n        // Southwest\n        top = inHeight - outHeight;\n        break;\n      case 8:\n        // Northwest\n        break;\n      default:\n        // Centre\n        left = (inWidth - outWidth + 1) / 2;\n        top = (inHeight - outHeight + 1) / 2;\n    }\n    return std::make_tuple(left, top);\n  }\n\n  /*\n    Calculate the (left, top) coordinates of the output image\n    within the input image, applying the given x and y offsets.\n  */\n  std::tuple<int, int> CalculateCrop(int const inWidth, int const inHeight,\n    int const outWidth, int const outHeight, int const x, int const y) {\n\n    // default values\n    int left = 0;\n    int top = 0;\n\n    // assign only if valid\n    if (x < (inWidth - outWidth)) {\n      left = x;\n    } else if (x >= (inWidth - outWidth)) {\n      left = inWidth - outWidth;\n    }\n\n    if (y < (inHeight - outHeight)) {\n      top = y;\n    } else if (y >= (inHeight - outHeight)) {\n      top = inHeight - outHeight;\n    }\n\n    return std::make_tuple(left, top);\n  }\n\n  /*\n    Are pixel values in this image 16-bit integer?\n  */\n  bool Is16Bit(VipsInterpretation const interpretation) {\n    return interpretation == VIPS_INTERPRETATION_RGB16 || interpretation == VIPS_INTERPRETATION_GREY16;\n  }\n\n  /*\n    Convert RGBA value to another colourspace\n  */\n  std::vector<double> GetRgbaAsColourspace(std::vector<double> const rgba,\n    VipsInterpretation const interpretation, bool premultiply) {\n    int const bands = static_cast<int>(rgba.size());\n    if (bands < 3) {\n      return rgba;\n    }\n    VImage pixel = VImage::new_matrix(1, 1);\n    pixel.set(\"bands\", bands);\n    pixel = pixel\n      .new_from_image(rgba)\n      .colourspace(interpretation, VImage::option()->set(\"source_space\", VIPS_INTERPRETATION_sRGB));\n    if (premultiply) {\n      pixel = pixel.premultiply();\n    }\n    return pixel(0, 0);\n  }\n\n  /*\n    Apply the alpha channel to a given colour\n  */\n  std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour, bool premultiply) {\n    // Scale up 8-bit values to match 16-bit input image\n    double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0;\n    // Create alphaColour colour\n    std::vector<double> alphaColour;\n    if (image.bands() > 2) {\n      alphaColour = {\n        multiplier * colour[0],\n        multiplier * colour[1],\n        multiplier * colour[2]\n      };\n    } else {\n      // Convert sRGB to greyscale\n      alphaColour = { multiplier * (\n        0.2126 * colour[0] +\n        0.7152 * colour[1] +\n        0.0722 * colour[2])\n      };\n    }\n    // Add alpha channel(s) to alphaColour colour\n    if (colour[3] < 255.0 || image.has_alpha()) {\n      int extraBands = image.bands() > 4 ? image.bands() - 3 : 1;\n      alphaColour.insert(alphaColour.end(), extraBands, colour[3] * multiplier);\n    }\n    // Ensure alphaColour colour uses correct colourspace\n    alphaColour = sharp::GetRgbaAsColourspace(alphaColour, image.interpretation(), premultiply);\n    // Add non-transparent alpha channel, if required\n    if (colour[3] < 255.0 && !image.has_alpha()) {\n      image = image.bandjoin_const({ 255 * multiplier });\n    }\n    return std::make_tuple(image, alphaColour);\n  }\n\n  /*\n    Removes alpha channels, if any.\n  */\n  VImage RemoveAlpha(VImage image) {\n    while (image.bands() > 1 && image.has_alpha()) {\n      image = image.extract_band(0, VImage::option()->set(\"n\", image.bands() - 1));\n    }\n    return image;\n  }\n\n  /*\n    Ensures alpha channel, if missing.\n  */\n  VImage EnsureAlpha(VImage image, double const value) {\n    if (!image.has_alpha()) {\n      image = image.bandjoin_const({ value * vips_interpretation_max_alpha(image.interpretation()) });\n    }\n    return image;\n  }\n\n  std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,\n    Canvas canvas, bool withoutEnlargement, bool withoutReduction) {\n    double hshrink = 1.0;\n    double vshrink = 1.0;\n\n    if (targetWidth > 0 && targetHeight > 0) {\n      // Fixed width and height\n      hshrink = static_cast<double>(width) / targetWidth;\n      vshrink = static_cast<double>(height) / targetHeight;\n\n      switch (canvas) {\n        case Canvas::CROP:\n        case Canvas::MIN:\n          if (hshrink < vshrink) {\n            vshrink = hshrink;\n          } else {\n            hshrink = vshrink;\n          }\n          break;\n        case Canvas::EMBED:\n        case Canvas::MAX:\n          if (hshrink > vshrink) {\n            vshrink = hshrink;\n          } else {\n            hshrink = vshrink;\n          }\n          break;\n        case Canvas::IGNORE_ASPECT:\n          break;\n      }\n    } else if (targetWidth > 0) {\n      // Fixed width\n      hshrink = static_cast<double>(width) / targetWidth;\n\n      if (canvas != Canvas::IGNORE_ASPECT) {\n        // Auto height\n        vshrink = hshrink;\n      }\n    } else if (targetHeight > 0) {\n      // Fixed height\n      vshrink = static_cast<double>(height) / targetHeight;\n\n      if (canvas != Canvas::IGNORE_ASPECT) {\n        // Auto width\n        hshrink = vshrink;\n      }\n    }\n\n    // We should not reduce or enlarge the output image, if\n    // withoutReduction or withoutEnlargement is specified.\n    if (withoutReduction) {\n      // Equivalent of VIPS_SIZE_UP\n      hshrink = std::min(1.0, hshrink);\n      vshrink = std::min(1.0, vshrink);\n    } else if (withoutEnlargement) {\n      // Equivalent of VIPS_SIZE_DOWN\n      hshrink = std::max(1.0, hshrink);\n      vshrink = std::max(1.0, vshrink);\n    }\n\n    // We don't want to shrink so much that we send an axis to 0\n    hshrink = std::min(hshrink, static_cast<double>(width));\n    vshrink = std::min(vshrink, static_cast<double>(height));\n\n    return std::make_pair(hshrink, vshrink);\n  }\n\n  /*\n    Ensure decoding remains sequential.\n  */\n  VImage StaySequential(VImage image, bool condition) {\n    if (vips_image_is_sequential(image.get_image()) && condition) {\n      image = image.copy_memory().copy();\n      image.remove(VIPS_META_SEQUENTIAL);\n    }\n    return image;\n  }\n}  // namespace sharp\n"
  },
  {
    "path": "src/common.h",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#ifndef SRC_COMMON_H_\n#define SRC_COMMON_H_\n\n#include <atomic>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include <napi.h>\n#include <vips/vips8>\n\n// Verify platform and compiler compatibility\n\n#if (VIPS_MAJOR_VERSION < 8) || \\\n  (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 17) || \\\n  (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 17 && VIPS_MICRO_VERSION < 3)\n#error \"libvips version 8.17.3+ is required - please see https://sharp.pixelplumbing.com/install\"\n#endif\n\n#if defined(__has_include)\n#if !__has_include(<filesystem>)\n#error \"C++17 compiler required - please see https://sharp.pixelplumbing.com/install\"\n#endif\n#endif\n\nusing vips::VImage;\n\nnamespace sharp {\n\n  struct InputDescriptor {\n    std::string name;\n    std::string file;\n    bool autoOrient;\n    char *buffer;\n    VipsFailOn failOn;\n    uint64_t limitInputPixels;\n    bool unlimited;\n    VipsAccess access;\n    size_t bufferLength;\n    bool isBuffer;\n    double density;\n    bool ignoreIcc;\n    VipsBandFormat rawDepth;\n    int rawChannels;\n    int rawWidth;\n    int rawHeight;\n    bool rawPremultiplied;\n    int rawPageHeight;\n    int pages;\n    int page;\n    int createChannels;\n    int createWidth;\n    int createHeight;\n    int createPageHeight;\n    std::vector<double> createBackground;\n    std::string createNoiseType;\n    double createNoiseMean;\n    double createNoiseSigma;\n    std::string textValue;\n    std::string textFont;\n    std::string textFontfile;\n    int textWidth;\n    int textHeight;\n    VipsAlign textAlign;\n    bool textJustify;\n    int textDpi;\n    bool textRgba;\n    int textSpacing;\n    VipsTextWrap textWrap;\n    int textAutofitDpi;\n    bool joinAnimated;\n    int joinAcross;\n    int joinShim;\n    std::vector<double> joinBackground;\n    VipsAlign joinHalign;\n    VipsAlign joinValign;\n    std::string svgStylesheet;\n    bool svgHighBitdepth;\n    int tiffSubifd;\n    int openSlideLevel;\n    std::vector<double> pdfBackground;\n    bool jp2Oneshot;\n\n    InputDescriptor():\n      autoOrient(false),\n      buffer(nullptr),\n      failOn(VIPS_FAIL_ON_WARNING),\n      limitInputPixels(0x3FFF * 0x3FFF),\n      unlimited(false),\n      access(VIPS_ACCESS_SEQUENTIAL),\n      bufferLength(0),\n      isBuffer(false),\n      density(72.0),\n      ignoreIcc(false),\n      rawDepth(VIPS_FORMAT_UCHAR),\n      rawChannels(0),\n      rawWidth(0),\n      rawHeight(0),\n      rawPremultiplied(false),\n      rawPageHeight(0),\n      pages(1),\n      page(0),\n      createChannels(0),\n      createWidth(0),\n      createHeight(0),\n      createPageHeight(0),\n      createBackground{ 0.0, 0.0, 0.0, 255.0 },\n      createNoiseMean(0.0),\n      createNoiseSigma(0.0),\n      textWidth(0),\n      textHeight(0),\n      textAlign(VIPS_ALIGN_LOW),\n      textJustify(false),\n      textDpi(72),\n      textRgba(false),\n      textSpacing(0),\n      textWrap(VIPS_TEXT_WRAP_WORD),\n      textAutofitDpi(0),\n      joinAnimated(false),\n      joinAcross(1),\n      joinShim(0),\n      joinBackground{ 0.0, 0.0, 0.0, 255.0 },\n      joinHalign(VIPS_ALIGN_LOW),\n      joinValign(VIPS_ALIGN_LOW),\n      svgHighBitdepth(false),\n      tiffSubifd(-1),\n      openSlideLevel(0),\n      pdfBackground{ 255.0, 255.0, 255.0, 255.0 },\n      jp2Oneshot(false) {}\n  };\n\n  // Convenience methods to access the attributes of a Napi::Object\n  bool HasAttr(Napi::Object obj, std::string attr);\n  std::string AttrAsStr(Napi::Object obj, std::string attr);\n  std::string AttrAsStr(Napi::Object obj, unsigned int const attr);\n  uint32_t AttrAsUint32(Napi::Object obj, std::string attr);\n  int32_t AttrAsInt32(Napi::Object obj, std::string attr);\n  int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr);\n  double AttrAsDouble(Napi::Object obj, std::string attr);\n  double AttrAsDouble(Napi::Object obj, unsigned int const attr);\n  bool AttrAsBool(Napi::Object obj, std::string attr);\n  std::vector<double> AttrAsVectorOfDouble(Napi::Object obj, std::string attr);\n  std::vector<int32_t> AttrAsInt32Vector(Napi::Object obj, std::string attr);\n  template <class T> T AttrAsEnum(Napi::Object obj, std::string attr, GType type) {\n    return static_cast<T>(\n      vips_enum_from_nick(nullptr, type, AttrAsStr(obj, attr).data()));\n  }\n\n  // Create an InputDescriptor instance from a Napi::Object describing an input image\n  InputDescriptor* CreateInputDescriptor(Napi::Object input);\n\n  enum class ImageType {\n    JPEG,\n    PNG,\n    WEBP,\n    JP2,\n    TIFF,\n    GIF,\n    SVG,\n    HEIF,\n    PDF,\n    MAGICK,\n    OPENSLIDE,\n    PPM,\n    FITS,\n    EXR,\n    JXL,\n    RAD,\n    DCRAW,\n    VIPS,\n    RAW,\n    UNKNOWN,\n    MISSING\n  };\n\n  enum class Canvas {\n      CROP,\n      EMBED,\n      MAX,\n      MIN,\n      IGNORE_ASPECT\n  };\n\n  // How many tasks are in the queue?\n  extern std::atomic<int> counterQueue;\n\n  // How many tasks are being processed?\n  extern std::atomic<int> counterProcess;\n\n  // Filename extension checkers\n  bool IsJpeg(std::string const &str);\n  bool IsPng(std::string const &str);\n  bool IsWebp(std::string const &str);\n  bool IsJp2(std::string const &str);\n  bool IsGif(std::string const &str);\n  bool IsTiff(std::string const &str);\n  bool IsHeic(std::string const &str);\n  bool IsHeif(std::string const &str);\n  bool IsAvif(std::string const &str);\n  bool IsJxl(std::string const &str);\n  bool IsDz(std::string const &str);\n  bool IsDzZip(std::string const &str);\n  bool IsV(std::string const &str);\n\n  /*\n    Trim space from end of string.\n  */\n  std::string TrimEnd(std::string const &str);\n\n  /*\n    Provide a string identifier for the given image type.\n  */\n  std::string ImageTypeId(ImageType const imageType);\n\n  /*\n    Determine image format of a buffer.\n  */\n  ImageType DetermineImageType(void *buffer, size_t const length);\n\n  /*\n    Determine image format of a file.\n  */\n  ImageType DetermineImageType(char const *file);\n\n  /*\n    Format-specific options builder\n  */\n  vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor);\n\n  /*\n    Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data)\n  */\n  std::tuple<VImage, ImageType> OpenInput(InputDescriptor *descriptor);\n\n  /*\n    Does this image have an embedded profile?\n  */\n  bool HasProfile(VImage image);\n\n  /*\n    Get copy of embedded profile.\n  */\n  std::pair<char*, size_t> GetProfile(VImage image);\n\n  /*\n    Set embedded profile.\n  */\n  VImage SetProfile(VImage image, std::pair<char*, size_t> icc);\n\n  /*\n    Remove all EXIF-related image fields.\n  */\n  VImage RemoveExif(VImage image);\n\n  /*\n    Get EXIF Orientation of image, if any.\n  */\n  int ExifOrientation(VImage image);\n\n  /*\n    Set EXIF Orientation of image.\n  */\n  VImage SetExifOrientation(VImage image, int const orientation);\n\n  /*\n    Remove EXIF Orientation from image.\n  */\n  VImage RemoveExifOrientation(VImage image);\n\n  /*\n    Set animation properties if necessary.\n  */\n  VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector<int> delay, int loop);\n\n  /*\n    Remove animation properties from image.\n  */\n  VImage RemoveAnimationProperties(VImage image);\n\n  /*\n    Remove GIF palette from image.\n  */\n  VImage RemoveGifPalette(VImage image);\n\n  /*\n    Does this image have a non-default density?\n  */\n  bool HasDensity(VImage image);\n\n  /*\n    Get pixels/mm resolution as pixels/inch density.\n  */\n  int GetDensity(VImage image);\n\n  /*\n    Set pixels/mm resolution based on a pixels/inch density.\n  */\n  VImage SetDensity(VImage image, const double density);\n\n  /*\n    Multi-page images can have a page height. Fetch it, and sanity check it.\n    If page-height is not set, it defaults to the image height\n  */\n  int GetPageHeight(VImage image);\n\n  /*\n    Check the proposed format supports the current dimensions.\n  */\n  void AssertImageTypeDimensions(VImage image, ImageType const imageType);\n\n  /*\n    Called when a Buffer undergoes GC, required to support mixed runtime libraries in Windows\n  */\n  extern std::function<void(void*, char*)> FreeCallback;\n\n  /*\n    Called with warnings from the glib-registered \"VIPS\" domain\n  */\n  void VipsWarningCallback(char const* log_domain, GLogLevelFlags log_level, char const* message, void* ignore);\n\n  /*\n    Pop the oldest warning message from the queue\n  */\n  std::string VipsWarningPop();\n\n  /*\n    Attach an event listener for progress updates, used to detect timeout\n  */\n  void SetTimeout(VImage image, int const timeoutSeconds);\n\n  /*\n    Event listener for progress updates, used to detect timeout\n  */\n  void VipsProgressCallBack(VipsImage *image, VipsProgress *progress, int *timeoutSeconds);\n\n  /*\n    Calculate the (left, top) coordinates of the output image\n    within the input image, applying the given gravity during an embed.\n  */\n  std::tuple<int, int> CalculateEmbedPosition(int const inWidth, int const inHeight,\n    int const outWidth, int const outHeight, int const gravity);\n\n  /*\n    Calculate the (left, top) coordinates of the output image\n    within the input image, applying the given gravity.\n  */\n  std::tuple<int, int> CalculateCrop(int const inWidth, int const inHeight,\n    int const outWidth, int const outHeight, int const gravity);\n\n  /*\n    Calculate the (left, top) coordinates of the output image\n    within the input image, applying the given x and y offsets of the output image.\n  */\n  std::tuple<int, int> CalculateCrop(int const inWidth, int const inHeight,\n    int const outWidth, int const outHeight, int const x, int const y);\n\n  /*\n    Are pixel values in this image 16-bit integer?\n  */\n  bool Is16Bit(VipsInterpretation const interpretation);\n\n  /*\n    Convert RGBA value to another colourspace\n  */\n  std::vector<double> GetRgbaAsColourspace(std::vector<double> const rgba,\n    VipsInterpretation const interpretation, bool premultiply);\n\n  /*\n    Apply the alpha channel to a given colour\n   */\n  std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour, bool premultiply);\n\n  /*\n    Removes alpha channels, if any.\n  */\n  VImage RemoveAlpha(VImage image);\n\n  /*\n    Ensures alpha channel, if missing.\n  */\n  VImage EnsureAlpha(VImage image, double const value);\n\n  /*\n    Calculate the horizontal and vertical shrink factors, taking the canvas mode into account.\n  */\n  std::pair<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight,\n    Canvas canvas, bool withoutEnlargement, bool withoutReduction);\n\n  /*\n    Ensure decoding remains sequential.\n  */\n  VImage StaySequential(VImage image, bool condition = true);\n\n}  // namespace sharp\n\n#endif  // SRC_COMMON_H_\n"
  },
  {
    "path": "src/emscripten/common.gypi",
    "content": "# Copyright 2013 Lovell Fuller and others.\n# SPDX-License-Identifier: Apache-2.0\n\n{\n  'variables': {\n    'OS': 'emscripten'\n  },\n  'target_defaults': {\n    'default_configuration': 'Release',\n    'type': 'executable',\n    'cflags': [\n      '-pthread'\n    ],\n    'cflags_cc': [\n      '-pthread'\n    ],\n    'ldflags': [\n      '--js-library=<!(node -p \"require(\\'emnapi\\').js_library\")',\n      '-sAUTO_JS_LIBRARIES=0',\n      '-sAUTO_NATIVE_LIBRARIES=0',\n      '-sDEFAULT_TO_CXX=0',\n      '-sNODEJS_CATCH_REJECTION=0'\n    ],\n    'defines': [\n      '__STDC_FORMAT_MACROS',\n      'BUILDING_NODE_EXTENSION',\n      'EMNAPI_WORKER_POOL_SIZE=1'\n    ],\n    'include_dirs': [\n      '<!(node -p \"require(\\'emnapi\\').include_dir\")'\n    ],\n    'sources': [\n      '<!@(node -p \"require(\\'emnapi\\').sources.map(x => JSON.stringify(path.relative(process.cwd(), x))).join(\\' \\')\")'\n    ],\n    'configurations': {\n      'Release': {}\n    }\n  }\n}\n"
  },
  {
    "path": "src/emscripten/pre.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n/* global Module, ENV, _vips_shutdown, _uv_library_shutdown */\n\nModule.preRun = () => {\n  ENV.VIPS_CONCURRENCY = Number(process.env.VIPS_CONCURRENCY) || 1;\n};\n\nModule.onRuntimeInitialized = () => {\n  module.exports = Module.emnapiInit({\n    context: require('@emnapi/runtime').getDefaultContext()\n  });\n\n  process.once('exit', () => {\n    _vips_shutdown();\n    _uv_library_shutdown();\n  });\n};\n"
  },
  {
    "path": "src/metadata.cc",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#include <cmath>\n#include <numeric>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <napi.h>\n#include <vips/vips8>\n\n#include \"./common.h\"\n#include \"./metadata.h\"\n\nstatic void* readPNGComment(VipsImage *image, const char *field, GValue *value, void *p);\n\nclass MetadataWorker : public Napi::AsyncWorker {\n public:\n  MetadataWorker(Napi::Function callback, MetadataBaton *baton, Napi::Function debuglog) :\n    Napi::AsyncWorker(callback), baton(baton), debuglog(Napi::Persistent(debuglog)) {}\n  ~MetadataWorker() {}\n\n  void Execute() {\n    // Decrement queued task counter\n    sharp::counterQueue--;\n\n    vips::VImage image;\n    sharp::ImageType imageType = sharp::ImageType::UNKNOWN;\n    try {\n      std::tie(image, imageType) = OpenInput(baton->input);\n    } catch (vips::VError const &err) {\n      (baton->err).append(err.what());\n    }\n    if (imageType != sharp::ImageType::UNKNOWN) {\n      // Image type\n      baton->format = sharp::ImageTypeId(imageType);\n      // VipsImage attributes\n      baton->width = image.width();\n      baton->height = image.height();\n      baton->space = vips_enum_nick(VIPS_TYPE_INTERPRETATION, image.interpretation());\n      baton->channels = image.bands();\n      baton->depth = vips_enum_nick(VIPS_TYPE_BAND_FORMAT, image.format());\n      if (sharp::HasDensity(image)) {\n        baton->density = sharp::GetDensity(image);\n      }\n      if (image.get_typeof(\"jpeg-chroma-subsample\") == VIPS_TYPE_REF_STRING) {\n        baton->chromaSubsampling = image.get_string(\"jpeg-chroma-subsample\");\n      }\n      if (image.get_typeof(\"interlaced\") == G_TYPE_INT) {\n        baton->isProgressive = image.get_int(\"interlaced\") == 1;\n      }\n      if (image.get_typeof(VIPS_META_PALETTE) == G_TYPE_INT) {\n        baton->isPalette = image.get_int(VIPS_META_PALETTE);\n      }\n      if (image.get_typeof(VIPS_META_BITS_PER_SAMPLE) == G_TYPE_INT) {\n        baton->bitsPerSample = image.get_int(VIPS_META_BITS_PER_SAMPLE);\n      }\n      if (image.get_typeof(VIPS_META_N_PAGES) == G_TYPE_INT) {\n        baton->pages = image.get_int(VIPS_META_N_PAGES);\n      }\n      if (image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT) {\n        baton->pageHeight = image.get_int(VIPS_META_PAGE_HEIGHT);\n      }\n      if (image.get_typeof(\"loop\") == G_TYPE_INT) {\n        baton->loop = image.get_int(\"loop\");\n      }\n      if (image.get_typeof(\"delay\") == VIPS_TYPE_ARRAY_INT) {\n        baton->delay = image.get_array_int(\"delay\");\n      }\n      if (image.get_typeof(\"heif-primary\") == G_TYPE_INT) {\n        baton->pagePrimary = image.get_int(\"heif-primary\");\n      }\n      if (image.get_typeof(\"heif-compression\") == VIPS_TYPE_REF_STRING) {\n        baton->compression = image.get_string(\"heif-compression\");\n      }\n      if (image.get_typeof(VIPS_META_RESOLUTION_UNIT) == VIPS_TYPE_REF_STRING) {\n        baton->resolutionUnit = image.get_string(VIPS_META_RESOLUTION_UNIT);\n      }\n      if (image.get_typeof(\"magick-format\") == VIPS_TYPE_REF_STRING) {\n        baton->formatMagick = image.get_string(\"magick-format\");\n      }\n      if (image.get_typeof(\"openslide.level-count\") == VIPS_TYPE_REF_STRING) {\n        int const levels = std::stoi(image.get_string(\"openslide.level-count\"));\n        for (int l = 0; l < levels; l++) {\n          std::string prefix = \"openslide.level[\" + std::to_string(l) + \"].\";\n          int const width = std::stoi(image.get_string((prefix + \"width\").data()));\n          int const height = std::stoi(image.get_string((prefix + \"height\").data()));\n          baton->levels.push_back(std::pair<int, int>(width, height));\n        }\n      }\n      if (image.get_typeof(VIPS_META_N_SUBIFDS) == G_TYPE_INT) {\n        baton->subifds = image.get_int(VIPS_META_N_SUBIFDS);\n      }\n      baton->hasProfile = sharp::HasProfile(image);\n      if (image.get_typeof(\"background\") == VIPS_TYPE_ARRAY_DOUBLE) {\n        baton->background = image.get_array_double(\"background\");\n      }\n      // Derived attributes\n      baton->hasAlpha = image.has_alpha();\n      baton->orientation = sharp::ExifOrientation(image);\n      // EXIF\n      if (image.get_typeof(VIPS_META_EXIF_NAME) == VIPS_TYPE_BLOB) {\n        size_t exifLength;\n        void const *exif = image.get_blob(VIPS_META_EXIF_NAME, &exifLength);\n        baton->exif = static_cast<char*>(g_malloc(exifLength));\n        memcpy(baton->exif, exif, exifLength);\n        baton->exifLength = exifLength;\n      }\n      // ICC profile\n      if (image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB) {\n        size_t iccLength;\n        void const *icc = image.get_blob(VIPS_META_ICC_NAME, &iccLength);\n        baton->icc = static_cast<char*>(g_malloc(iccLength));\n        memcpy(baton->icc, icc, iccLength);\n        baton->iccLength = iccLength;\n      }\n      // IPTC\n      if (image.get_typeof(VIPS_META_IPTC_NAME) == VIPS_TYPE_BLOB) {\n        size_t iptcLength;\n        void const *iptc = image.get_blob(VIPS_META_IPTC_NAME, &iptcLength);\n        baton->iptc = static_cast<char *>(g_malloc(iptcLength));\n        memcpy(baton->iptc, iptc, iptcLength);\n        baton->iptcLength = iptcLength;\n      }\n      // XMP\n      if (image.get_typeof(VIPS_META_XMP_NAME) == VIPS_TYPE_BLOB) {\n        size_t xmpLength;\n        void const *xmp = image.get_blob(VIPS_META_XMP_NAME, &xmpLength);\n        baton->xmp = static_cast<char *>(g_malloc(xmpLength));\n        memcpy(baton->xmp, xmp, xmpLength);\n        baton->xmpLength = xmpLength;\n      }\n      // TIFFTAG_PHOTOSHOP\n      if (image.get_typeof(VIPS_META_PHOTOSHOP_NAME) == VIPS_TYPE_BLOB) {\n        size_t tifftagPhotoshopLength;\n        void const *tifftagPhotoshop = image.get_blob(VIPS_META_PHOTOSHOP_NAME, &tifftagPhotoshopLength);\n        baton->tifftagPhotoshop = static_cast<char *>(g_malloc(tifftagPhotoshopLength));\n        memcpy(baton->tifftagPhotoshop, tifftagPhotoshop, tifftagPhotoshopLength);\n        baton->tifftagPhotoshopLength = tifftagPhotoshopLength;\n      }\n      // PNG comments\n      vips_image_map(image.get_image(), readPNGComment, &baton->comments);\n    }\n\n    // Clean up\n    vips_error_clear();\n    vips_thread_shutdown();\n  }\n\n  void OnOK() {\n    Napi::Env env = Env();\n    Napi::HandleScope scope(env);\n\n    // Handle warnings\n    std::string warning = sharp::VipsWarningPop();\n    while (!warning.empty()) {\n      debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) });\n      warning = sharp::VipsWarningPop();\n    }\n\n    if (baton->err.empty()) {\n      Napi::Object info = Napi::Object::New(env);\n      info.Set(\"format\", baton->format);\n      if (baton->input->bufferLength > 0) {\n        info.Set(\"size\", baton->input->bufferLength);\n      }\n      info.Set(\"width\", baton->width);\n      info.Set(\"height\", baton->height);\n      info.Set(\"space\", baton->space);\n      info.Set(\"channels\", baton->channels);\n      info.Set(\"depth\", baton->depth);\n      if (baton->density > 0) {\n        info.Set(\"density\", baton->density);\n      }\n      if (!baton->chromaSubsampling.empty()) {\n        info.Set(\"chromaSubsampling\", baton->chromaSubsampling);\n      }\n      info.Set(\"isProgressive\", baton->isProgressive);\n      info.Set(\"isPalette\", baton->isPalette);\n      if (baton->bitsPerSample > 0) {\n        info.Set(\"bitsPerSample\", baton->bitsPerSample);\n        if (baton->isPalette) {\n          // Deprecated, remove with libvips 8.17.0\n          info.Set(\"paletteBitDepth\", baton->bitsPerSample);\n        }\n      }\n      if (baton->pages > 0) {\n        info.Set(\"pages\", baton->pages);\n      }\n      if (baton->pageHeight > 0) {\n        info.Set(\"pageHeight\", baton->pageHeight);\n      }\n      if (baton->loop >= 0) {\n        info.Set(\"loop\", baton->loop);\n      }\n      if (!baton->delay.empty()) {\n        int i = 0;\n        Napi::Array delay = Napi::Array::New(env, static_cast<size_t>(baton->delay.size()));\n        for (int const d : baton->delay) {\n          delay.Set(i++, d);\n        }\n        info.Set(\"delay\", delay);\n      }\n      if (baton->pagePrimary > -1) {\n        info.Set(\"pagePrimary\", baton->pagePrimary);\n      }\n      if (!baton->compression.empty()) {\n        info.Set(\"compression\", baton->compression);\n      }\n      if (!baton->resolutionUnit.empty()) {\n        info.Set(\"resolutionUnit\", baton->resolutionUnit == \"in\" ? \"inch\" : baton->resolutionUnit);\n      }\n      if (!baton->formatMagick.empty()) {\n        info.Set(\"formatMagick\", baton->formatMagick);\n      }\n      if (!baton->levels.empty()) {\n        int i = 0;\n        Napi::Array levels = Napi::Array::New(env, static_cast<size_t>(baton->levels.size()));\n        for (const auto& [width, height] : baton->levels) {\n          Napi::Object level = Napi::Object::New(env);\n          level.Set(\"width\", width);\n          level.Set(\"height\", height);\n          levels.Set(i++, level);\n        }\n        info.Set(\"levels\", levels);\n      }\n      if (baton->subifds > 0) {\n        info.Set(\"subifds\", baton->subifds);\n      }\n      if (!baton->background.empty()) {\n        Napi::Object background = Napi::Object::New(env);\n        if (baton->background.size() == 3) {\n          background.Set(\"r\", baton->background[0]);\n          background.Set(\"g\", baton->background[1]);\n          background.Set(\"b\", baton->background[2]);\n        } else {\n          background.Set(\"gray\", round(baton->background[0] * 100 / 255));\n        }\n        info.Set(\"background\", background);\n      }\n      info.Set(\"hasProfile\", baton->hasProfile);\n      info.Set(\"hasAlpha\", baton->hasAlpha);\n      if (baton->orientation > 0) {\n        info.Set(\"orientation\", baton->orientation);\n      }\n      Napi::Object autoOrient = Napi::Object::New(env);\n      info.Set(\"autoOrient\", autoOrient);\n      if (baton->orientation >= 5) {\n        autoOrient.Set(\"width\", baton->height);\n        autoOrient.Set(\"height\", baton->width);\n      } else {\n        autoOrient.Set(\"width\", baton->width);\n        autoOrient.Set(\"height\", baton->height);\n      }\n      if (baton->exifLength > 0) {\n        info.Set(\"exif\", Napi::Buffer<char>::NewOrCopy(env, baton->exif, baton->exifLength, sharp::FreeCallback));\n      }\n      if (baton->iccLength > 0) {\n        info.Set(\"icc\", Napi::Buffer<char>::NewOrCopy(env, baton->icc, baton->iccLength, sharp::FreeCallback));\n      }\n      if (baton->iptcLength > 0) {\n        info.Set(\"iptc\", Napi::Buffer<char>::NewOrCopy(env, baton->iptc, baton->iptcLength, sharp::FreeCallback));\n      }\n      if (baton->xmpLength > 0) {\n        if (g_utf8_validate(static_cast<char const *>(baton->xmp), baton->xmpLength, nullptr)) {\n          info.Set(\"xmpAsString\",\n            Napi::String::New(env, static_cast<char const *>(baton->xmp), baton->xmpLength));\n        }\n        info.Set(\"xmp\", Napi::Buffer<char>::NewOrCopy(env, baton->xmp, baton->xmpLength, sharp::FreeCallback));\n      }\n      if (baton->tifftagPhotoshopLength > 0) {\n        info.Set(\"tifftagPhotoshop\",\n          Napi::Buffer<char>::NewOrCopy(env, baton->tifftagPhotoshop,\n            baton->tifftagPhotoshopLength, sharp::FreeCallback));\n      }\n      if (baton->comments.size() > 0) {\n        int i = 0;\n        Napi::Array comments = Napi::Array::New(env, baton->comments.size());\n        for (const auto& [keyword, text] : baton->comments) {\n          Napi::Object comment = Napi::Object::New(env);\n          comment.Set(\"keyword\", keyword);\n          comment.Set(\"text\", text);\n          comments.Set(i++, comment);\n        }\n        info.Set(\"comments\", comments);\n      }\n      Callback().Call(Receiver().Value(), { env.Null(), info });\n    } else {\n      Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });\n    }\n\n    delete baton->input;\n    delete baton;\n  }\n\n private:\n  MetadataBaton* baton;\n  Napi::FunctionReference debuglog;\n};\n\n/*\n  metadata(options, callback)\n*/\nNapi::Value metadata(const Napi::CallbackInfo& info) {\n  // V8 objects are converted to non-V8 types held in the baton struct\n  MetadataBaton *baton = new MetadataBaton;\n  Napi::Object options = info[size_t(0)].As<Napi::Object>();\n\n  // Input\n  baton->input = sharp::CreateInputDescriptor(options.Get(\"input\").As<Napi::Object>());\n\n  // Function to notify of libvips warnings\n  Napi::Function debuglog = options.Get(\"debuglog\").As<Napi::Function>();\n\n  // Join queue for worker thread\n  Napi::Function callback = info[size_t(1)].As<Napi::Function>();\n  MetadataWorker *worker = new MetadataWorker(callback, baton, debuglog);\n  worker->Receiver().Set(\"options\", options);\n  worker->Queue();\n\n  // Increment queued task counter\n  sharp::counterQueue++;\n\n  return info.Env().Undefined();\n}\n\nconst char *PNG_COMMENT_START = \"png-comment-\";\nconst int PNG_COMMENT_START_LEN = strlen(PNG_COMMENT_START);\n\nstatic void* readPNGComment(VipsImage *image, const char *field, GValue *value, void *p) {\n  MetadataComments *comments = static_cast<MetadataComments *>(p);\n\n  if (vips_isprefix(PNG_COMMENT_START, field)) {\n    const char *keyword = strchr(field + PNG_COMMENT_START_LEN, '-');\n    const char *str;\n    if (keyword != NULL && !vips_image_get_string(image, field, &str)) {\n      keyword++;  // Skip the hyphen\n      comments->push_back(std::make_pair(keyword, str));\n    }\n  }\n\n  return NULL;\n}\n"
  },
  {
    "path": "src/metadata.h",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#ifndef SRC_METADATA_H_\n#define SRC_METADATA_H_\n\n#include <string>\n#include <vector>\n#include <napi.h>\n\n#include \"./common.h\"\n\ntypedef std::vector<std::pair<std::string, std::string>> MetadataComments;\n\nstruct MetadataBaton {\n  // Input\n  sharp::InputDescriptor *input;\n  // Output\n  std::string format;\n  int width;\n  int height;\n  std::string space;\n  int channels;\n  std::string depth;\n  int density;\n  std::string chromaSubsampling;\n  bool isProgressive;\n  bool isPalette;\n  int bitsPerSample;\n  int pages;\n  int pageHeight;\n  int loop;\n  std::vector<int> delay;\n  int pagePrimary;\n  std::string compression;\n  std::string resolutionUnit;\n  std::string formatMagick;\n  std::vector<std::pair<int, int>> levels;\n  int subifds;\n  std::vector<double> background;\n  bool hasProfile;\n  bool hasAlpha;\n  int orientation;\n  char *exif;\n  size_t exifLength;\n  char *icc;\n  size_t iccLength;\n  char *iptc;\n  size_t iptcLength;\n  char *xmp;\n  size_t xmpLength;\n  char *tifftagPhotoshop;\n  size_t tifftagPhotoshopLength;\n  MetadataComments comments;\n  std::string err;\n\n  MetadataBaton():\n    input(nullptr),\n    width(0),\n    height(0),\n    channels(0),\n    density(0),\n    isProgressive(false),\n    isPalette(false),\n    bitsPerSample(0),\n    pages(0),\n    pageHeight(0),\n    loop(-1),\n    pagePrimary(-1),\n    subifds(0),\n    hasProfile(false),\n    hasAlpha(false),\n    orientation(0),\n    exif(nullptr),\n    exifLength(0),\n    icc(nullptr),\n    iccLength(0),\n    iptc(nullptr),\n    iptcLength(0),\n    xmp(nullptr),\n    xmpLength(0),\n    tifftagPhotoshop(nullptr),\n    tifftagPhotoshopLength(0) {}\n};\n\nNapi::Value metadata(const Napi::CallbackInfo& info);\n\n#endif  // SRC_METADATA_H_\n"
  },
  {
    "path": "src/operations.cc",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#include <algorithm>\n#include <functional>\n#include <memory>\n#include <tuple>\n#include <vector>\n#include <vips/vips8>\n\n#include \"./common.h\"\n#include \"./operations.h\"\n\nusing vips::VImage;\nusing vips::VError;\n\nnamespace sharp {\n  /*\n   * Tint an image using the provided RGB.\n   */\n  VImage Tint(VImage image, std::vector<double> const tint) {\n    std::vector<double> const tintLab = (VImage::black(1, 1) + tint)\n      .colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set(\"source_space\", VIPS_INTERPRETATION_sRGB))\n      .getpoint(0, 0);\n    // LAB identity function\n    VImage identityLab = VImage::identity(VImage::option()->set(\"bands\", 3))\n      .colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set(\"source_space\", VIPS_INTERPRETATION_sRGB));\n    // Scale luminance range, 0.0 to 1.0\n    VImage l = identityLab[0] / 100;\n    // Weighting functions\n    VImage weightL = 1.0 - 4.0 * ((l - 0.5) * (l - 0.5));\n    VImage weightAB = (weightL * tintLab).extract_band(1, VImage::option()->set(\"n\", 2));\n    identityLab = identityLab[0].bandjoin(weightAB);\n    // Convert lookup table to sRGB\n    VImage lut = identityLab.colourspace(VIPS_INTERPRETATION_sRGB,\n      VImage::option()->set(\"source_space\", VIPS_INTERPRETATION_LAB));\n    // Original colourspace\n    VipsInterpretation typeBeforeTint = image.interpretation();\n    if (typeBeforeTint == VIPS_INTERPRETATION_RGB) {\n      typeBeforeTint = VIPS_INTERPRETATION_sRGB;\n    }\n    // Apply lookup table\n    if (image.has_alpha()) {\n      VImage alpha = image[image.bands() - 1];\n      image = RemoveAlpha(image)\n        .colourspace(VIPS_INTERPRETATION_B_W)\n        .maplut(lut)\n        .colourspace(typeBeforeTint)\n        .bandjoin(alpha);\n    } else {\n      image = image\n        .colourspace(VIPS_INTERPRETATION_B_W)\n        .maplut(lut)\n        .colourspace(typeBeforeTint);\n    }\n    return image;\n  }\n\n  /*\n   * Stretch luminance to cover full dynamic range.\n   */\n  VImage Normalise(VImage image, int const lower, int const upper) {\n    // Get original colourspace\n    VipsInterpretation typeBeforeNormalize = image.interpretation();\n    if (typeBeforeNormalize == VIPS_INTERPRETATION_RGB) {\n      typeBeforeNormalize = VIPS_INTERPRETATION_sRGB;\n    }\n    // Convert to LAB colourspace\n    VImage lab = image.colourspace(VIPS_INTERPRETATION_LAB);\n    // Extract luminance\n    VImage luminance = lab[0];\n\n    // Find luminance range\n    int const min = lower == 0 ? luminance.min() : luminance.percent(lower);\n    int const max = upper == 100 ? luminance.max() : luminance.percent(upper);\n\n    if (std::abs(max - min) > 1) {\n      // Extract chroma\n      VImage chroma = lab.extract_band(1, VImage::option()->set(\"n\", 2));\n      // Calculate multiplication factor and addition\n      double f = 100.0 / (max - min);\n      double a = -(min * f);\n      // Scale luminance, join to chroma, convert back to original colourspace\n      VImage normalized = luminance.linear(f, a).bandjoin(chroma).colourspace(typeBeforeNormalize);\n      // Attach original alpha channel, if any\n      if (image.has_alpha()) {\n        // Extract original alpha channel\n        VImage alpha = image[image.bands() - 1];\n        // Join alpha channel to normalised image\n        return normalized.bandjoin(alpha);\n      } else {\n        return normalized;\n      }\n    }\n    return image;\n  }\n\n  /*\n   * Contrast limiting adapative histogram equalization (CLAHE)\n   */\n  VImage Clahe(VImage image, int const width, int const height, int const maxSlope) {\n    return image.hist_local(width, height, VImage::option()->set(\"max_slope\", maxSlope));\n  }\n\n  /*\n   * Gamma encoding/decoding\n   */\n  VImage Gamma(VImage image, double const exponent) {\n    if (image.has_alpha()) {\n      // Separate alpha channel\n      VImage alpha = image[image.bands() - 1];\n      return RemoveAlpha(image).gamma(VImage::option()->set(\"exponent\", exponent)).bandjoin(alpha);\n    } else {\n      return image.gamma(VImage::option()->set(\"exponent\", exponent));\n    }\n  }\n\n  /*\n   * Flatten image to remove alpha channel\n   */\n  VImage Flatten(VImage image, std::vector<double> flattenBackground) {\n    double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0;\n    std::vector<double> background {\n      flattenBackground[0] * multiplier,\n      flattenBackground[1] * multiplier,\n      flattenBackground[2] * multiplier\n    };\n    return image.flatten(VImage::option()->set(\"background\", background));\n  }\n\n  /**\n   * Produce the \"negative\" of the image.\n   */\n  VImage Negate(VImage image, bool const negateAlpha) {\n    if (image.has_alpha() && !negateAlpha) {\n      // Separate alpha channel\n      VImage alpha = image[image.bands() - 1];\n      return RemoveAlpha(image).invert().bandjoin(alpha);\n    } else {\n      return image.invert();\n    }\n  }\n\n  /*\n   * Gaussian blur. Use sigma of -1.0 for fast blur.\n   */\n  VImage Blur(VImage image, double const sigma, VipsPrecision precision, double const minAmpl) {\n    if (sigma == -1.0) {\n      // Fast, mild blur - averages neighbouring pixels\n      VImage blur = VImage::new_matrixv(3, 3,\n        1.0, 1.0, 1.0,\n        1.0, 1.0, 1.0,\n        1.0, 1.0, 1.0);\n      blur.set(\"scale\", 9.0);\n      return image.conv(blur);\n    } else {\n      // Slower, accurate Gaussian blur\n      return StaySequential(image).gaussblur(sigma, VImage::option()\n        ->set(\"precision\", precision)\n        ->set(\"min_ampl\", minAmpl));\n    }\n  }\n\n  /*\n   * Convolution with a kernel.\n   */\n  VImage Convolve(VImage image, int const width, int const height,\n    double const scale, double const offset,\n    std::vector<double> const &kernel_v\n  ) {\n    VImage kernel = VImage::new_from_memory(\n      static_cast<void*>(const_cast<double*>(kernel_v.data())),\n      width * height * sizeof(double),\n      width,\n      height,\n      1,\n      VIPS_FORMAT_DOUBLE);\n    kernel.set(\"scale\", scale);\n    kernel.set(\"offset\", offset);\n\n    return image.conv(kernel);\n  }\n\n  /*\n   * Recomb with a Matrix of the given bands/channel size.\n   * Eg. RGB will be a 3x3 matrix.\n   */\n  VImage Recomb(VImage image, std::vector<double> const& matrix) {\n    double* m = const_cast<double*>(matrix.data());\n    image = image.colourspace(VIPS_INTERPRETATION_sRGB);\n    if (matrix.size() == 9) {\n      return image\n        .recomb(image.bands() == 3\n          ? VImage::new_matrix(3, 3, m, 9)\n          : VImage::new_matrixv(4, 4,\n            m[0], m[1], m[2], 0.0,\n            m[3], m[4], m[5], 0.0,\n            m[6], m[7], m[8], 0.0,\n            0.0, 0.0, 0.0, 1.0));\n    } else {\n      return image.recomb(VImage::new_matrix(4, 4, m, 16));\n    }\n  }\n\n  VImage Modulate(VImage image, double const brightness, double const saturation,\n                  int const hue, double const lightness) {\n    VipsInterpretation colourspaceBeforeModulate = image.interpretation();\n    if (image.has_alpha()) {\n      // Separate alpha channel\n      VImage alpha = image[image.bands() - 1];\n      return RemoveAlpha(image)\n        .colourspace(VIPS_INTERPRETATION_LCH)\n        .linear(\n          { brightness, saturation, 1},\n          { lightness, 0.0, static_cast<double>(hue) }\n        )\n        .colourspace(colourspaceBeforeModulate)\n        .bandjoin(alpha);\n    } else {\n      return image\n        .colourspace(VIPS_INTERPRETATION_LCH)\n        .linear(\n          { brightness, saturation, 1 },\n          { lightness, 0.0, static_cast<double>(hue) }\n        )\n        .colourspace(colourspaceBeforeModulate);\n    }\n  }\n\n  /*\n   * Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen.\n   */\n  VImage Sharpen(VImage image, double const sigma, double const m1, double const m2,\n    double const x1, double const y2, double const y3) {\n    if (sigma == -1.0) {\n      // Fast, mild sharpen\n      VImage sharpen = VImage::new_matrixv(3, 3,\n        -1.0, -1.0, -1.0,\n        -1.0, 32.0, -1.0,\n        -1.0, -1.0, -1.0);\n      sharpen.set(\"scale\", 24.0);\n      return image.conv(sharpen);\n    } else {\n      // Slow, accurate sharpen in LAB colour space, with control over flat vs jagged areas\n      VipsInterpretation colourspaceBeforeSharpen = image.interpretation();\n      if (colourspaceBeforeSharpen == VIPS_INTERPRETATION_RGB) {\n        colourspaceBeforeSharpen = VIPS_INTERPRETATION_sRGB;\n      }\n      return image\n        .sharpen(VImage::option()\n          ->set(\"sigma\", sigma)\n          ->set(\"m1\", m1)\n          ->set(\"m2\", m2)\n          ->set(\"x1\", x1)\n          ->set(\"y2\", y2)\n          ->set(\"y3\", y3))\n        .colourspace(colourspaceBeforeSharpen);\n    }\n  }\n\n  VImage Threshold(VImage image, double const threshold, bool const thresholdGrayscale) {\n    if (!thresholdGrayscale) {\n      return image >= threshold;\n    }\n    return image.colourspace(VIPS_INTERPRETATION_B_W) >= threshold;\n  }\n\n  /*\n    Perform boolean/bitwise operation on image color channels - results in one channel image\n  */\n  VImage Bandbool(VImage image, VipsOperationBoolean const boolean) {\n    image = image.bandbool(boolean);\n    return image.copy(VImage::option()->set(\"interpretation\", VIPS_INTERPRETATION_B_W));\n  }\n\n  /*\n    Perform bitwise boolean operation between images\n  */\n  VImage Boolean(VImage image, VImage imageR, VipsOperationBoolean const boolean) {\n    return image.boolean(imageR, boolean);\n  }\n\n  /*\n    Trim an image\n  */\n  VImage Trim(VImage image, std::vector<double> background, double threshold, bool const lineArt) {\n    if (image.width() < 3 && image.height() < 3) {\n      throw VError(\"Image to trim must be at least 3x3 pixels\");\n    }\n    if (background.size() == 0) {\n      // Top-left pixel provides the default background colour if none is given\n      background = image.extract_area(0, 0, 1, 1)(0, 0);\n    } else if (sharp::Is16Bit(image.interpretation())) {\n      for (size_t i = 0; i < background.size(); i++) {\n        background[i] *= 256.0;\n      }\n      threshold *= 256.0;\n    }\n    std::vector<double> backgroundAlpha({ background.back() });\n    if (image.has_alpha()) {\n      background.pop_back();\n    } else {\n      background.resize(image.bands());\n    }\n    int left, top, width, height;\n    left = image.find_trim(&top, &width, &height, VImage::option()\n      ->set(\"background\", background)\n      ->set(\"line_art\", lineArt)\n      ->set(\"threshold\", threshold));\n    if (image.has_alpha()) {\n      // Search alpha channel (A)\n      int leftA, topA, widthA, heightA;\n      VImage alpha = image[image.bands() - 1];\n      leftA = alpha.find_trim(&topA, &widthA, &heightA, VImage::option()\n        ->set(\"background\", backgroundAlpha)\n        ->set(\"line_art\", lineArt)\n        ->set(\"threshold\", threshold));\n      if (widthA > 0 && heightA > 0) {\n        if (width > 0 && height > 0) {\n          // Combined bounding box (B)\n          int const leftB = std::min(left, leftA);\n          int const topB = std::min(top, topA);\n          int const widthB = std::max(left + width, leftA + widthA) - leftB;\n          int const heightB = std::max(top + height, topA + heightA) - topB;\n          return image.extract_area(leftB, topB, widthB, heightB);\n        } else {\n          // Use alpha only\n          return image.extract_area(leftA, topA, widthA, heightA);\n        }\n      }\n    }\n    if (width > 0 && height > 0) {\n      return image.extract_area(left, top, width, height);\n    }\n    return image;\n  }\n\n  /*\n   * Calculate (a * in + b)\n   */\n  VImage Linear(VImage image, std::vector<double> const a, std::vector<double> const b) {\n    size_t const bands = static_cast<size_t>(image.bands());\n    if (a.size() > bands) {\n      throw VError(\"Band expansion using linear is unsupported\");\n    }\n    bool const uchar = !Is16Bit(image.interpretation());\n    if (image.has_alpha() && a.size() != bands && (a.size() == 1 || a.size() == bands - 1 || bands - 1 == 1)) {\n      // Separate alpha channel\n      VImage alpha = image[bands - 1];\n      return RemoveAlpha(image).linear(a, b, VImage::option()->set(\"uchar\", uchar)).bandjoin(alpha);\n    } else {\n      return image.linear(a, b, VImage::option()->set(\"uchar\", uchar));\n    }\n  }\n\n  /*\n   * Unflatten\n   */\n  VImage Unflatten(VImage image) {\n    if (image.has_alpha()) {\n      VImage alpha = image[image.bands() - 1];\n      VImage noAlpha = RemoveAlpha(image);\n      return noAlpha.bandjoin(alpha & (noAlpha.colourspace(VIPS_INTERPRETATION_B_W) < 255));\n    } else {\n      return image.bandjoin(image.colourspace(VIPS_INTERPRETATION_B_W) < 255);\n    }\n  }\n\n  /*\n   * Ensure the image is in a given colourspace\n   */\n  VImage EnsureColourspace(VImage image, VipsInterpretation colourspace) {\n    if (colourspace != VIPS_INTERPRETATION_LAST && image.interpretation() != colourspace) {\n      image = image.colourspace(colourspace,\n        VImage::option()->set(\"source_space\", image.interpretation()));\n    }\n    return image;\n  }\n\n  /*\n   * Split and crop each frame, reassemble, and update pageHeight.\n   */\n  VImage CropMultiPage(VImage image, int left, int top, int width, int height,\n                       int nPages, int *pageHeight) {\n    if (top == 0 && height == *pageHeight) {\n      // Fast path; no need to adjust the height of the multi-page image\n      return image.extract_area(left, 0, width, image.height());\n    } else {\n      std::vector<VImage> pages;\n      pages.reserve(nPages);\n\n      // Split the image into cropped frames\n      image = StaySequential(image);\n      for (int i = 0; i < nPages; i++) {\n        pages.push_back(\n          image.extract_area(left, *pageHeight * i + top, width, height));\n      }\n\n      // Reassemble the frames into a tall, thin image\n      VImage assembled = VImage::arrayjoin(pages,\n        VImage::option()->set(\"across\", 1));\n\n      // Update the page height\n      *pageHeight = height;\n\n      return assembled;\n    }\n  }\n\n  /*\n   * Split into frames, embed each frame, reassemble, and update pageHeight.\n   */\n  VImage EmbedMultiPage(VImage image, int left, int top, int width, int height,\n                        VipsExtend extendWith, std::vector<double> background, int nPages, int *pageHeight) {\n    if (top == 0 && height == *pageHeight) {\n      // Fast path; no need to adjust the height of the multi-page image\n      return image.embed(left, 0, width, image.height(), VImage::option()\n        ->set(\"extend\", extendWith)\n        ->set(\"background\", background));\n    } else if (left == 0 && width == image.width()) {\n      // Fast path; no need to adjust the width of the multi-page image\n      std::vector<VImage> pages;\n      pages.reserve(nPages);\n\n      // Rearrange the tall image into a vertical grid\n      image = image.grid(*pageHeight, nPages, 1);\n\n      // Do the embed on the wide image\n      image = image.embed(0, top, image.width(), height, VImage::option()\n        ->set(\"extend\", extendWith)\n        ->set(\"background\", background));\n\n      // Split the wide image into frames\n      for (int i = 0; i < nPages; i++) {\n        pages.push_back(\n          image.extract_area(width * i, 0, width, height));\n      }\n\n      // Reassemble the frames into a tall, thin image\n      VImage assembled = VImage::arrayjoin(pages,\n        VImage::option()->set(\"across\", 1));\n\n      // Update the page height\n      *pageHeight = height;\n\n      return assembled;\n    } else {\n      std::vector<VImage> pages;\n      pages.reserve(nPages);\n\n      // Split the image into frames\n      for (int i = 0; i < nPages; i++) {\n        pages.push_back(\n          image.extract_area(0, *pageHeight * i, image.width(), *pageHeight));\n      }\n\n      // Embed each frame in the target size\n      for (int i = 0; i < nPages; i++) {\n        pages[i] = pages[i].embed(left, top, width, height, VImage::option()\n          ->set(\"extend\", extendWith)\n          ->set(\"background\", background));\n      }\n\n      // Reassemble the frames into a tall, thin image\n      VImage assembled = VImage::arrayjoin(pages,\n        VImage::option()->set(\"across\", 1));\n\n      // Update the page height\n      *pageHeight = height;\n\n      return assembled;\n    }\n  }\n\n  /*\n   * Dilate an image\n   */\n  VImage Dilate(VImage image, int const width) {\n    int const maskWidth = 2 * width + 1;\n    VImage mask = VImage::new_matrix(maskWidth, maskWidth);\n    return image.morph(\n      mask,\n      VIPS_OPERATION_MORPHOLOGY_DILATE).invert();\n  }\n\n  /*\n   * Erode an image\n   */\n  VImage Erode(VImage image, int const width) {\n    int const maskWidth = 2 * width + 1;\n    VImage mask = VImage::new_matrix(maskWidth, maskWidth);\n    return image.morph(\n      mask,\n      VIPS_OPERATION_MORPHOLOGY_ERODE).invert();\n  }\n\n}  // namespace sharp\n"
  },
  {
    "path": "src/operations.h",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#ifndef SRC_OPERATIONS_H_\n#define SRC_OPERATIONS_H_\n\n#include <algorithm>\n#include <functional>\n#include <memory>\n#include <tuple>\n#include <vector>\n#include <vips/vips8>\n\nusing vips::VImage;\n\nnamespace sharp {\n\n  /*\n   * Tint an image using the provided RGB.\n   */\n  VImage Tint(VImage image, std::vector<double> const tint);\n\n  /*\n   * Stretch luminance to cover full dynamic range.\n   */\n  VImage Normalise(VImage image, int const lower, int const upper);\n\n  /*\n   * Contrast limiting adapative histogram equalization (CLAHE)\n   */\n  VImage Clahe(VImage image, int const width, int const height, int const maxSlope);\n\n  /*\n   * Gamma encoding/decoding\n   */\n  VImage Gamma(VImage image, double const exponent);\n\n  /*\n   * Flatten image to remove alpha channel\n   */\n  VImage Flatten(VImage image, std::vector<double> flattenBackground);\n\n  /*\n   * Produce the \"negative\" of the image.\n   */\n  VImage Negate(VImage image, bool const negateAlpha);\n\n  /*\n   * Gaussian blur. Use sigma of -1.0 for fast blur.\n   */\n  VImage Blur(VImage image, double const sigma, VipsPrecision precision, double const minAmpl);\n\n  /*\n   * Convolution with a kernel.\n   */\n  VImage Convolve(VImage image, int const width, int const height,\n    double const scale, double const offset, std::vector<double> const &kernel_v);\n\n  /*\n   * Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen.\n   */\n  VImage Sharpen(VImage image, double const sigma, double const m1, double const m2,\n    double const x1, double const y2, double const y3);\n\n  /*\n    Threshold an image\n  */\n  VImage Threshold(VImage image, double const threshold, bool const thresholdColor);\n\n  /*\n    Perform boolean/bitwise operation on image color channels - results in one channel image\n  */\n  VImage Bandbool(VImage image, VipsOperationBoolean const boolean);\n\n  /*\n    Perform bitwise boolean operation between images\n  */\n  VImage Boolean(VImage image, VImage imageR, VipsOperationBoolean const boolean);\n\n  /*\n    Trim an image\n  */\n  VImage Trim(VImage image, std::vector<double> background, double threshold, bool const lineArt);\n\n  /*\n   * Linear adjustment (a * in + b)\n   */\n  VImage Linear(VImage image, std::vector<double> const a,  std::vector<double> const b);\n\n  /*\n   * Unflatten\n   */\n  VImage Unflatten(VImage image);\n\n  /*\n   * Recomb with a Matrix of the given bands/channel size.\n   * Eg. RGB will be a 3x3 matrix.\n   */\n  VImage Recomb(VImage image, std::vector<double> const &matrix);\n\n  /*\n   * Modulate brightness, saturation, hue and lightness\n   */\n  VImage Modulate(VImage image, double const brightness, double const saturation,\n                  int const hue, double const lightness);\n\n  /*\n   * Ensure the image is in a given colourspace\n   */\n  VImage EnsureColourspace(VImage image, VipsInterpretation colourspace);\n\n  /*\n   * Split and crop each frame, reassemble, and update pageHeight.\n   */\n  VImage CropMultiPage(VImage image, int left, int top, int width, int height,\n                       int nPages, int *pageHeight);\n\n  /*\n   * Split into frames, embed each frame, reassemble, and update pageHeight.\n   */\n  VImage EmbedMultiPage(VImage image, int left, int top, int width, int height,\n                        VipsExtend extendWith, std::vector<double> background, int nPages, int *pageHeight);\n\n  /*\n   * Dilate an image\n   */\n  VImage Dilate(VImage image, int const maskWidth);\n\n  /*\n   * Erode an image\n   */\n  VImage Erode(VImage image, int const maskWidth);\n}  // namespace sharp\n\n#endif  // SRC_OPERATIONS_H_\n"
  },
  {
    "path": "src/pipeline.cc",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#include <algorithm>\n#include <cmath>\n#include <filesystem>  // NOLINT(build/c++17)\n#include <map>\n#include <memory>\n#include <numeric>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n#include <vips/vips8>\n#include <napi.h>\n\n#include \"./common.h\"\n#include \"./operations.h\"\n#include \"./pipeline.h\"\n\nclass PipelineWorker : public Napi::AsyncWorker {\n public:\n  PipelineWorker(Napi::Function callback, PipelineBaton *baton,\n    Napi::Function debuglog, Napi::Function queueListener) :\n    Napi::AsyncWorker(callback),\n    baton(baton),\n    debuglog(Napi::Persistent(debuglog)),\n    queueListener(Napi::Persistent(queueListener)) {}\n  ~PipelineWorker() {}\n\n  // libuv worker\n  void Execute() {\n    // Decrement queued task counter\n    sharp::counterQueue--;\n    // Increment processing task counter\n    sharp::counterProcess++;\n\n    try {\n      // Open input\n      vips::VImage image;\n      sharp::ImageType inputImageType;\n      if (baton->join.empty()) {\n        std::tie(image, inputImageType) = sharp::OpenInput(baton->input);\n      } else {\n        std::vector<VImage> images;\n        bool hasAlpha = false;\n        for (auto &join : baton->join) {\n          std::tie(image, inputImageType) = sharp::OpenInput(join);\n          image = sharp::EnsureColourspace(image, baton->colourspacePipeline);\n          images.push_back(image);\n          hasAlpha |= image.has_alpha();\n        }\n        if (hasAlpha) {\n          for (auto &image : images) {\n            if (!image.has_alpha()) {\n              image = sharp::EnsureAlpha(image, 1);\n            }\n          }\n        } else {\n          baton->input->joinBackground.pop_back();\n        }\n        inputImageType = sharp::ImageType::PNG;\n        image = VImage::arrayjoin(images, VImage::option()\n          ->set(\"across\", baton->input->joinAcross)\n          ->set(\"shim\", baton->input->joinShim)\n          ->set(\"background\", baton->input->joinBackground)\n          ->set(\"halign\", baton->input->joinHalign)\n          ->set(\"valign\", baton->input->joinValign));\n        if (baton->input->joinAnimated) {\n          image = image.copy();\n          image.set(VIPS_META_N_PAGES, static_cast<int>(images.size()));\n          image.set(VIPS_META_PAGE_HEIGHT, static_cast<int>(image.height() / images.size()));\n        }\n      }\n      VipsAccess access = baton->input->access;\n      image = sharp::EnsureColourspace(image, baton->colourspacePipeline);\n\n      int nPages = baton->input->pages;\n      if (nPages == -1) {\n        // Resolve the number of pages if we need to render until the end of the document\n        nPages = image.get_typeof(VIPS_META_N_PAGES) != 0\n          ? image.get_int(VIPS_META_N_PAGES) - baton->input->page\n          : 1;\n      }\n\n      // Get pre-resize page height\n      int pageHeight = sharp::GetPageHeight(image);\n\n      // Calculate angle of rotation\n      VipsAngle rotation = VIPS_ANGLE_D0;\n      VipsAngle autoRotation = VIPS_ANGLE_D0;\n      bool autoFlop = false;\n\n      if (baton->input->autoOrient) {\n        // Rotate and flip image according to Exif orientation\n        std::tie(autoRotation, autoFlop) = CalculateExifRotationAndFlop(sharp::ExifOrientation(image));\n      }\n\n      rotation = CalculateAngleRotation(baton->angle);\n\n      bool const shouldRotateBefore = baton->rotateBefore &&\n        (rotation != VIPS_ANGLE_D0 || baton->flip || baton->flop || baton->rotationAngle != 0.0);\n      bool const shouldOrientBefore = (shouldRotateBefore || baton->orientBefore) &&\n        (autoRotation != VIPS_ANGLE_D0 || autoFlop);\n\n      if (shouldOrientBefore) {\n        image = sharp::StaySequential(image, autoRotation != VIPS_ANGLE_D0);\n        if (autoRotation != VIPS_ANGLE_D0) {\n          if (autoRotation != VIPS_ANGLE_D180) {\n            MultiPageUnsupported(nPages, \"Rotate\");\n          }\n          image = image.rot(autoRotation);\n          autoRotation = VIPS_ANGLE_D0;\n        }\n        if (autoFlop) {\n          image = image.flip(VIPS_DIRECTION_HORIZONTAL);\n          autoFlop = false;\n        }\n      }\n\n      if (shouldRotateBefore) {\n        image = sharp::StaySequential(image, rotation != VIPS_ANGLE_D0 || baton->flip || baton->rotationAngle != 0.0);\n        if (baton->flip) {\n          image = image.flip(VIPS_DIRECTION_VERTICAL);\n          baton->flip = false;\n        }\n        if (baton->flop) {\n          image = image.flip(VIPS_DIRECTION_HORIZONTAL);\n          baton->flop = false;\n        }\n        if (rotation != VIPS_ANGLE_D0) {\n          if (rotation != VIPS_ANGLE_D180) {\n            MultiPageUnsupported(nPages, \"Rotate\");\n          }\n          image = image.rot(rotation);\n          rotation = VIPS_ANGLE_D0;\n        }\n        if (baton->rotationAngle != 0.0) {\n          MultiPageUnsupported(nPages, \"Rotate\");\n          std::vector<double> background;\n          std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, false);\n          image = image.rotate(baton->rotationAngle, VImage::option()->set(\"background\", background)).copy_memory();\n          baton->rotationAngle = 0.0;\n        }\n      }\n\n      // Trim\n      if (baton->trimThreshold >= 0.0) {\n        MultiPageUnsupported(nPages, \"Trim\");\n        image = sharp::StaySequential(image);\n        image = sharp::Trim(image, baton->trimBackground, baton->trimThreshold, baton->trimLineArt);\n        baton->trimOffsetLeft = image.xoffset();\n        baton->trimOffsetTop = image.yoffset();\n      }\n\n      // Pre extraction\n      if (baton->topOffsetPre != -1) {\n        image = nPages > 1\n          ? sharp::CropMultiPage(image,\n              baton->leftOffsetPre, baton->topOffsetPre, baton->widthPre, baton->heightPre, nPages, &pageHeight)\n          : image.extract_area(baton->leftOffsetPre, baton->topOffsetPre, baton->widthPre, baton->heightPre);\n      }\n\n      // Get pre-resize image width and height\n      int inputWidth = image.width();\n      int inputHeight = image.height();\n\n      // Is there just one page? Shrink to inputHeight instead\n      if (nPages == 1) {\n        pageHeight = inputHeight;\n      }\n\n      // Scaling calculations\n      double hshrink;\n      double vshrink;\n      int targetResizeWidth = baton->width;\n      int targetResizeHeight = baton->height;\n\n      // When auto-rotating by 90 or 270 degrees, swap the target width and\n      // height to ensure the behavior aligns with how it would have been if\n      // the rotation had taken place *before* resizing.\n      if (autoRotation == VIPS_ANGLE_D90 || autoRotation == VIPS_ANGLE_D270) {\n        std::swap(targetResizeWidth, targetResizeHeight);\n      }\n\n      // Shrink to pageHeight, so we work for multi-page images\n      std::tie(hshrink, vshrink) = sharp::ResolveShrink(\n        inputWidth, pageHeight, targetResizeWidth, targetResizeHeight,\n        baton->canvas, baton->withoutEnlargement, baton->withoutReduction);\n\n      // The jpeg preload shrink.\n      int jpegShrinkOnLoad = 1;\n\n      // WebP, PDF, SVG scale\n      double scale = 1.0;\n\n      // Try to reload input using shrink-on-load for JPEG, WebP, SVG and PDF, when:\n      //  - the width or height parameters are specified;\n      //  - gamma correction doesn't need to be applied;\n      //  - trimming or pre-resize extract isn't required;\n      //  - input colourspace is not specified;\n      bool const shouldPreShrink = (targetResizeWidth > 0 || targetResizeHeight > 0) &&\n        baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold < 0.0 &&\n        baton->colourspacePipeline == VIPS_INTERPRETATION_LAST && !(shouldOrientBefore || shouldRotateBefore);\n\n      if (shouldPreShrink) {\n        // The common part of the shrink: the bit by which both axes must be shrunk\n        double shrink = std::min(hshrink, vshrink);\n\n        if (inputImageType == sharp::ImageType::JPEG) {\n          // Leave at least a factor of two for the final resize step, when fastShrinkOnLoad: false\n          // for more consistent results and to avoid extra sharpness to the image\n          int factor = baton->fastShrinkOnLoad ? 1 : 2;\n          if (shrink >= 8 * factor) {\n            jpegShrinkOnLoad = 8;\n          } else if (shrink >= 4 * factor) {\n            jpegShrinkOnLoad = 4;\n          } else if (shrink >= 2 * factor) {\n            jpegShrinkOnLoad = 2;\n          }\n          // Lower shrink-on-load for known libjpeg rounding errors\n          if (jpegShrinkOnLoad > 1 && static_cast<int>(shrink) == jpegShrinkOnLoad) {\n            jpegShrinkOnLoad /= 2;\n          }\n        } else if (inputImageType == sharp::ImageType::WEBP && baton->fastShrinkOnLoad && shrink > 1.0) {\n          // Avoid upscaling via webp\n          scale = 1.0 / shrink;\n        } else if (inputImageType == sharp::ImageType::SVG ||\n                   inputImageType == sharp::ImageType::PDF) {\n          scale = 1.0 / shrink;\n        }\n      }\n\n      // Reload input using shrink-on-load, it'll be an integer shrink\n      // factor for jpegload*, a double scale factor for webpload*,\n      // pdfload* and svgload*\n      if (jpegShrinkOnLoad > 1) {\n        vips::VOption *option = GetOptionsForImageType(inputImageType, baton->input)->set(\"shrink\", jpegShrinkOnLoad);\n        if (baton->input->buffer != nullptr) {\n          // Reload JPEG buffer\n          VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);\n          image = VImage::jpegload_buffer(blob, option);\n          vips_area_unref(reinterpret_cast<VipsArea*>(blob));\n        } else {\n          // Reload JPEG file\n          image = VImage::jpegload(const_cast<char*>(baton->input->file.data()), option);\n        }\n      } else if (scale != 1.0) {\n        vips::VOption *option = GetOptionsForImageType(inputImageType, baton->input)->set(\"scale\", scale);\n        if (inputImageType == sharp::ImageType::WEBP) {\n          if (baton->input->buffer != nullptr) {\n            // Reload WebP buffer\n            VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);\n            image = VImage::webpload_buffer(blob, option);\n            vips_area_unref(reinterpret_cast<VipsArea*>(blob));\n          } else {\n            // Reload WebP file\n            image = VImage::webpload(const_cast<char*>(baton->input->file.data()), option);\n          }\n        } else if (inputImageType == sharp::ImageType::SVG) {\n          if (baton->input->buffer != nullptr) {\n            // Reload SVG buffer\n            VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);\n            image = VImage::svgload_buffer(blob, option);\n            vips_area_unref(reinterpret_cast<VipsArea*>(blob));\n          } else {\n            // Reload SVG file\n            image = VImage::svgload(const_cast<char*>(baton->input->file.data()), option);\n          }\n          sharp::SetDensity(image, baton->input->density);\n          if (image.width() > 32767 || image.height() > 32767) {\n            throw vips::VError(\"Input SVG image will exceed 32767x32767 pixel limit when scaled\");\n          }\n        } else if (inputImageType == sharp::ImageType::PDF) {\n          if (baton->input->buffer != nullptr) {\n            // Reload PDF buffer\n            VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);\n            image = VImage::pdfload_buffer(blob, option);\n            vips_area_unref(reinterpret_cast<VipsArea*>(blob));\n          } else {\n            // Reload PDF file\n            image = VImage::pdfload(const_cast<char*>(baton->input->file.data()), option);\n          }\n          sharp::SetDensity(image, baton->input->density);\n        }\n      } else {\n        if (inputImageType == sharp::ImageType::SVG && (image.width() > 32767 || image.height() > 32767)) {\n          throw vips::VError(\"Input SVG image exceeds 32767x32767 pixel limit\");\n        }\n      }\n      if (baton->input->autoOrient) {\n        image = sharp::RemoveExifOrientation(image);\n      }\n\n      // Any pre-shrinking may already have been done\n      inputWidth = image.width();\n      inputHeight = image.height();\n\n      // After pre-shrink, but before the main shrink stage\n      // Reuse the initial pageHeight if we didn't pre-shrink\n      if (shouldPreShrink) {\n        pageHeight = sharp::GetPageHeight(image);\n      }\n\n      // Shrink to pageHeight, so we work for multi-page images\n      std::tie(hshrink, vshrink) = sharp::ResolveShrink(\n        inputWidth, pageHeight, targetResizeWidth, targetResizeHeight,\n        baton->canvas, baton->withoutEnlargement, baton->withoutReduction);\n\n      int targetHeight = static_cast<int>(std::rint(static_cast<double>(pageHeight) / vshrink));\n      int targetPageHeight = targetHeight;\n\n      // In toilet-roll mode, we must adjust vshrink so that we exactly hit\n      // pageHeight or we'll have pixels straddling pixel boundaries\n      if (inputHeight > pageHeight) {\n        targetHeight *= nPages;\n        vshrink = static_cast<double>(inputHeight) / targetHeight;\n      }\n\n      // Ensure we're using a device-independent colour space\n      std::pair<char*, size_t> inputProfile(nullptr, 0);\n      if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) && baton->withIccProfile.empty()) {\n        // Cache input profile for use with output\n        inputProfile = sharp::GetProfile(image);\n        baton->input->ignoreIcc = true;\n      }\n      char const *processingProfile = image.interpretation() == VIPS_INTERPRETATION_RGB16 ? \"p3\" : \"srgb\";\n      if (\n        sharp::HasProfile(image) &&\n        image.interpretation() != VIPS_INTERPRETATION_LABS &&\n        image.interpretation() != VIPS_INTERPRETATION_GREY16 &&\n        baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK &&\n        !baton->input->ignoreIcc\n      ) {\n        // Convert to sRGB/P3 using embedded profile\n        try {\n          image = image.icc_transform(processingProfile, VImage::option()\n            ->set(\"embedded\", true)\n            ->set(\"depth\", sharp::Is16Bit(image.interpretation()) ? 16 : 8)\n            ->set(\"intent\", VIPS_INTENT_PERCEPTUAL));\n        } catch(...) {\n          sharp::VipsWarningCallback(nullptr, G_LOG_LEVEL_WARNING, \"Invalid embedded profile\", nullptr);\n        }\n      } else if (\n        image.interpretation() == VIPS_INTERPRETATION_CMYK &&\n        baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK\n      ) {\n        image = image.icc_transform(processingProfile, VImage::option()\n          ->set(\"input_profile\", \"cmyk\")\n          ->set(\"intent\", VIPS_INTENT_PERCEPTUAL));\n      }\n\n      // Flatten image to remove alpha channel\n      if (baton->flatten && image.has_alpha()) {\n        image = sharp::Flatten(image, baton->flattenBackground);\n      }\n\n      // Gamma encoding (darken)\n      if (baton->gamma >= 1 && baton->gamma <= 3) {\n        image = sharp::Gamma(image, 1.0 / baton->gamma);\n      }\n\n      // Convert to greyscale (linear, therefore after gamma encoding, if any)\n      if (baton->greyscale) {\n        image = image.colourspace(VIPS_INTERPRETATION_B_W);\n      }\n\n      bool const shouldResize = hshrink != 1.0 || vshrink != 1.0;\n      bool const shouldBlur = baton->blurSigma != 0.0;\n      bool const shouldConv = baton->convKernelWidth * baton->convKernelHeight > 0;\n      bool const shouldSharpen = baton->sharpenSigma != 0.0;\n      bool const shouldComposite = !baton->composite.empty();\n\n      if (shouldComposite && !image.has_alpha()) {\n        image = sharp::EnsureAlpha(image, 1);\n      }\n\n      VipsBandFormat premultiplyFormat = image.format();\n      bool const shouldPremultiplyAlpha = image.has_alpha() &&\n        (shouldResize || shouldBlur || shouldConv || shouldSharpen);\n\n      if (shouldPremultiplyAlpha) {\n        image = image.premultiply().cast(premultiplyFormat);\n      }\n\n      // Resize\n      if (shouldResize) {\n        image = image.resize(1.0 / hshrink, VImage::option()\n          ->set(\"vscale\", 1.0 / vshrink)\n          ->set(\"kernel\", baton->kernel));\n      }\n\n      image = sharp::StaySequential(image,\n        autoRotation != VIPS_ANGLE_D0 ||\n        baton->flip ||\n        rotation != VIPS_ANGLE_D0);\n      // Auto-rotate post-extract\n      if (autoRotation != VIPS_ANGLE_D0) {\n        if (autoRotation != VIPS_ANGLE_D180) {\n          MultiPageUnsupported(nPages, \"Rotate\");\n        }\n        image = image.rot(autoRotation);\n      }\n      // Mirror vertically (up-down) about the x-axis\n      if (baton->flip) {\n        image = image.flip(VIPS_DIRECTION_VERTICAL);\n      }\n      // Mirror horizontally (left-right) about the y-axis\n      if (baton->flop != autoFlop) {\n        image = image.flip(VIPS_DIRECTION_HORIZONTAL);\n      }\n      // Rotate post-extract 90-angle\n      if (rotation != VIPS_ANGLE_D0) {\n        if (rotation != VIPS_ANGLE_D180) {\n          MultiPageUnsupported(nPages, \"Rotate\");\n        }\n        image = image.rot(rotation);\n      }\n\n      // Join additional color channels to the image\n      if (!baton->joinChannelIn.empty()) {\n        VImage joinImage;\n        sharp::ImageType joinImageType = sharp::ImageType::UNKNOWN;\n\n        for (unsigned int i = 0; i < baton->joinChannelIn.size(); i++) {\n          baton->joinChannelIn[i]->access = access;\n          std::tie(joinImage, joinImageType) = sharp::OpenInput(baton->joinChannelIn[i]);\n          joinImage = sharp::EnsureColourspace(joinImage, baton->colourspacePipeline);\n          image = image.bandjoin(joinImage);\n        }\n        image = image.copy(VImage::option()->set(\"interpretation\", baton->colourspace));\n        image = sharp::RemoveGifPalette(image);\n      }\n\n      inputWidth = image.width();\n      inputHeight = nPages > 1 ? targetPageHeight : image.height();\n\n      // Resolve dimensions\n      if (baton->width <= 0) {\n        baton->width = inputWidth;\n      }\n      if (baton->height <= 0) {\n        baton->height = inputHeight;\n      }\n\n      // Crop/embed\n      if (inputWidth != baton->width || inputHeight != baton->height) {\n        if (baton->canvas == sharp::Canvas::EMBED) {\n          std::vector<double> background;\n          std::tie(image, background) = sharp::ApplyAlpha(image, baton->resizeBackground, shouldPremultiplyAlpha);\n\n          // Embed\n          const auto& [left, top] = sharp::CalculateEmbedPosition(\n            inputWidth, inputHeight, baton->width, baton->height, baton->position);\n          const int width = std::max(inputWidth, baton->width);\n          const int height = std::max(inputHeight, baton->height);\n\n          image = nPages > 1\n            ? sharp::EmbedMultiPage(image,\n                left, top, width, height, VIPS_EXTEND_BACKGROUND, background, nPages, &targetPageHeight)\n            : image.embed(left, top, width, height, VImage::option()\n              ->set(\"extend\", VIPS_EXTEND_BACKGROUND)\n              ->set(\"background\", background));\n        } else if (baton->canvas == sharp::Canvas::CROP) {\n          if (baton->width > inputWidth) {\n            baton->width = inputWidth;\n          }\n          if (baton->height > inputHeight) {\n            baton->height = inputHeight;\n          }\n\n          // Crop\n          if (baton->position < 9) {\n            // Gravity-based crop\n            const auto& [left, top] = sharp::CalculateCrop(\n              inputWidth, inputHeight, baton->width, baton->height, baton->position);\n            const int width = std::min(inputWidth, baton->width);\n            const int height = std::min(inputHeight, baton->height);\n\n            image = nPages > 1\n              ? sharp::CropMultiPage(image,\n                  left, top, width, height, nPages, &targetPageHeight)\n              : image.extract_area(left, top, width, height);\n          } else {\n            int attention_x;\n            int attention_y;\n\n            // Attention-based or Entropy-based crop\n            MultiPageUnsupported(nPages, \"Resize strategy\");\n            image = sharp::StaySequential(image);\n            image = image.smartcrop(baton->width, baton->height, VImage::option()\n              ->set(\"interesting\", baton->position == 16 ? VIPS_INTERESTING_ENTROPY : VIPS_INTERESTING_ATTENTION)\n              ->set(\"premultiplied\", shouldPremultiplyAlpha)\n              ->set(\"attention_x\", &attention_x)\n              ->set(\"attention_y\", &attention_y));\n            baton->hasCropOffset = true;\n            baton->cropOffsetLeft = static_cast<int>(image.xoffset());\n            baton->cropOffsetTop = static_cast<int>(image.yoffset());\n            baton->hasAttentionCenter = true;\n            baton->attentionX = static_cast<int>(attention_x * jpegShrinkOnLoad / scale);\n            baton->attentionY = static_cast<int>(attention_y * jpegShrinkOnLoad / scale);\n          }\n        }\n      }\n\n      // Rotate post-extract non-90 angle\n      if (!baton->rotateBefore && baton->rotationAngle != 0.0) {\n        MultiPageUnsupported(nPages, \"Rotate\");\n        image = sharp::StaySequential(image);\n        std::vector<double> background;\n        std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, shouldPremultiplyAlpha);\n        image = image.rotate(baton->rotationAngle, VImage::option()->set(\"background\", background));\n      }\n\n      // Post extraction\n      if (baton->topOffsetPost != -1) {\n        if (nPages > 1) {\n          image = sharp::CropMultiPage(image,\n            baton->leftOffsetPost, baton->topOffsetPost, baton->widthPost, baton->heightPost,\n            nPages, &targetPageHeight);\n\n          // heightPost is used in the info object, so update to reflect the number of pages\n          baton->heightPost *= nPages;\n        } else {\n          image = image.extract_area(\n            baton->leftOffsetPost, baton->topOffsetPost, baton->widthPost, baton->heightPost);\n        }\n      }\n\n      // Affine transform\n      if (!baton->affineMatrix.empty()) {\n        MultiPageUnsupported(nPages, \"Affine\");\n        image = sharp::StaySequential(image);\n        std::vector<double> background;\n        std::tie(image, background) = sharp::ApplyAlpha(image, baton->affineBackground, shouldPremultiplyAlpha);\n        vips::VInterpolate interp = vips::VInterpolate::new_from_name(\n          const_cast<char*>(baton->affineInterpolator.data()));\n        image = image.affine(baton->affineMatrix, VImage::option()->set(\"background\", background)\n          ->set(\"idx\", baton->affineIdx)\n          ->set(\"idy\", baton->affineIdy)\n          ->set(\"odx\", baton->affineOdx)\n          ->set(\"ody\", baton->affineOdy)\n          ->set(\"interpolate\", interp));\n      }\n\n      // Extend edges\n      if (baton->extendTop > 0 || baton->extendBottom > 0 || baton->extendLeft > 0 || baton->extendRight > 0) {\n        // Embed\n        baton->width = image.width() + baton->extendLeft + baton->extendRight;\n        baton->height = (nPages > 1 ? targetPageHeight : image.height()) + baton->extendTop + baton->extendBottom;\n\n        if (baton->extendWith == VIPS_EXTEND_BACKGROUND) {\n          std::vector<double> background;\n          std::tie(image, background) = sharp::ApplyAlpha(image, baton->extendBackground, shouldPremultiplyAlpha);\n\n          image = sharp::StaySequential(image, nPages > 1);\n          image = nPages > 1\n            ? sharp::EmbedMultiPage(image,\n                baton->extendLeft, baton->extendTop, baton->width, baton->height,\n                baton->extendWith, background, nPages, &targetPageHeight)\n            : image.embed(baton->extendLeft, baton->extendTop, baton->width, baton->height,\n                VImage::option()->set(\"extend\", baton->extendWith)->set(\"background\", background));\n        } else {\n          std::vector<double> ignoredBackground(1);\n          image = sharp::StaySequential(image);\n          image = nPages > 1\n            ? sharp::EmbedMultiPage(image,\n                baton->extendLeft, baton->extendTop, baton->width, baton->height,\n                baton->extendWith, ignoredBackground, nPages, &targetPageHeight)\n            : image.embed(baton->extendLeft, baton->extendTop, baton->width, baton->height,\n                VImage::option()->set(\"extend\", baton->extendWith));\n        }\n      }\n      // Median - must happen before blurring, due to the utility of blurring after thresholding\n      if (baton->medianSize > 0) {\n        image = image.median(baton->medianSize);\n      }\n\n      // Threshold - must happen before blurring, due to the utility of blurring after thresholding\n      // Threshold - must happen before unflatten to enable non-white unflattening\n      if (baton->threshold != 0) {\n        image = sharp::Threshold(image, baton->threshold, baton->thresholdGrayscale);\n      }\n\n      // Dilate - must happen before blurring, due to the utility of dilating after thresholding\n      if (baton->dilateWidth != 0) {\n        image = sharp::Dilate(image, baton->dilateWidth);\n      }\n\n      // Erode - must happen before blurring, due to the utility of eroding after thresholding\n      if (baton->erodeWidth != 0) {\n        image = sharp::Erode(image, baton->erodeWidth);\n      }\n\n      // Blur\n      if (shouldBlur) {\n        image = sharp::Blur(image, baton->blurSigma, baton->precision, baton->minAmpl);\n      }\n\n      // Unflatten the image\n      if (baton->unflatten) {\n        image = sharp::Unflatten(image);\n      }\n\n      // Convolve\n      if (shouldConv) {\n        image = sharp::Convolve(image,\n          baton->convKernelWidth, baton->convKernelHeight,\n          baton->convKernelScale, baton->convKernelOffset,\n          baton->convKernel);\n      }\n\n      // Recomb\n      if (!baton->recombMatrix.empty()) {\n        image = sharp::Recomb(image, baton->recombMatrix);\n      }\n\n      // Modulate\n      if (baton->brightness != 1.0 || baton->saturation != 1.0 || baton->hue != 0.0 || baton->lightness != 0.0) {\n        image = sharp::Modulate(image, baton->brightness, baton->saturation, baton->hue, baton->lightness);\n      }\n\n      // Sharpen\n      if (shouldSharpen) {\n        image = sharp::Sharpen(image, baton->sharpenSigma, baton->sharpenM1, baton->sharpenM2,\n          baton->sharpenX1, baton->sharpenY2, baton->sharpenY3);\n      }\n\n      // Reverse premultiplication after all transformations\n      if (shouldPremultiplyAlpha) {\n        image = image.unpremultiply().cast(premultiplyFormat);\n      }\n      baton->premultiplied = shouldPremultiplyAlpha;\n\n      // Composite\n      if (shouldComposite) {\n        std::vector<VImage> images = { image };\n        std::vector<int> modes, xs, ys;\n        for (Composite *composite : baton->composite) {\n          VImage compositeImage;\n          sharp::ImageType compositeImageType = sharp::ImageType::UNKNOWN;\n          composite->input->access = access;\n          std::tie(compositeImage, compositeImageType) = sharp::OpenInput(composite->input);\n\n          if (composite->input->autoOrient) {\n            // Respect EXIF Orientation\n            VipsAngle compositeAutoRotation = VIPS_ANGLE_D0;\n            bool compositeAutoFlop = false;\n            std::tie(compositeAutoRotation, compositeAutoFlop) =\n              CalculateExifRotationAndFlop(sharp::ExifOrientation(compositeImage));\n\n            compositeImage = sharp::RemoveExifOrientation(compositeImage);\n            compositeImage = sharp::StaySequential(compositeImage, compositeAutoRotation != VIPS_ANGLE_D0);\n\n            if (compositeAutoRotation != VIPS_ANGLE_D0) {\n              compositeImage = compositeImage.rot(compositeAutoRotation);\n            }\n            if (compositeAutoFlop) {\n              compositeImage = compositeImage.flip(VIPS_DIRECTION_HORIZONTAL);\n            }\n          }\n\n          // Verify within current dimensions\n          if (compositeImage.width() > image.width() || compositeImage.height() > image.height()) {\n            throw vips::VError(\"Image to composite must have same dimensions or smaller\");\n          }\n          // Check if overlay is tiled\n          if (composite->tile) {\n            int across = 0;\n            int down = 0;\n            // Use gravity in overlay\n            if (compositeImage.width() <= image.width()) {\n              across = static_cast<int>(ceil(static_cast<double>(image.width()) / compositeImage.width()));\n              // Ensure odd number of tiles across when gravity is centre, north or south\n              if (composite->gravity == 0 || composite->gravity == 1 || composite->gravity == 3) {\n                across |= 1;\n              }\n            }\n            if (compositeImage.height() <= image.height()) {\n              down = static_cast<int>(ceil(static_cast<double>(image.height()) / compositeImage.height()));\n              // Ensure odd number of tiles down when gravity is centre, east or west\n              if (composite->gravity == 0 || composite->gravity == 2 || composite->gravity == 4) {\n                down |= 1;\n              }\n            }\n            if (across != 0 || down != 0) {\n              int left;\n              int top;\n              compositeImage = sharp::StaySequential(compositeImage).replicate(across, down);\n              if (composite->hasOffset) {\n                std::tie(left, top) = sharp::CalculateCrop(\n                  compositeImage.width(), compositeImage.height(), image.width(), image.height(),\n                  composite->left, composite->top);\n              } else {\n                std::tie(left, top) = sharp::CalculateCrop(\n                  compositeImage.width(), compositeImage.height(), image.width(), image.height(), composite->gravity);\n              }\n              compositeImage = compositeImage.extract_area(left, top, image.width(), image.height());\n            }\n            // gravity was used for extract_area, set it back to its default value of 0\n            composite->gravity = 0;\n          }\n          // Ensure image to composite is with unpremultiplied alpha\n          compositeImage = sharp::EnsureAlpha(compositeImage, 1);\n          if (composite->premultiplied) compositeImage = compositeImage.unpremultiply();\n          // Calculate position\n          int left;\n          int top;\n          if (composite->hasOffset) {\n            // Composite image at given offsets\n            if (composite->tile) {\n              std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(),\n                compositeImage.width(), compositeImage.height(), composite->left, composite->top);\n            } else {\n              left = composite->left;\n              top = composite->top;\n            }\n          } else {\n            // Composite image with given gravity\n            std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(),\n              compositeImage.width(), compositeImage.height(), composite->gravity);\n          }\n          images.push_back(compositeImage);\n          modes.push_back(composite->mode);\n          xs.push_back(left);\n          ys.push_back(top);\n        }\n        image = VImage::composite(images, modes, VImage::option()\n          ->set(\"compositing_space\", baton->colourspacePipeline == VIPS_INTERPRETATION_LAST\n            ? VIPS_INTERPRETATION_sRGB\n            : baton->colourspacePipeline)\n          ->set(\"x\", xs)\n          ->set(\"y\", ys));\n        image = sharp::RemoveGifPalette(image);\n      }\n\n      // Gamma decoding (brighten)\n      if (baton->gammaOut >= 1 && baton->gammaOut <= 3) {\n        image = sharp::Gamma(image, baton->gammaOut);\n      }\n\n      // Linear adjustment (a * in + b)\n      if (!baton->linearA.empty()) {\n        image = sharp::Linear(image, baton->linearA, baton->linearB);\n      }\n\n      // Apply normalisation - stretch luminance to cover full dynamic range\n      if (baton->normalise) {\n        image = sharp::StaySequential(image);\n        image = sharp::Normalise(image, baton->normaliseLower, baton->normaliseUpper);\n      }\n\n      // Apply contrast limiting adaptive histogram equalization (CLAHE)\n      if (baton->claheWidth != 0 && baton->claheHeight != 0) {\n        image = sharp::StaySequential(image);\n        image = sharp::Clahe(image, baton->claheWidth, baton->claheHeight, baton->claheMaxSlope);\n      }\n\n      // Apply bitwise boolean operation between images\n      if (baton->boolean != nullptr) {\n        VImage booleanImage;\n        sharp::ImageType booleanImageType = sharp::ImageType::UNKNOWN;\n        baton->boolean->access = access;\n        std::tie(booleanImage, booleanImageType) = sharp::OpenInput(baton->boolean);\n        booleanImage = sharp::EnsureColourspace(booleanImage, baton->colourspacePipeline);\n        image = sharp::Boolean(image, booleanImage, baton->booleanOp);\n        image = sharp::RemoveGifPalette(image);\n      }\n\n      // Apply per-channel Bandbool bitwise operations after all other operations\n      if (baton->bandBoolOp >= VIPS_OPERATION_BOOLEAN_AND && baton->bandBoolOp < VIPS_OPERATION_BOOLEAN_LAST) {\n        image = sharp::Bandbool(image, baton->bandBoolOp);\n      }\n\n      // Tint the image\n      if (baton->tint[0] >= 0.0) {\n        image = sharp::Tint(image, baton->tint);\n      }\n\n      // Remove alpha channel, if any\n      if (baton->removeAlpha) {\n        image = sharp::RemoveAlpha(image);\n      }\n\n      // Ensure alpha channel, if missing\n      if (baton->ensureAlpha != -1) {\n        image = sharp::EnsureAlpha(image, baton->ensureAlpha);\n      }\n\n      // Ensure output colour space\n      if (sharp::Is16Bit(image.interpretation())) {\n        image = image.cast(VIPS_FORMAT_USHORT);\n      }\n      if (image.interpretation() != baton->colourspace) {\n        image = image.colourspace(baton->colourspace, VImage::option()->set(\"source_space\", image.interpretation()));\n        if (inputProfile.first != nullptr && baton->withIccProfile.empty()) {\n          image = sharp::SetProfile(image, inputProfile);\n        }\n      }\n\n      // Extract channel\n      if (baton->extractChannel > -1) {\n        if (baton->extractChannel >= image.bands()) {\n          if (baton->extractChannel == 3 && image.has_alpha()) {\n            baton->extractChannel = image.bands() - 1;\n          } else {\n            (baton->err)\n              .append(\"Cannot extract channel \").append(std::to_string(baton->extractChannel))\n              .append(\" from image with channels 0-\").append(std::to_string(image.bands() - 1));\n            return Error();\n          }\n        }\n        VipsInterpretation colourspace = sharp::Is16Bit(image.interpretation())\n          ? VIPS_INTERPRETATION_GREY16\n          : VIPS_INTERPRETATION_B_W;\n        image = image\n          .extract_band(baton->extractChannel)\n          .copy(VImage::option()->set(\"interpretation\", colourspace));\n      }\n\n      // Apply output ICC profile\n      if (!baton->withIccProfile.empty()) {\n        try {\n          image = image.icc_transform(const_cast<char*>(baton->withIccProfile.data()), VImage::option()\n            ->set(\"input_profile\", processingProfile)\n            ->set(\"embedded\", true)\n            ->set(\"depth\", sharp::Is16Bit(image.interpretation()) ? 16 : 8)\n            ->set(\"intent\", VIPS_INTENT_PERCEPTUAL));\n        } catch(...) {\n          sharp::VipsWarningCallback(nullptr, G_LOG_LEVEL_WARNING, \"Invalid profile\", nullptr);\n        }\n      }\n\n      // Negate the colours in the image\n      if (baton->negate) {\n        image = sharp::Negate(image, baton->negateAlpha);\n      }\n\n      // Override EXIF Orientation tag\n      if (baton->withMetadataOrientation != -1) {\n        image = sharp::SetExifOrientation(image, baton->withMetadataOrientation);\n      }\n      // Override pixel density\n      if (baton->withMetadataDensity > 0) {\n        image = sharp::SetDensity(image, baton->withMetadataDensity);\n      }\n      // EXIF key/value pairs\n      if (baton->keepMetadata & VIPS_FOREIGN_KEEP_EXIF) {\n        image = image.copy();\n        if (!baton->withExifMerge) {\n          image = sharp::RemoveExif(image);\n        }\n        for (const auto& [key, value] : baton->withExif) {\n          image.set(key.c_str(), value.c_str());\n        }\n      }\n      // XMP buffer\n      if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_XMP) && !baton->withXmp.empty()) {\n        image = image.copy();\n        image.set(VIPS_META_XMP_NAME, nullptr,\n          const_cast<void*>(static_cast<void const*>(baton->withXmp.c_str())), baton->withXmp.size());\n      }\n      // Number of channels used in output image\n      baton->channels = image.bands();\n      baton->width = image.width();\n      baton->height = image.height();\n\n      image = sharp::SetAnimationProperties(\n        image, nPages, targetPageHeight, baton->delay, baton->loop);\n\n      if (image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT) {\n        baton->pageHeightOut = image.get_int(VIPS_META_PAGE_HEIGHT);\n        baton->pagesOut = image.get_int(VIPS_META_N_PAGES);\n      }\n\n      // Output\n      sharp::SetTimeout(image, baton->timeoutSeconds);\n      if (baton->fileOut.empty()) {\n        // Buffer output\n        if (baton->formatOut == \"jpeg\" || (baton->formatOut == \"input\" && inputImageType == sharp::ImageType::JPEG)) {\n          // Write JPEG to buffer\n          sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);\n          VipsArea *area = reinterpret_cast<VipsArea*>(image.jpegsave_buffer(VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"Q\", baton->jpegQuality)\n            ->set(\"interlace\", baton->jpegProgressive)\n            ->set(\"subsample_mode\", baton->jpegChromaSubsampling == \"4:4:4\"\n              ? VIPS_FOREIGN_SUBSAMPLE_OFF\n              : VIPS_FOREIGN_SUBSAMPLE_ON)\n            ->set(\"trellis_quant\", baton->jpegTrellisQuantisation)\n            ->set(\"quant_table\", baton->jpegQuantisationTable)\n            ->set(\"overshoot_deringing\", baton->jpegOvershootDeringing)\n            ->set(\"optimize_scans\", baton->jpegOptimiseScans)\n            ->set(\"optimize_coding\", baton->jpegOptimiseCoding)));\n          baton->bufferOut = static_cast<char*>(area->data);\n          baton->bufferOutLength = area->length;\n          area->free_fn = nullptr;\n          vips_area_unref(area);\n          baton->formatOut = \"jpeg\";\n          if (baton->colourspace == VIPS_INTERPRETATION_CMYK) {\n            baton->channels = std::min(baton->channels, 4);\n          } else {\n            baton->channels = std::min(baton->channels, 3);\n          }\n        } else if (baton->formatOut == \"jp2\" || (baton->formatOut == \"input\"\n          && inputImageType == sharp::ImageType::JP2)) {\n          // Write JP2 to Buffer\n          sharp::AssertImageTypeDimensions(image, sharp::ImageType::JP2);\n          VipsArea *area = reinterpret_cast<VipsArea*>(image.jp2ksave_buffer(VImage::option()\n            ->set(\"Q\", baton->jp2Quality)\n            ->set(\"lossless\", baton->jp2Lossless)\n            ->set(\"subsample_mode\", baton->jp2ChromaSubsampling == \"4:4:4\"\n              ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)\n            ->set(\"tile_height\", baton->jp2TileHeight)\n            ->set(\"tile_width\", baton->jp2TileWidth)));\n          baton->bufferOut = static_cast<char*>(area->data);\n          baton->bufferOutLength = area->length;\n          area->free_fn = nullptr;\n          vips_area_unref(area);\n          baton->formatOut = \"jp2\";\n        } else if (baton->formatOut == \"png\" || (baton->formatOut == \"input\" &&\n          (inputImageType == sharp::ImageType::PNG || inputImageType == sharp::ImageType::SVG))) {\n          // Write PNG to buffer\n          sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG);\n          VipsArea *area = reinterpret_cast<VipsArea*>(image.pngsave_buffer(VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"interlace\", baton->pngProgressive)\n            ->set(\"compression\", baton->pngCompressionLevel)\n            ->set(\"filter\", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE)\n            ->set(\"palette\", baton->pngPalette)\n            ->set(\"Q\", baton->pngQuality)\n            ->set(\"effort\", baton->pngEffort)\n            ->set(\"bitdepth\", sharp::Is16Bit(image.interpretation()) ? 16 : baton->pngBitdepth)\n            ->set(\"dither\", baton->pngDither)));\n          baton->bufferOut = static_cast<char*>(area->data);\n          baton->bufferOutLength = area->length;\n          area->free_fn = nullptr;\n          vips_area_unref(area);\n          baton->formatOut = \"png\";\n        } else if (baton->formatOut == \"webp\" ||\n          (baton->formatOut == \"input\" && inputImageType == sharp::ImageType::WEBP)) {\n          // Write WEBP to buffer\n          sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP);\n          VipsArea *area = reinterpret_cast<VipsArea*>(image.webpsave_buffer(VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"Q\", baton->webpQuality)\n            ->set(\"lossless\", baton->webpLossless)\n            ->set(\"near_lossless\", baton->webpNearLossless)\n            ->set(\"smart_subsample\", baton->webpSmartSubsample)\n            ->set(\"smart_deblock\", baton->webpSmartDeblock)\n            ->set(\"preset\", baton->webpPreset)\n            ->set(\"effort\", baton->webpEffort)\n            ->set(\"min_size\", baton->webpMinSize)\n            ->set(\"mixed\", baton->webpMixed)\n            ->set(\"alpha_q\", baton->webpAlphaQuality)));\n          baton->bufferOut = static_cast<char*>(area->data);\n          baton->bufferOutLength = area->length;\n          area->free_fn = nullptr;\n          vips_area_unref(area);\n          baton->formatOut = \"webp\";\n        } else if (baton->formatOut == \"gif\" ||\n          (baton->formatOut == \"input\" && inputImageType == sharp::ImageType::GIF)) {\n          // Write GIF to buffer\n          sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF);\n          VipsArea *area = reinterpret_cast<VipsArea*>(image.gifsave_buffer(VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"bitdepth\", baton->gifBitdepth)\n            ->set(\"effort\", baton->gifEffort)\n            ->set(\"reuse\", baton->gifReuse)\n            ->set(\"interlace\", baton->gifProgressive)\n            ->set(\"interframe_maxerror\", baton->gifInterFrameMaxError)\n            ->set(\"interpalette_maxerror\", baton->gifInterPaletteMaxError)\n            ->set(\"keep_duplicate_frames\", baton->gifKeepDuplicateFrames)\n            ->set(\"dither\", baton->gifDither)));\n          baton->bufferOut = static_cast<char*>(area->data);\n          baton->bufferOutLength = area->length;\n          area->free_fn = nullptr;\n          vips_area_unref(area);\n          baton->formatOut = \"gif\";\n        } else if (baton->formatOut == \"tiff\" ||\n          (baton->formatOut == \"input\" && inputImageType == sharp::ImageType::TIFF)) {\n          // Write TIFF to buffer\n          if (baton->tiffCompression == VIPS_FOREIGN_TIFF_COMPRESSION_JPEG) {\n            sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);\n            baton->channels = std::min(baton->channels, 3);\n          }\n          // Cast pixel values to float, if required\n          if (baton->tiffPredictor == VIPS_FOREIGN_TIFF_PREDICTOR_FLOAT) {\n            image = image.cast(VIPS_FORMAT_FLOAT);\n          }\n          VipsArea *area = reinterpret_cast<VipsArea*>(image.tiffsave_buffer(VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"Q\", baton->tiffQuality)\n            ->set(\"bitdepth\", baton->tiffBitdepth)\n            ->set(\"compression\", baton->tiffCompression)\n            ->set(\"bigtiff\", baton->tiffBigtiff)\n            ->set(\"miniswhite\", baton->tiffMiniswhite)\n            ->set(\"predictor\", baton->tiffPredictor)\n            ->set(\"pyramid\", baton->tiffPyramid)\n            ->set(\"tile\", baton->tiffTile)\n            ->set(\"tile_height\", baton->tiffTileHeight)\n            ->set(\"tile_width\", baton->tiffTileWidth)\n            ->set(\"xres\", baton->tiffXres)\n            ->set(\"yres\", baton->tiffYres)\n            ->set(\"resunit\", baton->tiffResolutionUnit)));\n          baton->bufferOut = static_cast<char*>(area->data);\n          baton->bufferOutLength = area->length;\n          area->free_fn = nullptr;\n          vips_area_unref(area);\n          baton->formatOut = \"tiff\";\n        } else if (baton->formatOut == \"heif\" ||\n          (baton->formatOut == \"input\" && inputImageType == sharp::ImageType::HEIF)) {\n          // Write HEIF to buffer\n          sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF);\n          image = sharp::RemoveAnimationProperties(image);\n          VipsArea *area = reinterpret_cast<VipsArea*>(image.heifsave_buffer(VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"Q\", baton->heifQuality)\n            ->set(\"compression\", baton->heifCompression)\n            ->set(\"effort\", baton->heifEffort)\n            ->set(\"bitdepth\", baton->heifBitdepth)\n            ->set(\"subsample_mode\", baton->heifChromaSubsampling == \"4:4:4\"\n              ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)\n            ->set(\"lossless\", baton->heifLossless)));\n          baton->bufferOut = static_cast<char*>(area->data);\n          baton->bufferOutLength = area->length;\n          area->free_fn = nullptr;\n          vips_area_unref(area);\n          baton->formatOut = \"heif\";\n        } else if (baton->formatOut == \"dz\") {\n          // Write DZ to buffer\n          baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP;\n          if (!image.has_alpha()) {\n            baton->tileBackground.pop_back();\n          }\n          image = sharp::StaySequential(image, baton->tileAngle != 0);\n          vips::VOption *options = BuildOptionsDZ(baton);\n          VipsArea *area = reinterpret_cast<VipsArea*>(image.dzsave_buffer(options));\n          baton->bufferOut = static_cast<char*>(area->data);\n          baton->bufferOutLength = area->length;\n          area->free_fn = nullptr;\n          vips_area_unref(area);\n          baton->formatOut = \"dz\";\n        } else if (baton->formatOut == \"jxl\" ||\n          (baton->formatOut == \"input\" && inputImageType == sharp::ImageType::JXL)) {\n          // Write JXL to buffer\n          image = sharp::RemoveAnimationProperties(image);\n          VipsArea *area = reinterpret_cast<VipsArea*>(image.jxlsave_buffer(VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"distance\", baton->jxlDistance)\n            ->set(\"tier\", baton->jxlDecodingTier)\n            ->set(\"effort\", baton->jxlEffort)\n            ->set(\"lossless\", baton->jxlLossless)));\n          baton->bufferOut = static_cast<char*>(area->data);\n          baton->bufferOutLength = area->length;\n          area->free_fn = nullptr;\n          vips_area_unref(area);\n          baton->formatOut = \"jxl\";\n        } else if (baton->formatOut == \"raw\" ||\n          (baton->formatOut == \"input\" && inputImageType == sharp::ImageType::RAW)) {\n          // Write raw, uncompressed image data to buffer\n          if (baton->greyscale || image.interpretation() == VIPS_INTERPRETATION_B_W) {\n            // Extract first band for greyscale image\n            image = image[0];\n            baton->channels = 1;\n          }\n          if (image.format() != baton->rawDepth) {\n            // Cast pixels to requested format\n            image = image.cast(baton->rawDepth);\n          }\n          // Get raw image data\n          baton->bufferOut = static_cast<char*>(image.write_to_memory(&baton->bufferOutLength));\n          if (baton->bufferOut == nullptr) {\n            (baton->err).append(\"Could not allocate enough memory for raw output\");\n            return Error();\n          }\n          baton->formatOut = \"raw\";\n        } else {\n          // Unsupported output format\n          (baton->err).append(\"Unsupported output format \");\n          if (baton->formatOut == \"input\") {\n            (baton->err).append(\"when trying to match input format of \");\n            (baton->err).append(ImageTypeId(inputImageType));\n          } else {\n            (baton->err).append(baton->formatOut);\n          }\n          return Error();\n        }\n      } else {\n        // File output\n        bool const isJpeg = sharp::IsJpeg(baton->fileOut);\n        bool const isPng = sharp::IsPng(baton->fileOut);\n        bool const isWebp = sharp::IsWebp(baton->fileOut);\n        bool const isGif = sharp::IsGif(baton->fileOut);\n        bool const isTiff = sharp::IsTiff(baton->fileOut);\n        bool const isJp2 = sharp::IsJp2(baton->fileOut);\n        bool const isHeif = sharp::IsHeif(baton->fileOut);\n        bool const isJxl = sharp::IsJxl(baton->fileOut);\n        bool const isDz = sharp::IsDz(baton->fileOut);\n        bool const isDzZip = sharp::IsDzZip(baton->fileOut);\n        bool const isV = sharp::IsV(baton->fileOut);\n        bool const mightMatchInput = baton->formatOut == \"input\";\n        bool const willMatchInput = mightMatchInput &&\n         !(isJpeg || isPng || isWebp || isGif || isTiff || isJp2 || isHeif || isDz || isDzZip || isV);\n\n        if (baton->formatOut == \"jpeg\" || (mightMatchInput && isJpeg) ||\n          (willMatchInput && inputImageType == sharp::ImageType::JPEG)) {\n          // Write JPEG to file\n          sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);\n          image.jpegsave(const_cast<char*>(baton->fileOut.data()), VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"Q\", baton->jpegQuality)\n            ->set(\"interlace\", baton->jpegProgressive)\n            ->set(\"subsample_mode\", baton->jpegChromaSubsampling == \"4:4:4\"\n              ? VIPS_FOREIGN_SUBSAMPLE_OFF\n              : VIPS_FOREIGN_SUBSAMPLE_ON)\n            ->set(\"trellis_quant\", baton->jpegTrellisQuantisation)\n            ->set(\"quant_table\", baton->jpegQuantisationTable)\n            ->set(\"overshoot_deringing\", baton->jpegOvershootDeringing)\n            ->set(\"optimize_scans\", baton->jpegOptimiseScans)\n            ->set(\"optimize_coding\", baton->jpegOptimiseCoding));\n          baton->formatOut = \"jpeg\";\n          baton->channels = std::min(baton->channels, 3);\n        } else if (baton->formatOut == \"jp2\" || (mightMatchInput && isJp2) ||\n          (willMatchInput && (inputImageType == sharp::ImageType::JP2))) {\n          // Write JP2 to file\n          sharp::AssertImageTypeDimensions(image, sharp::ImageType::JP2);\n          image.jp2ksave(const_cast<char*>(baton->fileOut.data()), VImage::option()\n            ->set(\"Q\", baton->jp2Quality)\n            ->set(\"lossless\", baton->jp2Lossless)\n            ->set(\"subsample_mode\", baton->jp2ChromaSubsampling == \"4:4:4\"\n              ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)\n            ->set(\"tile_height\", baton->jp2TileHeight)\n            ->set(\"tile_width\", baton->jp2TileWidth));\n            baton->formatOut = \"jp2\";\n        } else if (baton->formatOut == \"png\" || (mightMatchInput && isPng) || (willMatchInput &&\n          (inputImageType == sharp::ImageType::PNG || inputImageType == sharp::ImageType::SVG))) {\n          // Write PNG to file\n          sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG);\n          image.pngsave(const_cast<char*>(baton->fileOut.data()), VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"interlace\", baton->pngProgressive)\n            ->set(\"compression\", baton->pngCompressionLevel)\n            ->set(\"filter\", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE)\n            ->set(\"palette\", baton->pngPalette)\n            ->set(\"Q\", baton->pngQuality)\n            ->set(\"bitdepth\", sharp::Is16Bit(image.interpretation()) ? 16 : baton->pngBitdepth)\n            ->set(\"effort\", baton->pngEffort)\n            ->set(\"dither\", baton->pngDither));\n          baton->formatOut = \"png\";\n        } else if (baton->formatOut == \"webp\" || (mightMatchInput && isWebp) ||\n          (willMatchInput && inputImageType == sharp::ImageType::WEBP)) {\n          // Write WEBP to file\n          sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP);\n          image.webpsave(const_cast<char*>(baton->fileOut.data()), VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"Q\", baton->webpQuality)\n            ->set(\"lossless\", baton->webpLossless)\n            ->set(\"near_lossless\", baton->webpNearLossless)\n            ->set(\"smart_subsample\", baton->webpSmartSubsample)\n            ->set(\"smart_deblock\", baton->webpSmartDeblock)\n            ->set(\"preset\", baton->webpPreset)\n            ->set(\"effort\", baton->webpEffort)\n            ->set(\"min_size\", baton->webpMinSize)\n            ->set(\"mixed\", baton->webpMixed)\n            ->set(\"alpha_q\", baton->webpAlphaQuality));\n          baton->formatOut = \"webp\";\n        } else if (baton->formatOut == \"gif\" || (mightMatchInput && isGif) ||\n          (willMatchInput && inputImageType == sharp::ImageType::GIF)) {\n          // Write GIF to file\n          sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF);\n          image.gifsave(const_cast<char*>(baton->fileOut.data()), VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"bitdepth\", baton->gifBitdepth)\n            ->set(\"effort\", baton->gifEffort)\n            ->set(\"reuse\", baton->gifReuse)\n            ->set(\"interlace\", baton->gifProgressive)\n            ->set(\"interframe_maxerror\", baton->gifInterFrameMaxError)\n            ->set(\"interpalette_maxerror\", baton->gifInterPaletteMaxError)\n            ->set(\"keep_duplicate_frames\", baton->gifKeepDuplicateFrames)\n            ->set(\"dither\", baton->gifDither));\n          baton->formatOut = \"gif\";\n        } else if (baton->formatOut == \"tiff\" || (mightMatchInput && isTiff) ||\n          (willMatchInput && inputImageType == sharp::ImageType::TIFF)) {\n          // Write TIFF to file\n          if (baton->tiffCompression == VIPS_FOREIGN_TIFF_COMPRESSION_JPEG) {\n            sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);\n            baton->channels = std::min(baton->channels, 3);\n          }\n          // Cast pixel values to float, if required\n          if (baton->tiffPredictor == VIPS_FOREIGN_TIFF_PREDICTOR_FLOAT) {\n            image = image.cast(VIPS_FORMAT_FLOAT);\n          }\n          image.tiffsave(const_cast<char*>(baton->fileOut.data()), VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"Q\", baton->tiffQuality)\n            ->set(\"bitdepth\", baton->tiffBitdepth)\n            ->set(\"compression\", baton->tiffCompression)\n            ->set(\"bigtiff\", baton->tiffBigtiff)\n            ->set(\"miniswhite\", baton->tiffMiniswhite)\n            ->set(\"predictor\", baton->tiffPredictor)\n            ->set(\"pyramid\", baton->tiffPyramid)\n            ->set(\"tile\", baton->tiffTile)\n            ->set(\"tile_height\", baton->tiffTileHeight)\n            ->set(\"tile_width\", baton->tiffTileWidth)\n            ->set(\"xres\", baton->tiffXres)\n            ->set(\"yres\", baton->tiffYres)\n            ->set(\"resunit\", baton->tiffResolutionUnit));\n          baton->formatOut = \"tiff\";\n        } else if (baton->formatOut == \"heif\" || (mightMatchInput && isHeif) ||\n          (willMatchInput && inputImageType == sharp::ImageType::HEIF)) {\n          // Write HEIF to file\n          sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF);\n          image = sharp::RemoveAnimationProperties(image);\n          image.heifsave(const_cast<char*>(baton->fileOut.data()), VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"Q\", baton->heifQuality)\n            ->set(\"compression\", baton->heifCompression)\n            ->set(\"effort\", baton->heifEffort)\n            ->set(\"bitdepth\", baton->heifBitdepth)\n            ->set(\"subsample_mode\", baton->heifChromaSubsampling == \"4:4:4\"\n              ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)\n            ->set(\"lossless\", baton->heifLossless));\n          baton->formatOut = \"heif\";\n        } else if (baton->formatOut == \"jxl\" || (mightMatchInput && isJxl) ||\n          (willMatchInput && inputImageType == sharp::ImageType::JXL)) {\n          // Write JXL to file\n          image = sharp::RemoveAnimationProperties(image);\n          image.jxlsave(const_cast<char*>(baton->fileOut.data()), VImage::option()\n            ->set(\"keep\", baton->keepMetadata)\n            ->set(\"distance\", baton->jxlDistance)\n            ->set(\"tier\", baton->jxlDecodingTier)\n            ->set(\"effort\", baton->jxlEffort)\n            ->set(\"lossless\", baton->jxlLossless));\n          baton->formatOut = \"jxl\";\n        } else if (baton->formatOut == \"dz\" || isDz || isDzZip) {\n          // Write DZ to file\n          if (isDzZip) {\n            baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP;\n          }\n          if (!image.has_alpha()) {\n            baton->tileBackground.pop_back();\n          }\n          image = sharp::StaySequential(image, baton->tileAngle != 0);\n          vips::VOption *options = BuildOptionsDZ(baton);\n          image.dzsave(const_cast<char*>(baton->fileOut.data()), options);\n          baton->formatOut = \"dz\";\n        } else if (baton->formatOut == \"v\" || (mightMatchInput && isV) ||\n          (willMatchInput && inputImageType == sharp::ImageType::VIPS)) {\n          // Write V to file\n          image.vipssave(const_cast<char*>(baton->fileOut.data()), VImage::option()\n            ->set(\"keep\", baton->keepMetadata));\n          baton->formatOut = \"v\";\n        } else {\n          // Unsupported output format\n          (baton->err).append(\"Unsupported output format \" + baton->fileOut);\n          return Error();\n        }\n      }\n    } catch (vips::VError const &err) {\n      char const *what = err.what();\n      if (what && what[0]) {\n        (baton->err).append(what);\n      } else {\n        if (baton->input->failOn == VIPS_FAIL_ON_WARNING) {\n          (baton->err).append(\"Warning treated as error due to failOn setting\");\n          baton->errUseWarning = true;\n        } else {\n          (baton->err).append(\"Unknown error\");\n        }\n      }\n    }\n    // Clean up libvips' per-request data and threads\n    vips_error_clear();\n    vips_thread_shutdown();\n  }\n\n  void OnOK() {\n    Napi::Env env = Env();\n    Napi::HandleScope scope(env);\n\n    // Handle warnings\n    std::string warning = sharp::VipsWarningPop();\n    while (!warning.empty()) {\n      if (baton->errUseWarning) {\n        (baton->err).append(\"\\n\").append(warning);\n      } else {\n        debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) });\n      }\n      warning = sharp::VipsWarningPop();\n    }\n\n    if (baton->err.empty()) {\n      int width = baton->width;\n      int height = baton->height;\n      if (baton->topOffsetPre != -1 && (baton->width == -1 || baton->height == -1)) {\n        width = baton->widthPre;\n        height = baton->heightPre;\n      }\n      if (baton->topOffsetPost != -1) {\n        width = baton->widthPost;\n        height = baton->heightPost;\n      }\n      // Info Object\n      Napi::Object info = Napi::Object::New(env);\n      info.Set(\"format\", baton->formatOut);\n      info.Set(\"width\", static_cast<uint32_t>(width));\n      info.Set(\"height\", static_cast<uint32_t>(height));\n      info.Set(\"channels\", static_cast<uint32_t>(baton->channels));\n      if (baton->formatOut == \"raw\") {\n        info.Set(\"depth\", vips_enum_nick(VIPS_TYPE_BAND_FORMAT, baton->rawDepth));\n      }\n      info.Set(\"premultiplied\", baton->premultiplied);\n      if (baton->hasCropOffset) {\n        info.Set(\"cropOffsetLeft\", static_cast<int32_t>(baton->cropOffsetLeft));\n        info.Set(\"cropOffsetTop\", static_cast<int32_t>(baton->cropOffsetTop));\n      }\n      if (baton->hasAttentionCenter) {\n        info.Set(\"attentionX\", static_cast<int32_t>(baton->attentionX));\n        info.Set(\"attentionY\", static_cast<int32_t>(baton->attentionY));\n      }\n      if (baton->trimThreshold >= 0.0) {\n        info.Set(\"trimOffsetLeft\", static_cast<int32_t>(baton->trimOffsetLeft));\n        info.Set(\"trimOffsetTop\", static_cast<int32_t>(baton->trimOffsetTop));\n      }\n      if (baton->input->textAutofitDpi) {\n        info.Set(\"textAutofitDpi\", static_cast<uint32_t>(baton->input->textAutofitDpi));\n      }\n      if (baton->pageHeightOut) {\n        info.Set(\"pageHeight\", static_cast<int32_t>(baton->pageHeightOut));\n        info.Set(\"pages\", static_cast<int32_t>(baton->pagesOut));\n      }\n\n      if (baton->bufferOutLength > 0) {\n        // Add buffer size to info\n        info.Set(\"size\", static_cast<uint32_t>(baton->bufferOutLength));\n        // Pass ownership of output data to Buffer instance\n        Napi::Buffer<char> data = Napi::Buffer<char>::NewOrCopy(env, static_cast<char*>(baton->bufferOut),\n          baton->bufferOutLength, sharp::FreeCallback);\n        Callback().Call(Receiver().Value(), { env.Null(), data, info });\n      } else {\n        // Add file size to info\n        if (baton->formatOut != \"dz\" || sharp::IsDzZip(baton->fileOut)) {\n          try {\n            uint32_t const size = static_cast<uint32_t>(\n              std::filesystem::file_size(std::filesystem::u8path(baton->fileOut)));\n            info.Set(\"size\", size);\n          } catch (...) {}\n        }\n        Callback().Call(Receiver().Value(), { env.Null(), info });\n      }\n    } else {\n      Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });\n    }\n\n    // Delete baton\n    delete baton->input;\n    delete baton->boolean;\n    for (Composite *composite : baton->composite) {\n      delete composite->input;\n      delete composite;\n    }\n    for (sharp::InputDescriptor *input : baton->joinChannelIn) {\n      delete input;\n    }\n    for (sharp::InputDescriptor *input : baton->join) {\n      delete input;\n    }\n    delete baton;\n\n    // Decrement processing task counter\n    sharp::counterProcess--;\n    Napi::Number queueLength = Napi::Number::New(env, static_cast<int>(sharp::counterQueue));\n    queueListener.Call(Receiver().Value(), { queueLength });\n  }\n\n private:\n  PipelineBaton *baton;\n  Napi::FunctionReference debuglog;\n  Napi::FunctionReference queueListener;\n\n  void MultiPageUnsupported(int const pages, std::string op) {\n    if (pages > 1) {\n      throw vips::VError(op + \" is not supported for multi-page images\");\n    }\n  }\n\n  /*\n    Calculate the angle of rotation and need-to-flip for the given Exif orientation\n    By default, returns zero, i.e. no rotation.\n  */\n  std::tuple<VipsAngle, bool>\n  CalculateExifRotationAndFlop(int const exifOrientation) {\n    VipsAngle rotate = VIPS_ANGLE_D0;\n    bool flop = false;\n    switch (exifOrientation) {\n      case 6: rotate = VIPS_ANGLE_D90; break;\n      case 3: rotate = VIPS_ANGLE_D180; break;\n      case 8: rotate = VIPS_ANGLE_D270; break;\n      case 2: flop = true; break;\n      case 7: flop = true; rotate = VIPS_ANGLE_D270; break;\n      case 4: flop = true; rotate = VIPS_ANGLE_D180; break;\n      case 5: flop = true; rotate = VIPS_ANGLE_D90; break;\n    }\n    return std::make_tuple(rotate, flop);\n  }\n\n  /*\n    Calculate the rotation for the given angle.\n    Supports any positive or negative angle that is a multiple of 90.\n  */\n  VipsAngle\n  CalculateAngleRotation(int angle) {\n    angle = angle % 360;\n    if (angle < 0)\n      angle = 360 + angle;\n    switch (angle) {\n      case 90: return VIPS_ANGLE_D90;\n      case 180: return VIPS_ANGLE_D180;\n      case 270: return VIPS_ANGLE_D270;\n    }\n    return VIPS_ANGLE_D0;\n  }\n\n  /*\n    Assemble the suffix argument to dzsave, which is the format (by extname)\n    alongside comma-separated arguments to the corresponding `formatsave` vips\n    action.\n  */\n  std::string\n  AssembleSuffixString(std::string extname, std::vector<std::pair<std::string, std::string>> options) {\n    std::string argument;\n    for (const auto& [key, value] : options) {\n      if (!argument.empty()) {\n        argument += \",\";\n      }\n      argument += key + \"=\" + value;\n    }\n    return extname + \"[\" + argument + \"]\";\n  }\n\n  /*\n    Build VOption for dzsave\n  */\n  vips::VOption*\n  BuildOptionsDZ(PipelineBaton *baton) {\n    // Forward format options through suffix\n    std::string suffix;\n    if (baton->tileFormat == \"png\") {\n      std::vector<std::pair<std::string, std::string>> options {\n        {\"interlace\", baton->pngProgressive ? \"true\" : \"false\"},\n        {\"compression\", std::to_string(baton->pngCompressionLevel)},\n        {\"filter\", baton->pngAdaptiveFiltering ? \"all\" : \"none\"}\n      };\n      suffix = AssembleSuffixString(\".png\", options);\n    } else if (baton->tileFormat == \"webp\") {\n      std::vector<std::pair<std::string, std::string>> options {\n        {\"Q\", std::to_string(baton->webpQuality)},\n        {\"alpha_q\", std::to_string(baton->webpAlphaQuality)},\n        {\"lossless\", baton->webpLossless ? \"true\" : \"false\"},\n        {\"near_lossless\", baton->webpNearLossless ? \"true\" : \"false\"},\n        {\"smart_subsample\", baton->webpSmartSubsample ? \"true\" : \"false\"},\n        {\"smart_deblock\", baton->webpSmartDeblock ? \"true\" : \"false\"},\n        {\"preset\", vips_enum_nick(VIPS_TYPE_FOREIGN_WEBP_PRESET, baton->webpPreset)},\n        {\"min_size\", baton->webpMinSize ? \"true\" : \"false\"},\n        {\"mixed\", baton->webpMixed ? \"true\" : \"false\"},\n        {\"effort\", std::to_string(baton->webpEffort)}\n      };\n      suffix = AssembleSuffixString(\".webp\", options);\n    } else {\n      std::vector<std::pair<std::string, std::string>> options {\n        {\"Q\", std::to_string(baton->jpegQuality)},\n        {\"interlace\", baton->jpegProgressive ? \"true\" : \"false\"},\n        {\"subsample_mode\", baton->jpegChromaSubsampling == \"4:4:4\" ? \"off\" : \"on\"},\n        {\"trellis_quant\", baton->jpegTrellisQuantisation ? \"true\" : \"false\"},\n        {\"quant_table\", std::to_string(baton->jpegQuantisationTable)},\n        {\"overshoot_deringing\", baton->jpegOvershootDeringing ? \"true\": \"false\"},\n        {\"optimize_scans\", baton->jpegOptimiseScans ? \"true\": \"false\"},\n        {\"optimize_coding\", baton->jpegOptimiseCoding ? \"true\": \"false\"}\n      };\n      std::string extname = baton->tileLayout == VIPS_FOREIGN_DZ_LAYOUT_DZ ? \".jpeg\" : \".jpg\";\n      suffix = AssembleSuffixString(extname, options);\n    }\n    vips::VOption *options = VImage::option()\n      ->set(\"keep\", baton->keepMetadata)\n      ->set(\"tile_size\", baton->tileSize)\n      ->set(\"overlap\", baton->tileOverlap)\n      ->set(\"container\", baton->tileContainer)\n      ->set(\"layout\", baton->tileLayout)\n      ->set(\"suffix\", const_cast<char*>(suffix.data()))\n      ->set(\"angle\", CalculateAngleRotation(baton->tileAngle))\n      ->set(\"background\", baton->tileBackground)\n      ->set(\"centre\", baton->tileCentre)\n      ->set(\"id\", const_cast<char*>(baton->tileId.data()))\n      ->set(\"skip_blanks\", baton->tileSkipBlanks);\n    if (baton->tileDepth < VIPS_FOREIGN_DZ_DEPTH_LAST) {\n      options->set(\"depth\", baton->tileDepth);\n    }\n    if (!baton->tileBasename.empty()) {\n      options->set(\"basename\", const_cast<char*>(baton->tileBasename.data()));\n    }\n    return options;\n  }\n\n  /*\n    Clear all thread-local data.\n  */\n  void Error() {\n    // Clean up libvips' per-request data and threads\n    vips_error_clear();\n    vips_thread_shutdown();\n  }\n};\n\n/*\n  pipeline(options, output, callback)\n*/\nNapi::Value pipeline(const Napi::CallbackInfo& info) {\n  // V8 objects are converted to non-V8 types held in the baton struct\n  PipelineBaton *baton = new PipelineBaton;\n  Napi::Object options = info[size_t(0)].As<Napi::Object>();\n\n  // Input\n  baton->input = sharp::CreateInputDescriptor(options.Get(\"input\").As<Napi::Object>());\n  // Join images together\n  if (sharp::HasAttr(options, \"join\")) {\n    Napi::Array join = options.Get(\"join\").As<Napi::Array>();\n    for (unsigned int i = 0; i < join.Length(); i++) {\n      baton->join.push_back(\n        sharp::CreateInputDescriptor(join.Get(i).As<Napi::Object>()));\n    }\n  }\n  // Extract image options\n  baton->topOffsetPre = sharp::AttrAsInt32(options, \"topOffsetPre\");\n  baton->leftOffsetPre = sharp::AttrAsInt32(options, \"leftOffsetPre\");\n  baton->widthPre = sharp::AttrAsInt32(options, \"widthPre\");\n  baton->heightPre = sharp::AttrAsInt32(options, \"heightPre\");\n  baton->topOffsetPost = sharp::AttrAsInt32(options, \"topOffsetPost\");\n  baton->leftOffsetPost = sharp::AttrAsInt32(options, \"leftOffsetPost\");\n  baton->widthPost = sharp::AttrAsInt32(options, \"widthPost\");\n  baton->heightPost = sharp::AttrAsInt32(options, \"heightPost\");\n  // Output image dimensions\n  baton->width = sharp::AttrAsInt32(options, \"width\");\n  baton->height = sharp::AttrAsInt32(options, \"height\");\n  // Canvas option\n  std::string canvas = sharp::AttrAsStr(options, \"canvas\");\n  if (canvas == \"crop\") {\n    baton->canvas = sharp::Canvas::CROP;\n  } else if (canvas == \"embed\") {\n    baton->canvas = sharp::Canvas::EMBED;\n  } else if (canvas == \"max\") {\n    baton->canvas = sharp::Canvas::MAX;\n  } else if (canvas == \"min\") {\n    baton->canvas = sharp::Canvas::MIN;\n  } else if (canvas == \"ignore_aspect\") {\n    baton->canvas = sharp::Canvas::IGNORE_ASPECT;\n  }\n  // Composite\n  Napi::Array compositeArray = options.Get(\"composite\").As<Napi::Array>();\n  for (unsigned int i = 0; i < compositeArray.Length(); i++) {\n    Napi::Object compositeObject = compositeArray.Get(i).As<Napi::Object>();\n    Composite *composite = new Composite;\n    composite->input = sharp::CreateInputDescriptor(compositeObject.Get(\"input\").As<Napi::Object>());\n    composite->mode = sharp::AttrAsEnum<VipsBlendMode>(compositeObject, \"blend\", VIPS_TYPE_BLEND_MODE);\n    composite->gravity = sharp::AttrAsUint32(compositeObject, \"gravity\");\n    composite->left = sharp::AttrAsInt32(compositeObject, \"left\");\n    composite->top = sharp::AttrAsInt32(compositeObject, \"top\");\n    composite->hasOffset = sharp::AttrAsBool(compositeObject, \"hasOffset\");\n    composite->tile = sharp::AttrAsBool(compositeObject, \"tile\");\n    composite->premultiplied = sharp::AttrAsBool(compositeObject, \"premultiplied\");\n    baton->composite.push_back(composite);\n  }\n  // Resize options\n  baton->withoutEnlargement = sharp::AttrAsBool(options, \"withoutEnlargement\");\n  baton->withoutReduction = sharp::AttrAsBool(options, \"withoutReduction\");\n  baton->position = sharp::AttrAsInt32(options, \"position\");\n  baton->resizeBackground = sharp::AttrAsVectorOfDouble(options, \"resizeBackground\");\n  baton->kernel = sharp::AttrAsEnum<VipsKernel>(options, \"kernel\", VIPS_TYPE_KERNEL);\n  baton->fastShrinkOnLoad = sharp::AttrAsBool(options, \"fastShrinkOnLoad\");\n  // Join Channel Options\n  if (options.Has(\"joinChannelIn\")) {\n    Napi::Array joinChannelArray = options.Get(\"joinChannelIn\").As<Napi::Array>();\n    for (unsigned int i = 0; i < joinChannelArray.Length(); i++) {\n      baton->joinChannelIn.push_back(\n        sharp::CreateInputDescriptor(joinChannelArray.Get(i).As<Napi::Object>()));\n    }\n  }\n  // Operators\n  baton->flatten = sharp::AttrAsBool(options, \"flatten\");\n  baton->flattenBackground = sharp::AttrAsVectorOfDouble(options, \"flattenBackground\");\n  baton->unflatten = sharp::AttrAsBool(options, \"unflatten\");\n  baton->negate = sharp::AttrAsBool(options, \"negate\");\n  baton->negateAlpha = sharp::AttrAsBool(options, \"negateAlpha\");\n  baton->blurSigma = sharp::AttrAsDouble(options, \"blurSigma\");\n  baton->precision = sharp::AttrAsEnum<VipsPrecision>(options, \"precision\", VIPS_TYPE_PRECISION);\n  baton->minAmpl = sharp::AttrAsDouble(options, \"minAmpl\");\n  baton->brightness = sharp::AttrAsDouble(options, \"brightness\");\n  baton->saturation = sharp::AttrAsDouble(options, \"saturation\");\n  baton->hue = sharp::AttrAsInt32(options, \"hue\");\n  baton->lightness = sharp::AttrAsDouble(options, \"lightness\");\n  baton->medianSize = sharp::AttrAsUint32(options, \"medianSize\");\n  baton->sharpenSigma = sharp::AttrAsDouble(options, \"sharpenSigma\");\n  baton->sharpenM1 = sharp::AttrAsDouble(options, \"sharpenM1\");\n  baton->sharpenM2 = sharp::AttrAsDouble(options, \"sharpenM2\");\n  baton->sharpenX1 = sharp::AttrAsDouble(options, \"sharpenX1\");\n  baton->sharpenY2 = sharp::AttrAsDouble(options, \"sharpenY2\");\n  baton->sharpenY3 = sharp::AttrAsDouble(options, \"sharpenY3\");\n  baton->threshold = sharp::AttrAsInt32(options, \"threshold\");\n  baton->thresholdGrayscale = sharp::AttrAsBool(options, \"thresholdGrayscale\");\n  baton->trimBackground = sharp::AttrAsVectorOfDouble(options, \"trimBackground\");\n  baton->trimThreshold = sharp::AttrAsDouble(options, \"trimThreshold\");\n  baton->trimLineArt = sharp::AttrAsBool(options, \"trimLineArt\");\n  baton->gamma = sharp::AttrAsDouble(options, \"gamma\");\n  baton->gammaOut = sharp::AttrAsDouble(options, \"gammaOut\");\n  baton->linearA = sharp::AttrAsVectorOfDouble(options, \"linearA\");\n  baton->linearB = sharp::AttrAsVectorOfDouble(options, \"linearB\");\n  baton->dilateWidth = sharp::AttrAsUint32(options, \"dilateWidth\");\n  baton->erodeWidth = sharp::AttrAsUint32(options, \"erodeWidth\");\n  baton->greyscale = sharp::AttrAsBool(options, \"greyscale\");\n  baton->normalise = sharp::AttrAsBool(options, \"normalise\");\n  baton->normaliseLower = sharp::AttrAsUint32(options, \"normaliseLower\");\n  baton->normaliseUpper = sharp::AttrAsUint32(options, \"normaliseUpper\");\n  baton->tint = sharp::AttrAsVectorOfDouble(options, \"tint\");\n  baton->claheWidth = sharp::AttrAsUint32(options, \"claheWidth\");\n  baton->claheHeight = sharp::AttrAsUint32(options, \"claheHeight\");\n  baton->claheMaxSlope = sharp::AttrAsUint32(options, \"claheMaxSlope\");\n  baton->angle = sharp::AttrAsInt32(options, \"angle\");\n  baton->rotationAngle = sharp::AttrAsDouble(options, \"rotationAngle\");\n  baton->rotationBackground = sharp::AttrAsVectorOfDouble(options, \"rotationBackground\");\n  baton->rotateBefore = sharp::AttrAsBool(options, \"rotateBefore\");\n  baton->orientBefore = sharp::AttrAsBool(options, \"orientBefore\");\n  baton->flip = sharp::AttrAsBool(options, \"flip\");\n  baton->flop = sharp::AttrAsBool(options, \"flop\");\n  baton->extendTop = sharp::AttrAsInt32(options, \"extendTop\");\n  baton->extendBottom = sharp::AttrAsInt32(options, \"extendBottom\");\n  baton->extendLeft = sharp::AttrAsInt32(options, \"extendLeft\");\n  baton->extendRight = sharp::AttrAsInt32(options, \"extendRight\");\n  baton->extendBackground = sharp::AttrAsVectorOfDouble(options, \"extendBackground\");\n  baton->extendWith = sharp::AttrAsEnum<VipsExtend>(options, \"extendWith\", VIPS_TYPE_EXTEND);\n  baton->extractChannel = sharp::AttrAsInt32(options, \"extractChannel\");\n  baton->affineMatrix = sharp::AttrAsVectorOfDouble(options, \"affineMatrix\");\n  baton->affineBackground = sharp::AttrAsVectorOfDouble(options, \"affineBackground\");\n  baton->affineIdx = sharp::AttrAsDouble(options, \"affineIdx\");\n  baton->affineIdy = sharp::AttrAsDouble(options, \"affineIdy\");\n  baton->affineOdx = sharp::AttrAsDouble(options, \"affineOdx\");\n  baton->affineOdy = sharp::AttrAsDouble(options, \"affineOdy\");\n  baton->affineInterpolator = sharp::AttrAsStr(options, \"affineInterpolator\");\n  baton->removeAlpha = sharp::AttrAsBool(options, \"removeAlpha\");\n  baton->ensureAlpha = sharp::AttrAsDouble(options, \"ensureAlpha\");\n  if (options.Has(\"boolean\")) {\n    baton->boolean = sharp::CreateInputDescriptor(options.Get(\"boolean\").As<Napi::Object>());\n    baton->booleanOp = sharp::AttrAsEnum<VipsOperationBoolean>(options, \"booleanOp\", VIPS_TYPE_OPERATION_BOOLEAN);\n  }\n  if (options.Has(\"bandBoolOp\")) {\n    baton->bandBoolOp = sharp::AttrAsEnum<VipsOperationBoolean>(options, \"bandBoolOp\", VIPS_TYPE_OPERATION_BOOLEAN);\n  }\n  if (options.Has(\"convKernel\")) {\n    Napi::Object kernel = options.Get(\"convKernel\").As<Napi::Object>();\n    baton->convKernelWidth = sharp::AttrAsUint32(kernel, \"width\");\n    baton->convKernelHeight = sharp::AttrAsUint32(kernel, \"height\");\n    baton->convKernelScale = sharp::AttrAsDouble(kernel, \"scale\");\n    baton->convKernelOffset = sharp::AttrAsDouble(kernel, \"offset\");\n    size_t const kernelSize = static_cast<size_t>(baton->convKernelWidth * baton->convKernelHeight);\n    baton->convKernel.resize(kernelSize);\n    Napi::Array kdata = kernel.Get(\"kernel\").As<Napi::Array>();\n    for (unsigned int i = 0; i < kernelSize; i++) {\n      baton->convKernel[i] = sharp::AttrAsDouble(kdata, i);\n    }\n  }\n  if (options.Has(\"recombMatrix\")) {\n    Napi::Array recombMatrix = options.Get(\"recombMatrix\").As<Napi::Array>();\n    unsigned int matrixElements = recombMatrix.Length();\n    baton->recombMatrix.resize(matrixElements);\n    for (unsigned int i = 0; i < matrixElements; i++) {\n      baton->recombMatrix[i] = sharp::AttrAsDouble(recombMatrix, i);\n    }\n  }\n  baton->colourspacePipeline = sharp::AttrAsEnum<VipsInterpretation>(\n    options, \"colourspacePipeline\", VIPS_TYPE_INTERPRETATION);\n  if (baton->colourspacePipeline == VIPS_INTERPRETATION_ERROR) {\n    baton->colourspacePipeline = VIPS_INTERPRETATION_LAST;\n  }\n  baton->colourspace = sharp::AttrAsEnum<VipsInterpretation>(options, \"colourspace\", VIPS_TYPE_INTERPRETATION);\n  if (baton->colourspace == VIPS_INTERPRETATION_ERROR) {\n    baton->colourspace = VIPS_INTERPRETATION_sRGB;\n  }\n  // Output\n  baton->formatOut = sharp::AttrAsStr(options, \"formatOut\");\n  baton->fileOut = sharp::AttrAsStr(options, \"fileOut\");\n  baton->keepMetadata = sharp::AttrAsUint32(options, \"keepMetadata\");\n  baton->withMetadataOrientation = sharp::AttrAsUint32(options, \"withMetadataOrientation\");\n  baton->withMetadataDensity = sharp::AttrAsDouble(options, \"withMetadataDensity\");\n  baton->withIccProfile = sharp::AttrAsStr(options, \"withIccProfile\");\n  Napi::Object withExif = options.Get(\"withExif\").As<Napi::Object>();\n  Napi::Array withExifKeys = withExif.GetPropertyNames();\n  for (unsigned int i = 0; i < withExifKeys.Length(); i++) {\n    std::string k = sharp::AttrAsStr(withExifKeys, i);\n    if (withExif.HasOwnProperty(k)) {\n      baton->withExif.insert(std::make_pair(k, sharp::AttrAsStr(withExif, k)));\n    }\n  }\n  baton->withExifMerge = sharp::AttrAsBool(options, \"withExifMerge\");\n  baton->withXmp = sharp::AttrAsStr(options, \"withXmp\");\n  baton->timeoutSeconds = sharp::AttrAsUint32(options, \"timeoutSeconds\");\n  baton->loop = sharp::AttrAsUint32(options, \"loop\");\n  baton->delay = sharp::AttrAsInt32Vector(options, \"delay\");\n  // Format-specific\n  baton->jpegQuality = sharp::AttrAsUint32(options, \"jpegQuality\");\n  baton->jpegProgressive = sharp::AttrAsBool(options, \"jpegProgressive\");\n  baton->jpegChromaSubsampling = sharp::AttrAsStr(options, \"jpegChromaSubsampling\");\n  baton->jpegTrellisQuantisation = sharp::AttrAsBool(options, \"jpegTrellisQuantisation\");\n  baton->jpegQuantisationTable = sharp::AttrAsUint32(options, \"jpegQuantisationTable\");\n  baton->jpegOvershootDeringing = sharp::AttrAsBool(options, \"jpegOvershootDeringing\");\n  baton->jpegOptimiseScans = sharp::AttrAsBool(options, \"jpegOptimiseScans\");\n  baton->jpegOptimiseCoding = sharp::AttrAsBool(options, \"jpegOptimiseCoding\");\n  baton->pngProgressive = sharp::AttrAsBool(options, \"pngProgressive\");\n  baton->pngCompressionLevel = sharp::AttrAsUint32(options, \"pngCompressionLevel\");\n  baton->pngAdaptiveFiltering = sharp::AttrAsBool(options, \"pngAdaptiveFiltering\");\n  baton->pngPalette = sharp::AttrAsBool(options, \"pngPalette\");\n  baton->pngQuality = sharp::AttrAsUint32(options, \"pngQuality\");\n  baton->pngEffort = sharp::AttrAsUint32(options, \"pngEffort\");\n  baton->pngBitdepth = sharp::AttrAsUint32(options, \"pngBitdepth\");\n  baton->pngDither = sharp::AttrAsDouble(options, \"pngDither\");\n  baton->jp2Quality = sharp::AttrAsUint32(options, \"jp2Quality\");\n  baton->jp2Lossless = sharp::AttrAsBool(options, \"jp2Lossless\");\n  baton->jp2TileHeight = sharp::AttrAsUint32(options, \"jp2TileHeight\");\n  baton->jp2TileWidth = sharp::AttrAsUint32(options, \"jp2TileWidth\");\n  baton->jp2ChromaSubsampling = sharp::AttrAsStr(options, \"jp2ChromaSubsampling\");\n  baton->webpQuality = sharp::AttrAsUint32(options, \"webpQuality\");\n  baton->webpAlphaQuality = sharp::AttrAsUint32(options, \"webpAlphaQuality\");\n  baton->webpLossless = sharp::AttrAsBool(options, \"webpLossless\");\n  baton->webpNearLossless = sharp::AttrAsBool(options, \"webpNearLossless\");\n  baton->webpSmartSubsample = sharp::AttrAsBool(options, \"webpSmartSubsample\");\n  baton->webpSmartDeblock = sharp::AttrAsBool(options, \"webpSmartDeblock\");\n  baton->webpPreset = sharp::AttrAsEnum<VipsForeignWebpPreset>(options, \"webpPreset\", VIPS_TYPE_FOREIGN_WEBP_PRESET);\n  baton->webpEffort = sharp::AttrAsUint32(options, \"webpEffort\");\n  baton->webpMinSize = sharp::AttrAsBool(options, \"webpMinSize\");\n  baton->webpMixed = sharp::AttrAsBool(options, \"webpMixed\");\n  baton->gifBitdepth = sharp::AttrAsUint32(options, \"gifBitdepth\");\n  baton->gifEffort = sharp::AttrAsUint32(options, \"gifEffort\");\n  baton->gifDither = sharp::AttrAsDouble(options, \"gifDither\");\n  baton->gifInterFrameMaxError = sharp::AttrAsDouble(options, \"gifInterFrameMaxError\");\n  baton->gifInterPaletteMaxError = sharp::AttrAsDouble(options, \"gifInterPaletteMaxError\");\n  baton->gifKeepDuplicateFrames = sharp::AttrAsBool(options, \"gifKeepDuplicateFrames\");\n  baton->gifReuse = sharp::AttrAsBool(options, \"gifReuse\");\n  baton->gifProgressive = sharp::AttrAsBool(options, \"gifProgressive\");\n  baton->tiffQuality = sharp::AttrAsUint32(options, \"tiffQuality\");\n  baton->tiffBigtiff = sharp::AttrAsBool(options, \"tiffBigtiff\");\n  baton->tiffPyramid = sharp::AttrAsBool(options, \"tiffPyramid\");\n  baton->tiffMiniswhite = sharp::AttrAsBool(options, \"tiffMiniswhite\");\n  baton->tiffBitdepth = sharp::AttrAsUint32(options, \"tiffBitdepth\");\n  baton->tiffTile = sharp::AttrAsBool(options, \"tiffTile\");\n  baton->tiffTileWidth = sharp::AttrAsUint32(options, \"tiffTileWidth\");\n  baton->tiffTileHeight = sharp::AttrAsUint32(options, \"tiffTileHeight\");\n  baton->tiffXres = sharp::AttrAsDouble(options, \"tiffXres\");\n  baton->tiffYres = sharp::AttrAsDouble(options, \"tiffYres\");\n  if (baton->tiffXres == 1.0 && baton->tiffYres == 1.0 && baton->withMetadataDensity > 0) {\n    baton->tiffXres = baton->tiffYres = baton->withMetadataDensity / 25.4;\n  }\n  baton->tiffCompression = sharp::AttrAsEnum<VipsForeignTiffCompression>(\n    options, \"tiffCompression\", VIPS_TYPE_FOREIGN_TIFF_COMPRESSION);\n  baton->tiffPredictor = sharp::AttrAsEnum<VipsForeignTiffPredictor>(\n    options, \"tiffPredictor\", VIPS_TYPE_FOREIGN_TIFF_PREDICTOR);\n  baton->tiffResolutionUnit = sharp::AttrAsEnum<VipsForeignTiffResunit>(\n    options, \"tiffResolutionUnit\", VIPS_TYPE_FOREIGN_TIFF_RESUNIT);\n  baton->heifQuality = sharp::AttrAsUint32(options, \"heifQuality\");\n  baton->heifLossless = sharp::AttrAsBool(options, \"heifLossless\");\n  baton->heifCompression = sharp::AttrAsEnum<VipsForeignHeifCompression>(\n    options, \"heifCompression\", VIPS_TYPE_FOREIGN_HEIF_COMPRESSION);\n  baton->heifEffort = sharp::AttrAsUint32(options, \"heifEffort\");\n  baton->heifChromaSubsampling = sharp::AttrAsStr(options, \"heifChromaSubsampling\");\n  baton->heifBitdepth = sharp::AttrAsUint32(options, \"heifBitdepth\");\n  baton->jxlDistance = sharp::AttrAsDouble(options, \"jxlDistance\");\n  baton->jxlDecodingTier = sharp::AttrAsUint32(options, \"jxlDecodingTier\");\n  baton->jxlEffort = sharp::AttrAsUint32(options, \"jxlEffort\");\n  baton->jxlLossless = sharp::AttrAsBool(options, \"jxlLossless\");\n  baton->rawDepth = sharp::AttrAsEnum<VipsBandFormat>(options, \"rawDepth\", VIPS_TYPE_BAND_FORMAT);\n  baton->tileSize = sharp::AttrAsUint32(options, \"tileSize\");\n  baton->tileOverlap = sharp::AttrAsUint32(options, \"tileOverlap\");\n  baton->tileAngle = sharp::AttrAsInt32(options, \"tileAngle\");\n  baton->tileBackground = sharp::AttrAsVectorOfDouble(options, \"tileBackground\");\n  baton->tileSkipBlanks = sharp::AttrAsInt32(options, \"tileSkipBlanks\");\n  baton->tileContainer = sharp::AttrAsEnum<VipsForeignDzContainer>(\n    options, \"tileContainer\", VIPS_TYPE_FOREIGN_DZ_CONTAINER);\n  baton->tileLayout = sharp::AttrAsEnum<VipsForeignDzLayout>(options, \"tileLayout\", VIPS_TYPE_FOREIGN_DZ_LAYOUT);\n  baton->tileFormat = sharp::AttrAsStr(options, \"tileFormat\");\n  baton->tileDepth = sharp::AttrAsEnum<VipsForeignDzDepth>(options, \"tileDepth\", VIPS_TYPE_FOREIGN_DZ_DEPTH);\n  baton->tileCentre = sharp::AttrAsBool(options, \"tileCentre\");\n  baton->tileId = sharp::AttrAsStr(options, \"tileId\");\n  baton->tileBasename = sharp::AttrAsStr(options, \"tileBasename\");\n\n  // Function to notify of libvips warnings\n  Napi::Function debuglog = options.Get(\"debuglog\").As<Napi::Function>();\n\n  // Function to notify of queue length changes\n  Napi::Function queueListener = options.Get(\"queueListener\").As<Napi::Function>();\n\n  // Join queue for worker thread\n  Napi::Function callback = info[size_t(1)].As<Napi::Function>();\n  PipelineWorker *worker = new PipelineWorker(callback, baton, debuglog, queueListener);\n  worker->Receiver().Set(\"options\", options);\n  worker->Queue();\n\n  // Increment queued task counter\n  Napi::Number queueLength = Napi::Number::New(info.Env(), static_cast<int>(++sharp::counterQueue));\n  queueListener.Call(info.This(), { queueLength });\n\n  return info.Env().Undefined();\n}\n"
  },
  {
    "path": "src/pipeline.h",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#ifndef SRC_PIPELINE_H_\n#define SRC_PIPELINE_H_\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include <napi.h>\n#include <vips/vips8>\n\n#include \"./common.h\"\n\nNapi::Value pipeline(const Napi::CallbackInfo& info);\n\nstruct Composite {\n  sharp::InputDescriptor *input;\n  VipsBlendMode mode;\n  int gravity;\n  int left;\n  int top;\n  bool hasOffset;\n  bool tile;\n  bool premultiplied;\n\n  Composite():\n    input(nullptr),\n    mode(VIPS_BLEND_MODE_OVER),\n    gravity(0),\n    left(0),\n    top(0),\n    hasOffset(false),\n    tile(false),\n    premultiplied(false) {}\n};\n\nstruct PipelineBaton {\n  sharp::InputDescriptor *input;\n  std::vector<sharp::InputDescriptor *> join;\n  std::string formatOut;\n  std::string fileOut;\n  void *bufferOut;\n  size_t bufferOutLength;\n  int pageHeightOut;\n  int pagesOut;\n  std::vector<Composite *> composite;\n  std::vector<sharp::InputDescriptor *> joinChannelIn;\n  int topOffsetPre;\n  int leftOffsetPre;\n  int widthPre;\n  int heightPre;\n  int topOffsetPost;\n  int leftOffsetPost;\n  int widthPost;\n  int heightPost;\n  int width;\n  int height;\n  int channels;\n  VipsKernel kernel;\n  sharp::Canvas canvas;\n  int position;\n  std::vector<double> resizeBackground;\n  bool hasCropOffset;\n  int cropOffsetLeft;\n  int cropOffsetTop;\n  bool hasAttentionCenter;\n  int attentionX;\n  int attentionY;\n  bool premultiplied;\n  bool tileCentre;\n  bool fastShrinkOnLoad;\n  std::vector<double> tint;\n  bool flatten;\n  std::vector<double> flattenBackground;\n  bool unflatten;\n  bool negate;\n  bool negateAlpha;\n  double blurSigma;\n  VipsPrecision precision;\n  double minAmpl;\n  double brightness;\n  double saturation;\n  int hue;\n  double lightness;\n  int medianSize;\n  double sharpenSigma;\n  double sharpenM1;\n  double sharpenM2;\n  double sharpenX1;\n  double sharpenY2;\n  double sharpenY3;\n  int threshold;\n  bool thresholdGrayscale;\n  std::vector<double> trimBackground;\n  double trimThreshold;\n  bool trimLineArt;\n  int trimOffsetLeft;\n  int trimOffsetTop;\n  std::vector<double> linearA;\n  std::vector<double> linearB;\n  int dilateWidth;\n  int erodeWidth;\n  double gamma;\n  double gammaOut;\n  bool greyscale;\n  bool normalise;\n  int normaliseLower;\n  int normaliseUpper;\n  int claheWidth;\n  int claheHeight;\n  int claheMaxSlope;\n  int angle;\n  double rotationAngle;\n  std::vector<double> rotationBackground;\n  bool rotateBefore;\n  bool orientBefore;\n  bool flip;\n  bool flop;\n  int extendTop;\n  int extendBottom;\n  int extendLeft;\n  int extendRight;\n  std::vector<double> extendBackground;\n  VipsExtend extendWith;\n  bool withoutEnlargement;\n  bool withoutReduction;\n  std::vector<double> affineMatrix;\n  std::vector<double> affineBackground;\n  double affineIdx;\n  double affineIdy;\n  double affineOdx;\n  double affineOdy;\n  std::string affineInterpolator;\n  int jpegQuality;\n  bool jpegProgressive;\n  std::string jpegChromaSubsampling;\n  bool jpegTrellisQuantisation;\n  int jpegQuantisationTable;\n  bool jpegOvershootDeringing;\n  bool jpegOptimiseScans;\n  bool jpegOptimiseCoding;\n  bool pngProgressive;\n  int pngCompressionLevel;\n  bool pngAdaptiveFiltering;\n  bool pngPalette;\n  int pngQuality;\n  int pngEffort;\n  int pngBitdepth;\n  double pngDither;\n  int jp2Quality;\n  bool jp2Lossless;\n  int jp2TileHeight;\n  int jp2TileWidth;\n  std::string jp2ChromaSubsampling;\n  int webpQuality;\n  int webpAlphaQuality;\n  bool webpNearLossless;\n  bool webpLossless;\n  bool webpSmartSubsample;\n  bool webpSmartDeblock;\n  VipsForeignWebpPreset webpPreset;\n  int webpEffort;\n  bool webpMinSize;\n  bool webpMixed;\n  int gifBitdepth;\n  int gifEffort;\n  double gifDither;\n  double gifInterFrameMaxError;\n  double gifInterPaletteMaxError;\n  bool gifKeepDuplicateFrames;\n  bool gifReuse;\n  bool gifProgressive;\n  int tiffQuality;\n  VipsForeignTiffCompression tiffCompression;\n  bool tiffBigtiff;\n  VipsForeignTiffPredictor tiffPredictor;\n  bool tiffPyramid;\n  int tiffBitdepth;\n  bool tiffMiniswhite;\n  bool tiffTile;\n  int tiffTileHeight;\n  int tiffTileWidth;\n  double tiffXres;\n  double tiffYres;\n  VipsForeignTiffResunit tiffResolutionUnit;\n  int heifQuality;\n  VipsForeignHeifCompression heifCompression;\n  int heifEffort;\n  std::string heifChromaSubsampling;\n  bool heifLossless;\n  int heifBitdepth;\n  double jxlDistance;\n  int jxlDecodingTier;\n  int jxlEffort;\n  bool jxlLossless;\n  VipsBandFormat rawDepth;\n  std::string err;\n  bool errUseWarning;\n  int keepMetadata;\n  int withMetadataOrientation;\n  double withMetadataDensity;\n  std::string withIccProfile;\n  std::unordered_map<std::string, std::string> withExif;\n  bool withExifMerge;\n  std::string withXmp;\n  int timeoutSeconds;\n  std::vector<double> convKernel;\n  int convKernelWidth;\n  int convKernelHeight;\n  double convKernelScale;\n  double convKernelOffset;\n  sharp::InputDescriptor *boolean;\n  VipsOperationBoolean booleanOp;\n  VipsOperationBoolean bandBoolOp;\n  int extractChannel;\n  bool removeAlpha;\n  double ensureAlpha;\n  VipsInterpretation colourspacePipeline;\n  VipsInterpretation colourspace;\n  std::vector<int> delay;\n  int loop;\n  int tileSize;\n  int tileOverlap;\n  VipsForeignDzContainer tileContainer;\n  VipsForeignDzLayout tileLayout;\n  std::string tileFormat;\n  int tileAngle;\n  std::vector<double> tileBackground;\n  int tileSkipBlanks;\n  VipsForeignDzDepth tileDepth;\n  std::string tileId;\n  std::string tileBasename;\n  std::vector<double> recombMatrix;\n\n  PipelineBaton():\n    input(nullptr),\n    bufferOutLength(0),\n    pageHeightOut(0),\n    pagesOut(0),\n    topOffsetPre(-1),\n    topOffsetPost(-1),\n    channels(0),\n    kernel(VIPS_KERNEL_LANCZOS3),\n    canvas(sharp::Canvas::CROP),\n    position(0),\n    resizeBackground{ 0.0, 0.0, 0.0, 255.0 },\n    hasCropOffset(false),\n    cropOffsetLeft(0),\n    cropOffsetTop(0),\n    hasAttentionCenter(false),\n    attentionX(0),\n    attentionY(0),\n    premultiplied(false),\n    tint{ -1.0, 0.0, 0.0, 0.0 },\n    flatten(false),\n    flattenBackground{ 0.0, 0.0, 0.0 },\n    unflatten(false),\n    negate(false),\n    negateAlpha(true),\n    blurSigma(0.0),\n    brightness(1.0),\n    saturation(1.0),\n    hue(0),\n    lightness(0),\n    medianSize(0),\n    sharpenSigma(0.0),\n    sharpenM1(1.0),\n    sharpenM2(2.0),\n    sharpenX1(2.0),\n    sharpenY2(10.0),\n    sharpenY3(20.0),\n    threshold(0),\n    thresholdGrayscale(true),\n    trimBackground{},\n    trimThreshold(-1.0),\n    trimLineArt(false),\n    trimOffsetLeft(0),\n    trimOffsetTop(0),\n    linearA{},\n    linearB{},\n    dilateWidth(0),\n    erodeWidth(0),\n    gamma(0.0),\n    greyscale(false),\n    normalise(false),\n    normaliseLower(1),\n    normaliseUpper(99),\n    claheWidth(0),\n    claheHeight(0),\n    claheMaxSlope(3),\n    angle(0),\n    rotationAngle(0.0),\n    rotationBackground{ 0.0, 0.0, 0.0, 255.0 },\n    flip(false),\n    flop(false),\n    extendTop(0),\n    extendBottom(0),\n    extendLeft(0),\n    extendRight(0),\n    extendBackground{ 0.0, 0.0, 0.0, 255.0 },\n    extendWith(VIPS_EXTEND_BACKGROUND),\n    withoutEnlargement(false),\n    withoutReduction(false),\n    affineMatrix{ 1.0, 0.0, 0.0, 1.0 },\n    affineBackground{ 0.0, 0.0, 0.0, 255.0 },\n    affineIdx(0),\n    affineIdy(0),\n    affineOdx(0),\n    affineOdy(0),\n    affineInterpolator(\"bicubic\"),\n    jpegQuality(80),\n    jpegProgressive(false),\n    jpegChromaSubsampling(\"4:2:0\"),\n    jpegTrellisQuantisation(false),\n    jpegQuantisationTable(0),\n    jpegOvershootDeringing(false),\n    jpegOptimiseScans(false),\n    jpegOptimiseCoding(true),\n    pngProgressive(false),\n    pngCompressionLevel(6),\n    pngAdaptiveFiltering(false),\n    pngPalette(false),\n    pngQuality(100),\n    pngEffort(7),\n    pngBitdepth(8),\n    pngDither(1.0),\n    jp2Quality(80),\n    jp2Lossless(false),\n    jp2TileHeight(512),\n    jp2TileWidth(512),\n    jp2ChromaSubsampling(\"4:4:4\"),\n    webpQuality(80),\n    webpAlphaQuality(100),\n    webpNearLossless(false),\n    webpLossless(false),\n    webpSmartSubsample(false),\n    webpSmartDeblock(false),\n    webpPreset(VIPS_FOREIGN_WEBP_PRESET_DEFAULT),\n    webpEffort(4),\n    webpMinSize(false),\n    webpMixed(false),\n    gifBitdepth(8),\n    gifEffort(7),\n    gifDither(1.0),\n    gifInterFrameMaxError(0.0),\n    gifInterPaletteMaxError(3.0),\n    gifKeepDuplicateFrames(false),\n    gifReuse(true),\n    gifProgressive(false),\n    tiffQuality(80),\n    tiffCompression(VIPS_FOREIGN_TIFF_COMPRESSION_JPEG),\n    tiffBigtiff(false),\n    tiffPredictor(VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL),\n    tiffPyramid(false),\n    tiffBitdepth(8),\n    tiffMiniswhite(false),\n    tiffTile(false),\n    tiffTileHeight(256),\n    tiffTileWidth(256),\n    tiffXres(1.0),\n    tiffYres(1.0),\n    tiffResolutionUnit(VIPS_FOREIGN_TIFF_RESUNIT_INCH),\n    heifQuality(50),\n    heifCompression(VIPS_FOREIGN_HEIF_COMPRESSION_AV1),\n    heifEffort(4),\n    heifChromaSubsampling(\"4:4:4\"),\n    heifLossless(false),\n    heifBitdepth(8),\n    jxlDistance(1.0),\n    jxlDecodingTier(0),\n    jxlEffort(7),\n    jxlLossless(false),\n    rawDepth(VIPS_FORMAT_UCHAR),\n    errUseWarning(false),\n    keepMetadata(0),\n    withMetadataOrientation(-1),\n    withMetadataDensity(0.0),\n    withExifMerge(true),\n    timeoutSeconds(0),\n    convKernelWidth(0),\n    convKernelHeight(0),\n    convKernelScale(0.0),\n    convKernelOffset(0.0),\n    boolean(nullptr),\n    booleanOp(VIPS_OPERATION_BOOLEAN_LAST),\n    bandBoolOp(VIPS_OPERATION_BOOLEAN_LAST),\n    extractChannel(-1),\n    removeAlpha(false),\n    ensureAlpha(-1.0),\n    colourspacePipeline(VIPS_INTERPRETATION_LAST),\n    colourspace(VIPS_INTERPRETATION_LAST),\n    loop(-1),\n    tileSize(256),\n    tileOverlap(0),\n    tileContainer(VIPS_FOREIGN_DZ_CONTAINER_FS),\n    tileLayout(VIPS_FOREIGN_DZ_LAYOUT_DZ),\n    tileAngle(0),\n    tileBackground{ 255.0, 255.0, 255.0, 255.0 },\n    tileSkipBlanks(-1),\n    tileDepth(VIPS_FOREIGN_DZ_DEPTH_LAST) {}\n};\n\n#endif  // SRC_PIPELINE_H_\n"
  },
  {
    "path": "src/sharp.cc",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#include <mutex>\n\n#include <napi.h>\n#include <vips/vips8>\n\n#include \"./common.h\"\n#include \"./metadata.h\"\n#include \"./pipeline.h\"\n#include \"./stats.h\"\n#include \"./utilities.h\"\n\nNapi::Object init(Napi::Env env, Napi::Object exports) {\n  static std::once_flag sharp_vips_init_once;\n  std::call_once(sharp_vips_init_once, []() {\n    vips_init(\"sharp\");\n  });\n\n  g_log_set_handler(\"VIPS\", static_cast<GLogLevelFlags>(G_LOG_LEVEL_WARNING),\n    static_cast<GLogFunc>(sharp::VipsWarningCallback), nullptr);\n\n  // Methods available to JavaScript\n  exports.Set(\"metadata\", Napi::Function::New(env, metadata));\n  exports.Set(\"pipeline\", Napi::Function::New(env, pipeline));\n  exports.Set(\"cache\", Napi::Function::New(env, cache));\n  exports.Set(\"concurrency\", Napi::Function::New(env, concurrency));\n  exports.Set(\"counters\", Napi::Function::New(env, counters));\n  exports.Set(\"simd\", Napi::Function::New(env, simd));\n  exports.Set(\"libvipsVersion\", Napi::Function::New(env, libvipsVersion));\n  exports.Set(\"format\", Napi::Function::New(env, format));\n  exports.Set(\"block\", Napi::Function::New(env, block));\n  exports.Set(\"_maxColourDistance\", Napi::Function::New(env, _maxColourDistance));\n  exports.Set(\"_isUsingJemalloc\", Napi::Function::New(env, _isUsingJemalloc));\n  exports.Set(\"_isUsingX64V2\", Napi::Function::New(env, _isUsingX64V2));\n  exports.Set(\"stats\", Napi::Function::New(env, stats));\n  return exports;\n}\n\nNODE_API_MODULE(sharp, init)\n"
  },
  {
    "path": "src/stats.cc",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\n#include <napi.h>\n#include <vips/vips8>\n\n#include \"./common.h\"\n#include \"./stats.h\"\n\nclass StatsWorker : public Napi::AsyncWorker {\n public:\n  StatsWorker(Napi::Function callback, StatsBaton *baton, Napi::Function debuglog) :\n    Napi::AsyncWorker(callback), baton(baton), debuglog(Napi::Persistent(debuglog)) {}\n  ~StatsWorker() {}\n\n  const int STAT_MIN_INDEX = 0;\n  const int STAT_MAX_INDEX = 1;\n  const int STAT_SUM_INDEX = 2;\n  const int STAT_SQ_SUM_INDEX = 3;\n  const int STAT_MEAN_INDEX = 4;\n  const int STAT_STDEV_INDEX = 5;\n  const int STAT_MINX_INDEX = 6;\n  const int STAT_MINY_INDEX = 7;\n  const int STAT_MAXX_INDEX = 8;\n  const int STAT_MAXY_INDEX = 9;\n\n  void Execute() {\n    // Decrement queued task counter\n    sharp::counterQueue--;\n\n    vips::VImage image;\n    sharp::ImageType imageType = sharp::ImageType::UNKNOWN;\n    try {\n      std::tie(image, imageType) = OpenInput(baton->input);\n    } catch (vips::VError const &err) {\n      (baton->err).append(err.what());\n    }\n    if (imageType != sharp::ImageType::UNKNOWN) {\n      try {\n        vips::VImage stats = image.stats();\n        int const bands = image.bands();\n        for (int b = 1; b <= bands; b++) {\n          ChannelStats cStats(\n            static_cast<int>(stats.getpoint(STAT_MIN_INDEX, b).front()),\n            static_cast<int>(stats.getpoint(STAT_MAX_INDEX, b).front()),\n            stats.getpoint(STAT_SUM_INDEX, b).front(),\n            stats.getpoint(STAT_SQ_SUM_INDEX, b).front(),\n            stats.getpoint(STAT_MEAN_INDEX, b).front(),\n            stats.getpoint(STAT_STDEV_INDEX, b).front(),\n            static_cast<int>(stats.getpoint(STAT_MINX_INDEX, b).front()),\n            static_cast<int>(stats.getpoint(STAT_MINY_INDEX, b).front()),\n            static_cast<int>(stats.getpoint(STAT_MAXX_INDEX, b).front()),\n            static_cast<int>(stats.getpoint(STAT_MAXY_INDEX, b).front()));\n          baton->channelStats.push_back(cStats);\n        }\n        // Image is not opaque when alpha layer is present and contains a non-mamixa value\n        if (image.has_alpha()) {\n          double const minAlpha = static_cast<double>(stats.getpoint(STAT_MIN_INDEX, bands).front());\n          if (minAlpha != vips_interpretation_max_alpha(image.interpretation())) {\n            baton->isOpaque = false;\n          }\n        }\n        // Convert to greyscale\n        vips::VImage greyscale = image.colourspace(VIPS_INTERPRETATION_B_W)[0];\n        // Estimate entropy via histogram of greyscale value frequency\n        baton->entropy = std::abs(greyscale.hist_find().hist_entropy());\n        // Estimate sharpness via standard deviation of greyscale laplacian\n        if (image.width() > 1 || image.height() > 1) {\n          VImage laplacian = VImage::new_matrixv(3, 3,\n            0.0,  1.0, 0.0,\n            1.0, -4.0, 1.0,\n            0.0,  1.0, 0.0);\n          laplacian.set(\"scale\", 9.0);\n          baton->sharpness = greyscale.conv(laplacian).deviate();\n        }\n        // Most dominant sRGB colour via 4096-bin 3D histogram\n        vips::VImage hist = sharp::RemoveAlpha(image)\n          .colourspace(VIPS_INTERPRETATION_sRGB)\n          .hist_find_ndim(VImage::option()->set(\"bins\", 16));\n        std::complex<double> maxpos = hist.maxpos();\n        int const dx = static_cast<int>(std::real(maxpos));\n        int const dy = static_cast<int>(std::imag(maxpos));\n        std::vector<double> pel = hist(dx, dy);\n        int const dz = std::distance(pel.begin(), std::find(pel.begin(), pel.end(), hist.max()));\n        baton->dominantRed = dx * 16 + 8;\n        baton->dominantGreen = dy * 16 + 8;\n        baton->dominantBlue = dz * 16 + 8;\n      } catch (vips::VError const &err) {\n        (baton->err).append(err.what());\n      }\n    }\n\n    // Clean up\n    vips_error_clear();\n    vips_thread_shutdown();\n  }\n\n  void OnOK() {\n    Napi::Env env = Env();\n    Napi::HandleScope scope(env);\n\n    // Handle warnings\n    std::string warning = sharp::VipsWarningPop();\n    while (!warning.empty()) {\n      debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) });\n      warning = sharp::VipsWarningPop();\n    }\n\n    if (baton->err.empty()) {\n      // Stats Object\n      Napi::Object info = Napi::Object::New(env);\n      Napi::Array channels = Napi::Array::New(env);\n\n      std::vector<ChannelStats>::iterator it;\n      int i = 0;\n      for (it = baton->channelStats.begin(); it < baton->channelStats.end(); it++, i++) {\n        Napi::Object channelStat = Napi::Object::New(env);\n        channelStat.Set(\"min\", it->min);\n        channelStat.Set(\"max\", it->max);\n        channelStat.Set(\"sum\", it->sum);\n        channelStat.Set(\"squaresSum\", it->squaresSum);\n        channelStat.Set(\"mean\", it->mean);\n        channelStat.Set(\"stdev\", it->stdev);\n        channelStat.Set(\"minX\", it->minX);\n        channelStat.Set(\"minY\", it->minY);\n        channelStat.Set(\"maxX\", it->maxX);\n        channelStat.Set(\"maxY\", it->maxY);\n        channels.Set(i, channelStat);\n      }\n\n      info.Set(\"channels\", channels);\n      info.Set(\"isOpaque\", baton->isOpaque);\n      info.Set(\"entropy\", baton->entropy);\n      info.Set(\"sharpness\", baton->sharpness);\n      Napi::Object dominant = Napi::Object::New(env);\n      dominant.Set(\"r\", baton->dominantRed);\n      dominant.Set(\"g\", baton->dominantGreen);\n      dominant.Set(\"b\", baton->dominantBlue);\n      info.Set(\"dominant\", dominant);\n      Callback().Call(Receiver().Value(), { env.Null(), info });\n    } else {\n      Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });\n    }\n\n    delete baton->input;\n    delete baton;\n  }\n\n private:\n  StatsBaton* baton;\n  Napi::FunctionReference debuglog;\n};\n\n/*\n  stats(options, callback)\n*/\nNapi::Value stats(const Napi::CallbackInfo& info) {\n  // V8 objects are converted to non-V8 types held in the baton struct\n  StatsBaton *baton = new StatsBaton;\n  Napi::Object options = info[size_t(0)].As<Napi::Object>();\n\n  // Input\n  baton->input = sharp::CreateInputDescriptor(options.Get(\"input\").As<Napi::Object>());\n  baton->input->access = VIPS_ACCESS_RANDOM;\n\n  // Function to notify of libvips warnings\n  Napi::Function debuglog = options.Get(\"debuglog\").As<Napi::Function>();\n\n  // Join queue for worker thread\n  Napi::Function callback = info[size_t(1)].As<Napi::Function>();\n  StatsWorker *worker = new StatsWorker(callback, baton, debuglog);\n  worker->Receiver().Set(\"options\", options);\n  worker->Queue();\n\n  // Increment queued task counter\n  sharp::counterQueue++;\n\n  return info.Env().Undefined();\n}\n"
  },
  {
    "path": "src/stats.h",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#ifndef SRC_STATS_H_\n#define SRC_STATS_H_\n\n#include <string>\n#include <vector>\n#include <napi.h>\n\n#include \"./common.h\"\n\nstruct ChannelStats {\n  // stats per channel\n  int min;\n  int max;\n  double sum;\n  double squaresSum;\n  double mean;\n  double stdev;\n  int minX;\n  int minY;\n  int maxX;\n  int maxY;\n\n  ChannelStats(int minVal, int maxVal, double sumVal, double squaresSumVal,\n    double meanVal, double stdevVal, int minXVal, int minYVal, int maxXVal, int maxYVal):\n    min(minVal), max(maxVal), sum(sumVal), squaresSum(squaresSumVal),  // NOLINT(build/include_what_you_use)\n    mean(meanVal), stdev(stdevVal), minX(minXVal), minY(minYVal), maxX(maxXVal), maxY(maxYVal) {}\n};\n\nstruct StatsBaton {\n  // Input\n  sharp::InputDescriptor *input;\n\n  // Output\n  std::vector<ChannelStats> channelStats;\n  bool isOpaque;\n  double entropy;\n  double sharpness;\n  int dominantRed;\n  int dominantGreen;\n  int dominantBlue;\n\n  std::string err;\n\n  StatsBaton():\n    input(nullptr),\n    isOpaque(true),\n    entropy(0.0),\n    sharpness(0.0),\n    dominantRed(0),\n    dominantGreen(0),\n    dominantBlue(0)\n    {}\n};\n\nNapi::Value stats(const Napi::CallbackInfo& info);\n\n#endif  // SRC_STATS_H_\n"
  },
  {
    "path": "src/utilities.cc",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#include <cmath>\n#include <cstdio>\n#include <string>\n\n#include <napi.h>\n#include <vips/vips8>\n#include <vips/vector.h>\n\n#include \"./common.h\"\n#include \"./operations.h\"\n#include \"./utilities.h\"\n\n/*\n  Get and set cache limits\n*/\nNapi::Value cache(const Napi::CallbackInfo& info) {\n  Napi::Env env = info.Env();\n\n  // Set memory limit\n  if (info[size_t(0)].IsNumber()) {\n    vips_cache_set_max_mem(info[size_t(0)].As<Napi::Number>().Int32Value() * 1048576);\n  }\n  // Set file limit\n  if (info[size_t(1)].IsNumber()) {\n    vips_cache_set_max_files(info[size_t(1)].As<Napi::Number>().Int32Value());\n  }\n  // Set items limit\n  if (info[size_t(2)].IsNumber()) {\n    vips_cache_set_max(info[size_t(2)].As<Napi::Number>().Int32Value());\n  }\n\n  // Get memory stats\n  Napi::Object memory = Napi::Object::New(env);\n  memory.Set(\"current\", round(vips_tracked_get_mem() / 1048576));\n  memory.Set(\"high\", round(vips_tracked_get_mem_highwater() / 1048576));\n  memory.Set(\"max\", round(vips_cache_get_max_mem() / 1048576));\n  // Get file stats\n  Napi::Object files = Napi::Object::New(env);\n  files.Set(\"current\", vips_tracked_get_files());\n  files.Set(\"max\", vips_cache_get_max_files());\n\n  // Get item stats\n  Napi::Object items = Napi::Object::New(env);\n  items.Set(\"current\", vips_cache_get_size());\n  items.Set(\"max\", vips_cache_get_max());\n\n  Napi::Object cache = Napi::Object::New(env);\n  cache.Set(\"memory\", memory);\n  cache.Set(\"files\", files);\n  cache.Set(\"items\", items);\n  return cache;\n}\n\n/*\n  Get and set size of thread pool\n*/\nNapi::Value concurrency(const Napi::CallbackInfo& info) {\n  // Set concurrency\n  if (info[size_t(0)].IsNumber()) {\n    vips_concurrency_set(info[size_t(0)].As<Napi::Number>().Int32Value());\n  }\n  // Get concurrency\n  return Napi::Number::New(info.Env(), vips_concurrency_get());\n}\n\n/*\n  Get internal counters (queued tasks, processing tasks)\n*/\nNapi::Value counters(const Napi::CallbackInfo& info) {\n  Napi::Object counters = Napi::Object::New(info.Env());\n  counters.Set(\"queue\", static_cast<int>(sharp::counterQueue));\n  counters.Set(\"process\", static_cast<int>(sharp::counterProcess));\n  return counters;\n}\n\n/*\n  Get and set use of SIMD vector unit instructions\n*/\nNapi::Value simd(const Napi::CallbackInfo& info) {\n  // Set state\n  if (info[size_t(0)].IsBoolean()) {\n    vips_vector_set_enabled(info[size_t(0)].As<Napi::Boolean>().Value());\n  }\n  // Get state\n  return Napi::Boolean::New(info.Env(), vips_vector_isenabled());\n}\n\n/*\n  Get libvips version\n*/\nNapi::Value libvipsVersion(const Napi::CallbackInfo& info) {\n  Napi::Env env = info.Env();\n  Napi::Object version = Napi::Object::New(env);\n\n  char semver[9];\n  std::snprintf(semver, sizeof(semver), \"%d.%d.%d\", vips_version(0), vips_version(1), vips_version(2));\n  version.Set(\"semver\", Napi::String::New(env, semver));\n#ifdef SHARP_USE_GLOBAL_LIBVIPS\n  version.Set(\"isGlobal\", Napi::Boolean::New(env, true));\n#else\n  version.Set(\"isGlobal\", Napi::Boolean::New(env, false));\n#endif\n#ifdef __EMSCRIPTEN__\n  version.Set(\"isWasm\", Napi::Boolean::New(env, true));\n#else\n  version.Set(\"isWasm\", Napi::Boolean::New(env, false));\n#endif\n  return version;\n}\n\n/*\n  Get available input/output file/buffer/stream formats\n*/\nNapi::Value format(const Napi::CallbackInfo& info) {\n  Napi::Env env = info.Env();\n  Napi::Object format = Napi::Object::New(env);\n  for (std::string const f : {\n    \"jpeg\", \"png\", \"webp\", \"tiff\", \"magick\", \"openslide\", \"dz\",\n    \"ppm\", \"fits\", \"gif\", \"svg\", \"heif\", \"pdf\", \"vips\", \"jp2k\", \"jxl\", \"rad\", \"dcraw\"\n  }) {\n    // Input\n    const VipsObjectClass *oc = vips_class_find(\"VipsOperation\", (f + \"load\").c_str());\n    Napi::Boolean hasInputFile = Napi::Boolean::New(env, oc);\n    Napi::Boolean hasInputBuffer =\n      Napi::Boolean::New(env, vips_type_find(\"VipsOperation\", (f + \"load_buffer\").c_str()));\n    Napi::Object input = Napi::Object::New(env);\n    input.Set(\"file\", hasInputFile);\n    input.Set(\"buffer\", hasInputBuffer);\n    input.Set(\"stream\", hasInputBuffer);\n    if (hasInputFile) {\n      const VipsForeignClass *fc = VIPS_FOREIGN_CLASS(oc);\n      if (fc->suffs) {\n        Napi::Array fileSuffix = Napi::Array::New(env);\n        const char **suffix = fc->suffs;\n        for (int i = 0; *suffix; i++, suffix++) {\n          fileSuffix.Set(i, Napi::String::New(env, *suffix));\n        }\n        input.Set(\"fileSuffix\", fileSuffix);\n      }\n    }\n    // Output\n    Napi::Boolean hasOutputFile =\n      Napi::Boolean::New(env, vips_type_find(\"VipsOperation\", (f + \"save\").c_str()));\n    Napi::Boolean hasOutputBuffer =\n      Napi::Boolean::New(env, vips_type_find(\"VipsOperation\", (f + \"save_buffer\").c_str()));\n    Napi::Object output = Napi::Object::New(env);\n    output.Set(\"file\", hasOutputFile);\n    output.Set(\"buffer\", hasOutputBuffer);\n    output.Set(\"stream\", hasOutputBuffer);\n    // Other attributes\n    Napi::Object container = Napi::Object::New(env);\n    container.Set(\"id\", f);\n    container.Set(\"input\", input);\n    container.Set(\"output\", output);\n    // Add to set of formats\n    format.Set(f, container);\n  }\n\n  // Raw, uncompressed data\n  Napi::Boolean supported = Napi::Boolean::New(env, true);\n  Napi::Boolean unsupported = Napi::Boolean::New(env, false);\n  Napi::Object rawInput = Napi::Object::New(env);\n  rawInput.Set(\"file\", unsupported);\n  rawInput.Set(\"buffer\", supported);\n  rawInput.Set(\"stream\", supported);\n  Napi::Object rawOutput = Napi::Object::New(env);\n  rawOutput.Set(\"file\", unsupported);\n  rawOutput.Set(\"buffer\", supported);\n  rawOutput.Set(\"stream\", supported);\n  Napi::Object raw = Napi::Object::New(env);\n  raw.Set(\"id\", \"raw\");\n  raw.Set(\"input\", rawInput);\n  raw.Set(\"output\", rawOutput);\n  format.Set(\"raw\", raw);\n\n  return format;\n}\n\n/*\n  (Un)block libvips operations at runtime.\n*/\nvoid block(const Napi::CallbackInfo& info) {\n  Napi::Array ops = info[size_t(0)].As<Napi::Array>();\n  bool const state = info[size_t(1)].As<Napi::Boolean>().Value();\n  for (unsigned int i = 0; i < ops.Length(); i++) {\n    vips_operation_block_set(ops.Get(i).As<Napi::String>().Utf8Value().c_str(), state);\n  }\n}\n\n/*\n  Synchronous, internal-only method used by some of the functional tests.\n  Calculates the maximum colour distance using the DE2000 algorithm\n  between two images of the same dimensions and number of channels.\n*/\nNapi::Value _maxColourDistance(const Napi::CallbackInfo& info) {\n  Napi::Env env = info.Env();\n\n  // Open input files\n  VImage image1;\n  sharp::ImageType imageType1 = sharp::DetermineImageType(info[size_t(0)].As<Napi::String>().Utf8Value().data());\n  if (imageType1 != sharp::ImageType::UNKNOWN) {\n    try {\n      image1 = VImage::new_from_file(info[size_t(0)].As<Napi::String>().Utf8Value().c_str());\n    } catch (...) {\n      throw Napi::Error::New(env, \"Input file 1 has corrupt header\");\n    }\n  } else {\n    throw Napi::Error::New(env, \"Input file 1 is of an unsupported image format\");\n  }\n  VImage image2;\n  sharp::ImageType imageType2 = sharp::DetermineImageType(info[size_t(1)].As<Napi::String>().Utf8Value().data());\n  if (imageType2 != sharp::ImageType::UNKNOWN) {\n    try {\n      image2 = VImage::new_from_file(info[size_t(1)].As<Napi::String>().Utf8Value().c_str());\n    } catch (...) {\n      throw Napi::Error::New(env, \"Input file 2 has corrupt header\");\n    }\n  } else {\n    throw Napi::Error::New(env, \"Input file 2 is of an unsupported image format\");\n  }\n  // Ensure same number of channels\n  if (image1.bands() != image2.bands()) {\n    throw Napi::Error::New(env, \"mismatchedBands\");\n  }\n  // Ensure same dimensions\n  if (image1.width() != image2.width() || image1.height() != image2.height()) {\n    throw Napi::Error::New(env, \"mismatchedDimensions\");\n  }\n\n  double maxColourDistance;\n  try {\n    // Premultiply and remove alpha\n    if (image1.has_alpha()) {\n      image1 = image1.premultiply().extract_band(1, VImage::option()->set(\"n\", image1.bands() - 1));\n    }\n    if (image2.has_alpha()) {\n      image2 = image2.premultiply().extract_band(1, VImage::option()->set(\"n\", image2.bands() - 1));\n    }\n    // Calculate colour distance\n    maxColourDistance = image1.dE00(image2).max();\n  } catch (vips::VError const &err) {\n    throw Napi::Error::New(env, err.what());\n  }\n\n  // Clean up libvips' per-request data and threads\n  vips_error_clear();\n  vips_thread_shutdown();\n\n  return Napi::Number::New(env, maxColourDistance);\n}\n\n#if defined(__GNUC__)\n// mallctl will be resolved by the runtime linker when jemalloc is being used\nextern \"C\" {\n  int mallctl(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen) __attribute__((weak));\n}\nNapi::Value _isUsingJemalloc(const Napi::CallbackInfo& info) {\n  Napi::Env env = info.Env();\n  return Napi::Boolean::New(env, mallctl != nullptr);\n}\n#else\nNapi::Value _isUsingJemalloc(const Napi::CallbackInfo& info) {\n  Napi::Env env = info.Env();\n  return Napi::Boolean::New(env, false);\n}\n#endif\n\n#if defined(__GNUC__) && defined(__x86_64__)\n// Are SSE 4.2 intrinsics available at runtime?\nNapi::Value _isUsingX64V2(const Napi::CallbackInfo& info) {\n  Napi::Env env = info.Env();\n  unsigned int eax, ebx, ecx, edx;\n  __asm__ __volatile__(\"cpuid\"\n    : \"=a\"(eax), \"=b\"(ebx), \"=c\"(ecx), \"=d\"(edx)\n    : \"a\"(1));\n  return Napi::Boolean::New(env, (ecx & 1U << 20) != 0);\n}\n#else\nNapi::Value _isUsingX64V2(const Napi::CallbackInfo& info) {\n  Napi::Env env = info.Env();\n  return Napi::Boolean::New(env, false);\n}\n#endif\n"
  },
  {
    "path": "src/utilities.h",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\n#ifndef SRC_UTILITIES_H_\n#define SRC_UTILITIES_H_\n\n#include <napi.h>\n\nNapi::Value cache(const Napi::CallbackInfo& info);\nNapi::Value concurrency(const Napi::CallbackInfo& info);\nNapi::Value counters(const Napi::CallbackInfo& info);\nNapi::Value simd(const Napi::CallbackInfo& info);\nNapi::Value libvipsVersion(const Napi::CallbackInfo& info);\nNapi::Value format(const Napi::CallbackInfo& info);\nvoid block(const Napi::CallbackInfo& info);\nNapi::Value _maxColourDistance(const Napi::CallbackInfo& info);\nNapi::Value _isUsingJemalloc(const Napi::CallbackInfo& info);\nNapi::Value _isUsingX64V2(const Napi::CallbackInfo& info);\n\n#endif  // SRC_UTILITIES_H_\n"
  },
  {
    "path": "test/bench/Dockerfile",
    "content": "FROM ubuntu:25.04\nARG BRANCH=main\n\n# Install basic dependencies\nRUN apt-get -y update && apt-get install -y build-essential curl git ca-certificates gnupg\n\n# Install latest Node.js LTS\nRUN curl -fsSL https://deb.nodesource.com/setup_24.x -o nodesource_setup.sh\nRUN bash nodesource_setup.sh\nRUN apt-get install -y nodejs\n\n# Install benchmark dependencies\nRUN apt-get install -y imagemagick libmagick++-dev graphicsmagick\n\n# Install sharp\nRUN mkdir /tmp/sharp\nRUN cd /tmp && git clone --single-branch --branch $BRANCH https://github.com/lovell/sharp.git\nRUN cd /tmp/sharp && npm install && npm run build\n\n# Install benchmark test\nRUN cd /tmp/sharp/test/bench && npm install --omit optional\n\nRUN cat /etc/os-release | grep VERSION=\nRUN node -v\n\nWORKDIR /tmp/sharp/test/bench\n\nCMD [ \"node\", \"perf\" ]\n"
  },
  {
    "path": "test/bench/package.json",
    "content": "{\n  \"name\": \"sharp-benchmark\",\n  \"version\": \"0.0.1\",\n  \"private\": true,\n  \"author\": \"Lovell Fuller <npm@lovell.info>\",\n  \"description\": \"Benchmark and performance tests for sharp\",\n  \"scripts\": {\n    \"test\": \"node perf && node random && node parallel\"\n  },\n  \"dependencies\": {\n    \"async\": \"3.2.6\",\n    \"benchmark\": \"2.1.4\",\n    \"gm\": \"1.25.1\",\n    \"imagemagick\": \"0.1.3\",\n    \"jimp\": \"1.6.0\"\n  },\n  \"optionalDependencies\": {\n    \"@tensorflow/tfjs-node\": \"4.22.0\",\n    \"mapnik\": \"4.5.9\"\n  },\n  \"license\": \"Apache-2.0\"\n}\n"
  },
  {
    "path": "test/bench/parallel.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nprocess.env.UV_THREADPOOL_SIZE = 64;\n\nconst assert = require('node:assert');\nconst async = require('async');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\nconst width = 720;\nconst height = 480;\n\nsharp.concurrency(1);\n\nconst timer = setInterval(() => {\n  console.dir(sharp.counters());\n}, 100);\n\nasync.mapSeries([1, 1, 2, 4, 8, 16, 32, 64], (parallelism, next) => {\n  const start = Date.now();\n  async.times(parallelism,\n    (_id, callback) => {\n      sharp(fixtures.inputJpg).resize(width, height).toBuffer((err, buffer) => {\n        buffer = null;\n        callback(err, Date.now() - start);\n      });\n    },\n    (err, ids) => {\n      assert(!err);\n      assert(ids.length === parallelism);\n      ids.sort();\n      const mean = ids.reduce((a, b) => a + b) / ids.length;\n      console.log(`${parallelism} parallel calls: fastest=${ids[0]}ms slowest=${ids[ids.length - 1]}ms mean=${mean}ms`);\n      next();\n    }\n  );\n}, () => {\n  clearInterval(timer);\n  console.dir(sharp.counters());\n});\n"
  },
  {
    "path": "test/bench/perf.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst { execSync } = require('node:child_process');\n\nconst async = require('async');\nconst Benchmark = require('benchmark');\n\nconst safeRequire = (name) => {\n  try {\n    return require(name);\n  } catch (_err) {}\n  return null;\n};\n\n// Contenders\nconst sharp = require('../../');\nconst gm = require('gm');\nconst imagemagick = require('imagemagick');\nconst mapnik = safeRequire('mapnik');\nconst { Jimp, JimpMime } = require('jimp');\n\nprocess.env.TF_CPP_MIN_LOG_LEVEL = 1;\nconst tfjs = safeRequire('@tensorflow/tfjs-node');\n\nconst fixtures = require('../fixtures');\n\nconst outputJpg = fixtures.path('output.jpg');\nconst outputPng = fixtures.path('output.png');\nconst outputWebP = fixtures.path('output.webp');\n\nconst width = 720;\nconst height = 588;\nconst heightPng = 540;\n\n// Disable libvips cache to ensure tests are as fair as they can be\nsharp.cache(false);\n\n// Spawn one thread per physical CPU core\nconst physicalCores = Number(execSync('lscpu -p | egrep -v \"^#\" | sort -u -t, -k 2,4 | wc -l', { encoding: 'utf-8' }).trim());\nconsole.log(`Detected ${physicalCores} physical cores`);\nsharp.concurrency(physicalCores);\n\nasync.series({\n  jpeg: (callback) => {\n    const inputJpgBuffer = fs.readFileSync(fixtures.inputJpg);\n    const jpegSuite = new Benchmark.Suite('jpeg');\n    // jimp\n    jpegSuite.add('jimp-buffer-buffer', {\n      defer: true,\n      fn: async (deferred) => {\n        const image = await Jimp.read(inputJpgBuffer);\n        await image\n          .resize({ w: width, h: height, mode: Jimp.RESIZE_BICUBIC })\n          .getBuffer(JimpMime.jpeg, { quality: 80 });\n        deferred.resolve();\n      }\n    }).add('jimp-file-file', {\n      defer: true,\n      fn: async (deferred) => {\n        const image = await Jimp.read(fixtures.inputJpg);\n        await image\n          .resize({ w: width, h: height, mode: Jimp.RESIZE_BICUBIC })\n          .getBuffer(JimpMime.jpeg, { quality: 80 });\n        deferred.resolve();\n      }\n    });\n    // mapnik\n    mapnik && jpegSuite.add('mapnik-file-file', {\n      defer: true,\n      fn: (deferred) => {\n        mapnik.Image.open(fixtures.inputJpg, (err, img) => {\n          if (err) throw err;\n          img\n            .resize(width, height, {\n              scaling_method: mapnik.imageScaling.lanczos\n            })\n            .save(outputJpg, 'jpeg:quality=80', (err) => {\n              if (err) throw err;\n              deferred.resolve();\n            });\n        });\n      }\n    }).add('mapnik-buffer-buffer', {\n      defer: true,\n      fn: (deferred) => {\n        mapnik.Image.fromBytes(inputJpgBuffer, { max_size: 3000 }, (err, img) => {\n          if (err) throw err;\n          img\n            .resize(width, height, {\n              scaling_method: mapnik.imageScaling.lanczos\n            })\n            .encode('jpeg:quality=80', (err) => {\n              if (err) throw err;\n              deferred.resolve();\n            });\n        });\n      }\n    });\n    // imagemagick\n    jpegSuite.add('imagemagick-file-file', {\n      defer: true,\n      fn: (deferred) => {\n        imagemagick.resize({\n          srcPath: fixtures.inputJpg,\n          dstPath: outputJpg,\n          quality: 0.8,\n          width,\n          height,\n          format: 'jpg',\n          filter: 'Lanczos'\n        }, (err) => {\n          if (err) {\n            throw err;\n          } else {\n            deferred.resolve();\n          }\n        });\n      }\n    });\n    // gm\n    jpegSuite.add('gm-buffer-file', {\n      defer: true,\n      fn: (deferred) => {\n        gm(inputJpgBuffer)\n          .filter('Lanczos')\n          .resize(width, height)\n          .quality(80)\n          .write(outputJpg, (err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('gm-buffer-buffer', {\n      defer: true,\n      fn: (deferred) => {\n        gm(inputJpgBuffer)\n          .filter('Lanczos')\n          .resize(width, height)\n          .quality(80)\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('gm-file-file', {\n      defer: true,\n      fn: (deferred) => {\n        gm(fixtures.inputJpg)\n          .filter('Lanczos')\n          .resize(width, height)\n          .quality(80)\n          .write(outputJpg, (err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('gm-file-buffer', {\n      defer: true,\n      fn: (deferred) => {\n        gm(fixtures.inputJpg)\n          .filter('Lanczos')\n          .resize(width, height)\n          .quality(80)\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    });\n    // tfjs\n    tfjs && jpegSuite.add('tfjs-node-buffer-buffer', {\n      defer: true,\n      fn: (deferred) => {\n        const decoded = tfjs.node.decodeJpeg(inputJpgBuffer);\n        const resized = tfjs.image.resizeBilinear(decoded, [height, width]);\n        tfjs\n          .node\n          .encodeJpeg(resized, 'rgb', 80)\n          .then(() => {\n            deferred.resolve();\n            tfjs.disposeVariables();\n          })\n          .catch((err) => {\n            throw err;\n          });\n      }\n    });\n    // sharp\n    jpegSuite.add('sharp-buffer-file', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .toFile(outputJpg, (err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-buffer-buffer', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-file-file', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(fixtures.inputJpg)\n          .resize(width, height)\n          .toFile(outputJpg, (err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-stream-stream', {\n      defer: true,\n      fn: (deferred) => {\n        const readable = fs.createReadStream(fixtures.inputJpg);\n        const writable = fs.createWriteStream(outputJpg);\n        writable.on('finish', () => {\n          deferred.resolve();\n        });\n        const pipeline = sharp()\n          .resize(width, height);\n        readable.pipe(pipeline).pipe(writable);\n      }\n    }).add('sharp-file-buffer', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(fixtures.inputJpg)\n          .resize(width, height)\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-promise', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .toBuffer()\n          .then(() => {\n            deferred.resolve();\n          })\n          .catch((err) => {\n            throw err;\n          });\n      }\n    }).on('cycle', (event) => {\n      console.log(`jpeg ${String(event.target)}`);\n    }).on('complete', function () {\n      callback(null, this.filter('fastest').map('name'));\n    }).run();\n  },\n  // Effect of applying operations\n  operations: (callback) => {\n    const inputJpgBuffer = fs.readFileSync(fixtures.inputJpg);\n    const operationsSuite = new Benchmark.Suite('operations');\n    operationsSuite.add('sharp-sharpen-mild', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .sharpen()\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-sharpen-radius', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .sharpen(3, 1, 3)\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-blur-mild', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .blur()\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-blur-radius', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .blur(3)\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-gamma', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .gamma()\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-normalise', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .normalise()\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-greyscale', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .greyscale()\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-greyscale-gamma', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .gamma()\n          .greyscale()\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-progressive', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .jpeg({ progressive: true })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-without-chroma-subsampling', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .jpeg({ chromaSubsampling: '4:4:4' })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-rotate', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .rotate(90)\n          .resize(width, height)\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-without-simd', {\n      defer: true,\n      fn: (deferred) => {\n        sharp.simd(false);\n        sharp(inputJpgBuffer)\n          .resize(width, height)\n          .toBuffer((err) => {\n            sharp.simd(true);\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-random-access-read', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer, { sequentialRead: false })\n          .resize(width, height)\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-crop-entropy', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height, {\n            fit: 'cover',\n            position: sharp.strategy.entropy\n          })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-crop-attention', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height, {\n            fit: 'cover',\n            position: sharp.strategy.attention\n          })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).on('cycle', (event) => {\n      console.log(`operations ${String(event.target)}`);\n    }).on('complete', function () {\n      callback(null, this.filter('fastest').map('name'));\n    }).run();\n  },\n  // Comparative speed of kernels\n  kernels: (callback) => {\n    const inputJpgBuffer = fs.readFileSync(fixtures.inputJpg);\n    (new Benchmark.Suite('kernels')).add('sharp-cubic', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height, { kernel: 'cubic' })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-lanczos2', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height, { kernel: 'lanczos2' })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-lanczos3', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height, { kernel: 'lanczos3' })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-mks2013', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height, { kernel: 'mks2013' })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-mks2021', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputJpgBuffer)\n          .resize(width, height, { kernel: 'mks2021' })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).on('cycle', (event) => {\n      console.log(`kernels ${String(event.target)}`);\n    }).on('complete', function () {\n      callback(null, this.filter('fastest').map('name'));\n    }).run();\n  },\n  // PNG\n  png: (callback) => {\n    const inputPngBuffer = fs.readFileSync(fixtures.inputPngAlphaPremultiplicationLarge);\n    const pngSuite = new Benchmark.Suite('png');\n    const minSamples = 64;\n    // jimp\n    pngSuite.add('jimp-buffer-buffer', {\n      defer: true,\n      fn: async (deferred) => {\n        const image = await Jimp.read(inputPngBuffer);\n        await image\n          .resize({ w: width, h: heightPng, mode: Jimp.RESIZE_BICUBIC })\n          .getBuffer(JimpMime.png, { deflateLevel: 6, filterType: 0 });\n        deferred.resolve();\n      }\n    }).add('jimp-file-file', {\n      defer: true,\n      fn: async (deferred) => {\n        const image = await Jimp.read(fixtures.inputPngAlphaPremultiplicationLarge);\n        await image\n          .resize({ w: width, h: heightPng, mode: Jimp.RESIZE_BICUBIC })\n          .write(outputPng, { deflateLevel: 6, filterType: 0 });\n        deferred.resolve();\n      }\n    });\n    // mapnik\n    mapnik && pngSuite.add('mapnik-file-file', {\n      defer: true,\n      fn: (deferred) => {\n        mapnik.Image.open(fixtures.inputPngAlphaPremultiplicationLarge, (err, img) => {\n          if (err) throw err;\n          img.premultiply((err, img) => {\n            if (err) throw err;\n            img.resize(width, heightPng, {\n              scaling_method: mapnik.imageScaling.lanczos\n            }, (err, img) => {\n              if (err) throw err;\n              img.demultiply((err, img) => {\n                if (err) throw err;\n                img.save(outputPng, 'png32:f=no:z=6', (err) => {\n                  if (err) throw err;\n                  deferred.resolve();\n                });\n              });\n            });\n          });\n        });\n      }\n    }).add('mapnik-buffer-buffer', {\n      defer: true,\n      fn: (deferred) => {\n        mapnik.Image.fromBytes(inputPngBuffer, { max_size: 3000 }, (err, img) => {\n          if (err) throw err;\n          img.premultiply((err, img) => {\n            if (err) throw err;\n            img.resize(width, heightPng, {\n              scaling_method: mapnik.imageScaling.lanczos\n            }, (err, img) => {\n              if (err) throw err;\n              img.demultiply((err, img) => {\n                if (err) throw err;\n                img.encode('png32:f=no:z=6', (err) => {\n                  if (err) throw err;\n                  deferred.resolve();\n                });\n              });\n            });\n          });\n        });\n      }\n    });\n    // imagemagick\n    pngSuite.add('imagemagick-file-file', {\n      defer: true,\n      fn: (deferred) => {\n        imagemagick.resize({\n          srcPath: fixtures.inputPngAlphaPremultiplicationLarge,\n          dstPath: outputPng,\n          width,\n          height: heightPng,\n          filter: 'Lanczos',\n          customArgs: [\n            '-define', 'PNG:compression-level=6',\n            '-define', 'PNG:compression-filter=0'\n          ]\n        }, (err) => {\n          if (err) {\n            throw err;\n          } else {\n            deferred.resolve();\n          }\n        });\n      }\n    });\n    // gm\n    pngSuite.add('gm-file-file', {\n      defer: true,\n      fn: (deferred) => {\n        gm(fixtures.inputPngAlphaPremultiplicationLarge)\n          .filter('Lanczos')\n          .resize(width, heightPng)\n          .define('PNG:compression-level=6')\n          .define('PNG:compression-filter=0')\n          .write(outputPng, (err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('gm-file-buffer', {\n      defer: true,\n      fn: (deferred) => {\n        gm(fixtures.inputPngAlphaPremultiplicationLarge)\n          .filter('Lanczos')\n          .resize(width, heightPng)\n          .define('PNG:compression-level=6')\n          .define('PNG:compression-filter=0')\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    });\n    // sharp\n    pngSuite.add('sharp-buffer-file', {\n      defer: true,\n      minSamples,\n      fn: (deferred) => {\n        sharp(inputPngBuffer)\n          .resize(width, heightPng)\n          .png({ compressionLevel: 6 })\n          .toFile(outputPng, (err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-buffer-buffer', {\n      defer: true,\n      minSamples,\n      fn: (deferred) => {\n        sharp(inputPngBuffer)\n          .resize(width, heightPng)\n          .png({ compressionLevel: 6 })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-file-file', {\n      defer: true,\n      minSamples,\n      fn: (deferred) => {\n        sharp(fixtures.inputPngAlphaPremultiplicationLarge)\n          .resize(width, heightPng)\n          .png({ compressionLevel: 6 })\n          .toFile(outputPng, (err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-file-buffer', {\n      defer: true,\n      minSamples,\n      fn: (deferred) => {\n        sharp(fixtures.inputPngAlphaPremultiplicationLarge)\n          .resize(width, heightPng)\n          .png({ compressionLevel: 6 })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-progressive', {\n      defer: true,\n      minSamples,\n      fn: (deferred) => {\n        sharp(inputPngBuffer)\n          .resize(width, heightPng)\n          .png({ compressionLevel: 6, progressive: true })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-adaptiveFiltering', {\n      defer: true,\n      minSamples,\n      fn: (deferred) => {\n        sharp(inputPngBuffer)\n          .resize(width, heightPng)\n          .png({ adaptiveFiltering: true, compressionLevel: 6 })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-compressionLevel=9', {\n      defer: true,\n      minSamples,\n      fn: (deferred) => {\n        sharp(inputPngBuffer)\n          .resize(width, heightPng)\n          .png({ compressionLevel: 9 })\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    });\n    pngSuite.on('cycle', (event) => {\n      console.log(` png ${String(event.target)}`);\n    }).on('complete', function () {\n      callback(null, this.filter('fastest').map('name'));\n    }).run();\n  },\n  // WebP\n  webp: (callback) => {\n    const inputWebPBuffer = fs.readFileSync(fixtures.inputWebP);\n    (new Benchmark.Suite('webp')).add('sharp-buffer-file', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputWebPBuffer)\n          .resize(width, height)\n          .toFile(outputWebP, (err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-buffer-buffer', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(inputWebPBuffer)\n          .resize(width, height)\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-file-file', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(fixtures.inputWebP)\n          .resize(width, height)\n          .toFile(outputWebP, (err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).add('sharp-file-buffer', {\n      defer: true,\n      fn: (deferred) => {\n        sharp(fixtures.inputWebP)\n          .resize(width, height)\n          .toBuffer((err) => {\n            if (err) {\n              throw err;\n            } else {\n              deferred.resolve();\n            }\n          });\n      }\n    }).on('cycle', (event) => {\n      console.log(`webp ${String(event.target)}`);\n    }).on('complete', function () {\n      callback(null, this.filter('fastest').map('name'));\n    }).run();\n  }\n}, (err, results) => {\n  if (err) {\n    throw err;\n  }\n  Object.keys(results).forEach((format) => {\n    if (results[format].toString().substr(0, 5) !== 'sharp') {\n      console.log(`sharp was slower than ${results[format]} for ${format}`);\n    }\n  });\n  console.dir(sharp.cache());\n});\n"
  },
  {
    "path": "test/bench/random.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst imagemagick = require('imagemagick');\nconst gm = require('gm');\nconst assert = require('node:assert');\nconst Benchmark = require('benchmark');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\nsharp.cache(false);\n\nconst min = 320;\nconst max = 960;\n\nconst randomDimension = () => Math.ceil((Math.random() * (max - min)) + min);\n\nnew Benchmark.Suite('random').add('imagemagick', {\n  defer: true,\n  fn: (deferred) => {\n    imagemagick.resize({\n      srcPath: fixtures.inputJpg,\n      dstPath: fixtures.path('output.jpg'),\n      quality: 0.8,\n      width: randomDimension(),\n      height: randomDimension(),\n      format: 'jpg',\n      filter: 'Lanczos'\n    }, (err) => {\n      if (err) {\n        throw err;\n      } else {\n        deferred.resolve();\n      }\n    });\n  }\n}).add('gm', {\n  defer: true,\n  fn: (deferred) => {\n    gm(fixtures.inputJpg)\n      .resize(randomDimension(), randomDimension())\n      .filter('Lanczos')\n      .quality(80)\n      .toBuffer((err, buffer) => {\n        if (err) {\n          throw err;\n        } else {\n          assert.notStrictEqual(null, buffer);\n          deferred.resolve();\n        }\n      });\n  }\n}).add('sharp', {\n  defer: true,\n  fn: (deferred) => {\n    sharp(fixtures.inputJpg)\n      .resize(randomDimension(), randomDimension())\n      .toBuffer((err, buffer) => {\n        if (err) {\n          throw err;\n        } else {\n          assert.notStrictEqual(null, buffer);\n          deferred.resolve();\n        }\n      });\n  }\n}).on('cycle', (event) => {\n  console.log(String(event.target));\n}).on('complete', function () {\n  const winner = this.filter('fastest').map('name');\n  assert.strictEqual('sharp', String(winner), `sharp was slower than ${winner}`);\n}).run();\n"
  },
  {
    "path": "test/bench/run-with-docker.sh",
    "content": "#!/usr/bin/env bash\nset -e\n\nif ! type docker >/dev/null; then\n  echo \"Please install docker\"\n  exit 1\nfi\n\nBRANCH=$(git branch --show-current)\necho \"Running sharp performance tests using $BRANCH branch\"\n\ndocker build --build-arg \"BRANCH=$BRANCH\" -t sharp-test-bench .\ndocker run --rm -it sharp-test-bench\n"
  },
  {
    "path": "test/fixtures/index.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst path = require('node:path');\nconst sharp = require('../../');\nconst maxColourDistance = require('../../lib/sharp')._maxColourDistance;\n\n// Helpers\nconst getPath = (filename) => path.join(__dirname, filename);\n\n// Generates a 64-bit-as-binary-string image fingerprint\n// Based on the dHash gradient method - see http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html\nasync function fingerprint (image) {\n  return sharp(image)\n    .flatten('gray')\n    .greyscale()\n    .normalise()\n    .resize(9, 8, { fit: sharp.fit.fill })\n    .raw()\n    .toBuffer()\n    .then((data) => {\n      let fingerprint = '';\n      for (let col = 0; col < 8; col++) {\n        for (let row = 0; row < 8; row++) {\n          const left = data[(row * 8) + col];\n          const right = data[(row * 8) + col + 1];\n          fingerprint = fingerprint + (left < right ? '1' : '0');\n        }\n      }\n      return fingerprint;\n    });\n}\n\nmodule.exports = {\n\n  inputJpgWithLandscapeExif1: getPath('Landscape_1.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithLandscapeExif2: getPath('Landscape_2.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithLandscapeExif3: getPath('Landscape_3.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithLandscapeExif4: getPath('Landscape_4.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithLandscapeExif5: getPath('Landscape_5.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithLandscapeExif6: getPath('Landscape_6.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithLandscapeExif7: getPath('Landscape_7.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithLandscapeExif8: getPath('Landscape_8.jpg'), // https://github.com/recurser/exif-orientation-examples\n\n  inputJpgWithPortraitExif1: getPath('Portrait_1.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithPortraitExif2: getPath('Portrait_2.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithPortraitExif3: getPath('Portrait_3.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithPortraitExif4: getPath('Portrait_4.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithPortraitExif5: getPath('Portrait_5.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithPortraitExif6: getPath('Portrait_6.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithPortraitExif7: getPath('Portrait_7.jpg'), // https://github.com/recurser/exif-orientation-examples\n  inputJpgWithPortraitExif8: getPath('Portrait_8.jpg'), // https://github.com/recurser/exif-orientation-examples\n\n  inputJpg: getPath('2569067123_aca715a2ee_o.jpg'), // http://www.flickr.com/photos/grizdave/2569067123/\n  inputJpgWithExif: getPath('Landscape_8.jpg'), // https://github.com/recurser/exif-orientation-examples/blob/master/Landscape_8.jpg\n  inputJpgWithIptcAndXmp: getPath('Landscape_9.jpg'), // https://unsplash.com/photos/RWAIyGmgHTQ\n  inputJpgWithExifMirroring: getPath('Landscape_5.jpg'), // https://github.com/recurser/exif-orientation-examples/blob/master/Landscape_5.jpg\n  inputJpgWithGammaHoliness: getPath('gamma_dalai_lama_gray.jpg'), // http://www.4p8.com/eric.brasseur/gamma.html\n  inputJpgWithCmykProfile: getPath('Channel_digital_image_CMYK_color.jpg'), // http://en.wikipedia.org/wiki/File:Channel_digital_image_CMYK_color.jpg\n  inputJpgWithCmykNoProfile: getPath('Channel_digital_image_CMYK_color_no_profile.jpg'),\n  inputJpgWithCorruptHeader: getPath('corrupt-header.jpg'),\n  inputJpgWithLowContrast: getPath('low-contrast.jpg'), // http://www.flickr.com/photos/grizdave/2569067123/\n  inputJpgLarge: getPath('giant-image.jpg'),\n  inputJpg320x240: getPath('320x240.jpg'), // http://www.andrewault.net/2010/01/26/create-a-test-pattern-video-with-perl/\n  inputJpgOverlayLayer2: getPath('alpha-layer-2-ink.jpg'),\n  inputJpgTruncated: getPath('truncated.jpg'), // head -c 10000 2569067123_aca715a2ee_o.jpg > truncated.jpg\n  inputJpgCenteredImage: getPath('centered_image.jpeg'),\n  inputJpgRandom: getPath('random.jpg'), // convert -size 200x200 xc:   +noise Random   random.jpg\n  inputJpgThRandom: getPath('thRandom.jpg'), // convert random.jpg  -channel G -threshold 5% -separate +channel -negate thRandom.jpg\n  inputJpgLossless: getPath('testimgl.jpg'), // Lossless JPEG from ftp://ftp.fu-berlin.de/unix/X11/graphics/ImageMagick/delegates/ljpeg-6b.tar.gz\n\n  inputPng: getPath('50020484-00001.png'), // http://c.searspartsdirect.com/lis_png/PLDM/50020484-00001.png\n  inputPngGradients: getPath('gradients-rgb8.png'),\n  inputPngWithTransparency: getPath('blackbug.png'), // public domain\n  inputPngCompleteTransparency: getPath('full-transparent.png'),\n  inputPngWithGreyAlpha: getPath('grey-8bit-alpha.png'),\n  inputPngWithOneColor: getPath('2x2_fdcce6.png'),\n  inputPngWithTransparency16bit: getPath('tbgn2c16.png'), // http://www.schaik.com/pngsuite/tbgn2c16.png\n  inputPng8BitGreyBackground: getPath('bgbn4a08.png'), // http://www.schaik.com/pngsuite/bgbn4a08.png\n  inputPng16BitGreyBackground: getPath('bggn4a16.png'), // http://www.schaik.com/pngsuite/bggn4a16.png\n  inputPng16BitGreyAlpha: getPath('16-bit-grey-alpha.png'), // CC-BY-NC-SA florc http://www.colourlovers.com/pattern/50713/pat\n  inputPngOverlayLayer0: getPath('alpha-layer-0-background.png'),\n  inputPngOverlayLayer1: getPath('alpha-layer-1-fill.png'),\n  inputPngAlphaPremultiplicationSmall: getPath('alpha-premultiply-1024x768-paper.png'),\n  inputPngAlphaPremultiplicationLarge: getPath('alpha-premultiply-2048x1536-paper.png'),\n  inputPngBooleanNoAlpha: getPath('bandbool.png'),\n  inputPngTestJoinChannel: getPath('testJoinChannel.png'),\n  inputPngTruncated: getPath('truncated.png'), // gm convert 2569067123_aca715a2ee_o.jpg -resize 320x240 saw.png ; head -c 10000 saw.png > truncated.png\n  inputPngEmbed: getPath('embedgravitybird.png'), // Released to sharp under a CC BY 4.0\n  inputPngRGBWithAlpha: getPath('2569067123_aca715a2ee_o.png'), // http://www.flickr.com/photos/grizdave/2569067123/ (same as inputJpg)\n  inputPngImageInAlpha: getPath('image-in-alpha.png'), // https://github.com/lovell/sharp/issues/1597\n  inputPngSolidAlpha: getPath('with-alpha.png'), // https://github.com/lovell/sharp/issues/1599\n  inputPngP3: getPath('p3.png'), // https://github.com/lovell/sharp/issues/2862\n  inputPngPalette: getPath('swiss.png'), // https://github.com/randy408/libspng/issues/188\n  inputPngTrimIncludeAlpha: getPath('trim-mc.png'), // https://github.com/lovell/sharp/issues/2166\n  inputPngTrimSpecificColour: getPath('Flag_of_the_Netherlands.png'), // https://commons.wikimedia.org/wiki/File:Flag_of_the_Netherlands.svg\n  inputPngTrimSpecificColour16bit: getPath('Flag_of_the_Netherlands-16bit.png'), // convert Flag_of_the_Netherlands.png -depth 16 Flag_of_the_Netherlands-16bit.png\n  inputPngTrimSpecificColourIncludeAlpha: getPath('Flag_of_the_Netherlands-alpha.png'), // convert Flag_of_the_Netherlands.png -alpha set -background none -channel A -evaluate multiply 0.5 +channel Flag_of_the_Netherlands-alpha.png\n  inputPngUint32Limit: getPath('65536-uint32-limit.png'), // https://alexandre.alapetite.fr/doc-alex/large-image/\n  inputPngWithProPhotoProfile: getPath('prophoto.png'),\n\n  inputWebP: getPath('4.webp'), // http://www.gstatic.com/webp/gallery/4.webp\n  inputWebPWithTransparency: getPath('5_webp_a.webp'), // http://www.gstatic.com/webp/gallery3/5_webp_a.webp\n  inputWebPAnimated: getPath('rotating-squares.webp'), // http://www.gstatic.com/webp/gallery3/5_webp_a.webp\n  inputWebPAnimatedLoop3: getPath('animated-loop-3.webp'), // http://www.gstatic.com/webp/gallery3/5_webp_a.webp\n  inputWebPAnimatedBigHeight: getPath('big-height.webp'),\n  inputTiff: getPath('G31D.TIF'), // http://www.fileformat.info/format/tiff/sample/e6c9a6e5253348f4aef6d17b534360ab/index.htm\n  inputTiffMultipage: getPath('G31D_MULTI.TIF'), // gm convert G31D.TIF -resize 50% G31D_2.TIF ; tiffcp G31D.TIF G31D_2.TIF G31D_MULTI.TIF\n  inputTiffCielab: getPath('cielab-dagams.tiff'), // https://github.com/lovell/sharp/issues/646\n  inputTiffUncompressed: getPath('uncompressed_tiff.tiff'), // https://code.google.com/archive/p/imagetestsuite/wikis/TIFFTestSuite.wiki file: 0c84d07e1b22b76f24cccc70d8788e4a.tif\n  inputTiff8BitDepth: getPath('8bit_depth.tiff'),\n  inputTifftagPhotoshop: getPath('tifftag-photoshop.tiff'), // https://github.com/lovell/sharp/issues/1600\n  inputTiffFogra: getPath('fogra-0-100-100-0.tif'), // https://github.com/lovell/sharp/issues/4045\n  inputTiffGeo: getPath('bonne.geo.tif'), // https://download.osgeo.org/geotiff/samples/intergraph\n\n  inputJp2: getPath('relax.jp2'), // https://www.fnordware.com/j2k/relax.jp2\n  inputJp2TileParts: getPath('relax_tileparts.jp2'), // kdu_expand -i relax.jp2 -o relax-tmp.tif ; kdu_compress -i relax-tmp.tif -o relax_tileparts.jp2 -jp2_space sRGB Clayers=8 -rate 1.0,0.04 Stiles='{128,128}' ORGtparts=L ; rm relax-tmp.tif\n  inputGif: getPath('Crash_test.gif'), // http://upload.wikimedia.org/wikipedia/commons/e/e3/Crash_test.gif\n  inputGifGreyPlusAlpha: getPath('grey-plus-alpha.gif'), // http://i.imgur.com/gZ5jlmE.gif\n  inputGifAnimated: getPath('rotating-squares.gif'), // CC0 https://loading.io/spinner/blocks/-rotating-squares-preloader-gif\n  inputGifAnimatedLoop3: getPath('animated-loop-3.gif'), // CC-BY-SA-4.0 Petrus3743 https://commons.wikimedia.org/wiki/File:01-Goldener_Schnitt_Formel-Animation.gif\n  inputSvg: getPath('check.svg'), // http://dev.w3.org/SVG/tools/svgweb/samples/svg-files/check.svg\n  inputSvgSmallViewBox: getPath('circle.svg'),\n  inputSvgWithEmbeddedImages: getPath('struct-image-04-t.svg'), // https://dev.w3.org/SVG/profiles/1.2T/test/svg/struct-image-04-t.svg\n  inputAvif: getPath('sdr_cosmos12920_cicp1-13-6_yuv444_full_qp10.avif'), // CC by-nc-nd https://github.com/AOMediaCodec/av1-avif/tree/master/testFiles/Netflix\n\n  inputJPGBig: getPath('flowers.jpeg'),\n\n  inputPngDotAndLines: getPath('dot-and-lines.png'),\n\n  inputPngStripesV: getPath('stripesV.png'),\n  inputPngStripesH: getPath('stripesH.png'),\n\n  inputJpgBooleanTest: getPath('booleanTest.jpg'),\n\n  inputV: getPath('vfile.v'),\n\n  inputJpgClahe: getPath('concert.jpg'), // public domain - https://www.flickr.com/photos/mars_/14389236779/\n\n  testPattern: getPath('test-pattern.png'),\n\n  inputPngWithTransparent: getPath('d.png'),\n  // Path for tests requiring human inspection\n  path: getPath,\n\n  // Path for expected output images\n  expected: (filename) => getPath(path.join('expected', filename)),\n\n  // Verify similarity of expected vs actual images via fingerprint\n  // Specify distance threshold using `options={threshold: 42}`, default\n  // `threshold` is 5;\n  assertSimilar: async (expectedImage, actualImage, options, callback) => {\n    if (typeof options === 'function') {\n      callback = options;\n      options = {};\n    }\n    if (typeof options === 'undefined' || options === null) {\n      options = {};\n    }\n    if (options.threshold === null || typeof options.threshold === 'undefined') {\n      options.threshold = 5; // ~7% threshold\n    }\n    if (typeof options.threshold !== 'number') {\n      throw new TypeError('`options.threshold` must be a number');\n    }\n\n    try {\n      const [expectedFingerprint, actualFingerprint] = await Promise.all([\n        fingerprint(expectedImage),\n        fingerprint(actualImage)\n      ]);\n      let distance = 0;\n      for (let i = 0; i < 64; i++) {\n        if (expectedFingerprint[i] !== actualFingerprint[i]) {\n          distance++;\n        }\n      }\n      if (distance > options.threshold) {\n        throw new Error(`Expected maximum similarity distance: ${options.threshold}. Actual: ${distance}.`);\n      }\n    } catch (err) {\n      if (callback) {\n        return callback(err);\n      }\n      throw err;\n    }\n    if (callback) {\n      callback();\n    }\n  },\n\n  assertMaxColourDistance: (actualImagePath, expectedImagePath, acceptedDistance) => {\n    if (typeof actualImagePath !== 'string') {\n      throw new TypeError(`\\`actualImagePath\\` must be a string; got ${actualImagePath}`);\n    }\n    if (typeof expectedImagePath !== 'string') {\n      throw new TypeError(`\\`expectedImagePath\\` must be a string; got ${expectedImagePath}`);\n    }\n    if (typeof acceptedDistance !== 'number') {\n      // Default threshold\n      acceptedDistance = 1;\n    }\n    const distance = maxColourDistance(actualImagePath, expectedImagePath);\n    if (distance > acceptedDistance) {\n      throw new Error(`Expected maximum absolute distance of ${acceptedDistance}, actual ${distance}`);\n    }\n  }\n\n};\n"
  },
  {
    "path": "test/leak/leak.sh",
    "content": "#!/usr/bin/env bash\nset -e\n\nif ! type valgrind >/dev/null; then\n  echo \"Please install valgrind before running memory leak tests\"\n  exit 1\nfi\n\ncurl -s -o ./test/leak/libvips.supp https://raw.githubusercontent.com/libvips/libvips/master/suppressions/valgrind.supp\n\nTESTS=$(ls test/unit --ignore=svg.js --ignore=text.js)\nfor test in $TESTS; do\n  G_SLICE=always-malloc G_DEBUG=gc-friendly VIPS_LEAK=1 VIPS_NOVECTOR=1 valgrind \\\n    --suppressions=test/leak/libvips.supp \\\n    --suppressions=test/leak/sharp.supp \\\n    --gen-suppressions=yes \\\n    --leak-check=full \\\n    --show-leak-kinds=definite,indirect \\\n    --num-callers=20 \\\n    --trace-children=yes \\\n    node --zero-fill-buffers --test \"test/unit/$test\";\ndone\n"
  },
  {
    "path": "test/leak/sharp.supp",
    "content": "# libjpeg warnings\n{\n  cond_jpeg_read_scanlines\n  Memcheck:Cond\n  ...\n  fun:jpeg_read_scanlines\n}\n{\n  value_jpeg_read_scanlines\n  Memcheck:Value8\n  ...\n  fun:jpeg_read_scanlines\n}\n{\n  cond_jpeg_write_scanlines\n  Memcheck:Cond\n  ...\n  fun:jpeg_write_scanlines\n}\n{\n  cond_jpeg_finish_compress\n  Memcheck:Cond\n  ...\n  fun:jpeg_finish_compress\n}\n{\n  value_jpeg_finish_compress\n  Memcheck:Value8\n  ...\n  fun:jpeg_finish_compress\n}\n{\n  value_jpeg_obj\n  Memcheck:Value8\n  obj:*/libjpeg.so*\n}\n{\n  cond_jpeg_obj\n  Memcheck:Cond\n  obj:*/libjpeg.so*\n}\n{\n  value_jpeg_obj_static\n  Memcheck:Value8\n  obj:*/libvips.so*\n}\n{\n  cond_jpeg_obj_static\n  Memcheck:Cond\n  obj:*/libvips.so*\n}\n{\n  param_jpeg_jpeg_finish_compress\n  Memcheck:Param\n  write(buf)\n  ...\n  fun:jpeg_finish_compress\n}\n# libpng\n{\n  cond_libpng_png_read_row\n  Memcheck:Cond\n  ...\n  fun:png_read_row\n}\n{\n  value_libpng_png_read_row\n  Memcheck:Value8\n  ...\n  fun:png_read_row\n}\n{\n  cond_libpng_png_write_rows\n  Memcheck:Cond\n  ...\n  fun:png_write_row\n  fun:png_write_rows\n}\n{\n  value_libpng_png_write_rows\n  Memcheck:Value8\n  ...\n  fun:png_write_row\n  fun:png_write_rows\n}\n\n# libwebp\n{\n  cond_libwebp_WebPEncodeRGBA\n  Memcheck:Cond\n  ...\n  fun:WebPEncodeRGBA\n}\n{\n  value_libwebp_WebPEncodeRGBA\n  Memcheck:Value8\n  ...\n  fun:WebPEncodeRGBA\n}\n{\n  cond_libwebp_WebPEncodeRGB\n  Memcheck:Cond\n  ...\n  fun:WebPEncodeRGB\n}\n{\n  value_libwebp_WebPEncodeRGB\n  Memcheck:Value8\n  ...\n  fun:WebPEncodeRGB\n}\n{\n  value_libwebp_WebPEncode\n  Memcheck:Value8\n  ...\n  fun:WebPEncode\n}\n{\n  cond_libwebp_WebPEncode\n  Memcheck:Cond\n  ...\n  fun:WebPEncode\n}\n{\n  value_libwebp_WebPPictureImportRGBA\n  Memcheck:Value8\n  ...\n  fun:WebPPictureImportRGBA\n}\n{\n  cond_libwebp_WebPPictureImportRGBA\n  Memcheck:Cond\n  ...\n  fun:WebPPictureImportRGBA\n}\n{\n  value_libwebp_WebPPictureImportRGB\n  Memcheck:Value8\n  ...\n  fun:WebPPictureImportRGB\n}\n{\n  cond_libwebp_WebPPictureImportRGB\n  Memcheck:Cond\n  ...\n  fun:WebPPictureImportRGB\n}\n{\n  value_libwebp_WebPDecode\n  Memcheck:Value8\n  ...\n  fun:WebPDecode\n}\n{\n  cond_libwebp_WebPDecode\n  Memcheck:Cond\n  ...\n  fun:WebPDecode\n}\n{\n  cond_libwebp_generic\n  Memcheck:Cond\n  obj:*/libwebp.so.*\n}\n\n# tiff\n{\n  param_tiff_write_encoded_tile\n  Memcheck:Param\n  write(buf)\n  fun:write\n  ...\n  fun:TIFFWriteEncodedTile\n}\n\n# fontconfig\n{\n  leak_fontconfig_FcConfigSubstituteWithPat\n  Memcheck:Leak\n  match-leak-kinds: definite,indirect\n  ...\n  fun:FcConfigSubstituteWithPat\n}\n{\n  leak_fontconfig_init\n  Memcheck:Leak\n  match-leak-kinds: indirect\n  fun:calloc\n  ...\n  fun:FcInitLoadConfigAndFonts\n}\n{\n  leak_fontconfig_XML_ParseBuffer\n  Memcheck:Leak\n  match-leak-kinds: definite\n  ...\n  fun:XML_ParseBuffer\n  obj:*/libfontconfig.so.*\n}\n{\n  leak_fontconfig_XML_ParseBuffer_indirect\n  Memcheck:Leak\n  match-leak-kinds: indirect\n  ...\n  fun:XML_ParseBuffer\n  obj:*/libfontconfig.so.*\n}\n{\n  leak_fontconfig_FcInitLoadConfigAndFonts\n  Memcheck:Leak\n  match-leak-kinds: definite\n  fun:malloc\n  ...\n  fun:XML_ParseBuffer\n  ...\n  fun:FcInitLoadConfigAndFonts\n}\n{\n  leak_fontconfig_FcDefaultSubstitute\n  Memcheck:Leak\n  match-leak-kinds: indirect\n  fun:calloc\n  ...\n  fun:FcDefaultSubstitute\n  ...\n  fun:pango_itemize_with_base_dir\n  ...\n  fun:pango_layout_get_pixel_extents\n  fun:vips_text_get_extents\n}\n{\n  leak_fontconfig_FcLangSetCreate\n  Memcheck:Leak\n  match-leak-kinds: indirect\n  fun:malloc\n  fun:FcLangSetCreate\n  fun:FcLangSetCopy\n  fun:FcValueSave\n  ...\n  fun:FcFontRenderPrepare\n  fun:FcFontMatch\n  ...\n  fun:pango_itemize_with_base_dir\n  ...\n  fun:pango_layout_get_pixel_extents\n  fun:vips_text_get_extents\n}\n\n# heif\n{\n  cond_heif_encode_image\n  Memcheck:Cond\n  ...\n  fun:heif_context_encode_image\n}\n{\n  value8_heif_encode_image\n  Memcheck:Value8\n  ...\n  fun:heif_context_encode_image\n}\n{\n  cond_heif_aom_codec_encode\n  Memcheck:Cond\n  ...\n  fun:aom_codec_encode\n}\n{\n  value8_heif_aom_codec_encode\n  Memcheck:Value8\n  ...\n  fun:aom_codec_encode\n}\n{\n  value1_heif_aom_codec_encode\n  Memcheck:Value1\n  ...\n  fun:aom_codec_encode\n}\n{\n  cond_heif_av1_encode_frame\n  Memcheck:Cond\n  ...\n  fun:av1_encode_frame\n}\n{\n  value8_heif_av1_encode_frame\n  Memcheck:Value8\n  ...\n  fun:av1_encode_frame\n}\n{\n  cond_heif_context_write\n  Memcheck:Cond\n  ...\n  fun:heif_context_write\n}\n{\n  value8_heif_context_write\n  Memcheck:Value8\n  ...\n  fun:heif_context_write\n}\n{\n  cond_heif_context_read\n  Memcheck:Cond\n  ...\n  fun:heif_context_read_from_reader\n}\n{\n  value8_heif_context_read\n  Memcheck:Value8\n  ...\n  fun:heif_context_read_from_reader\n}\n\n# glib\n{\n  leak_glib__tls_get_addr\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:malloc\n  fun:allocate_dtv_entry\n  fun:allocate_and_init\n  fun:tls_get_addr_tail\n  fun:__tls_get_addr\n}\n{\n  value_g_utf8_make_valid_strlen\n  Memcheck:Value8\n  fun:strlen\n  fun:g_utf8_make_valid\n}\n{\n  value_g_utf8_make_valid_strncpy\n  Memcheck:Value8\n  fun:strncpy\n  fun:g_strndup\n  ...\n  fun:g_utf8_make_valid\n}\n{\n  cond_g_utf8_make_valid_strncpy\n  Memcheck:Cond\n  fun:strncpy\n  fun:g_strndup\n  ...\n  fun:g_utf8_make_valid\n}\n\n# libvips\n{\n  cond_libvips_interpolate_lbb\n  Memcheck:Cond\n  ...\n  fun:_ZL32vips_interpolate_lbb_interpolateP16_VipsInterpolatePvP11_VipsRegiondd\n  fun:vips_affine_gen\n}\n{\n  cond_libvips_conv_gen\n  Memcheck:Cond\n  fun:conv_gen\n  fun:vips_region_generate\n}\n{\n  value_libvips_col_sRGB2scRGB_8\n  Memcheck:Value8\n  fun:vips_col_sRGB2scRGB_8\n}\n{\n  value_libvips_col_sRGB2scRGB_line_8\n  Memcheck:Value8\n  fun:vips_sRGB2scRGB_line_8\n}\n{\n  value_libvips_write_webp\n  Memcheck:Value8\n  ...\n  fun:write_webp.constprop.1\n  fun:vips__webp_write_buffer\n}\n{\n  value_libvips_start_thread\n  Memcheck:Value8\n  obj:*/libvips.so.*\n  fun:start_thread\n  fun:clone\n}\n{\n  cond_libvips_vips_cast_gen\n  Memcheck:Cond\n  fun:vips_cast_gen\n}\n{\n  cond_libvips_vips_region_fill\n  Memcheck:Cond\n  ...\n  fun:vips_region_fill\n  fun:vips_region_prepare\n}\n{\n  cond_libvips_vips_region_prepare_to\n  Memcheck:Cond\n  ...\n  fun:vips_region_prepare_to\n}\n{\n  cond_libvips_vips_stats_scan\n  Memcheck:Cond\n  fun:vips_stats_scan\n}\n{\n  value_libvips_vips_region_fill\n  Memcheck:Value8\n  ...\n  fun:vips_region_fill\n  fun:vips_region_prepare\n}\n{\n  value_libvips_vips_hist_find_uchar_scan\n  Memcheck:Value8\n  fun:vips_hist_find_uchar_scan\n}\n{\n  value_libvips_write_webp_image\n  Memcheck:Value8\n  ...\n  fun:write_webp_image\n}\n{\n  param_libvips_write_buf\n  Memcheck:Param\n  write(buf)\n  fun:write\n  ...\n  fun:start_thread\n}\n{\n  cond_libvips_source_read\n  Memcheck:Cond\n  ...\n  fun:vips_source_read\n}\n{\n  value8_libvips_source_read\n  Memcheck:Value8\n  ...\n  fun:vips_source_read\n}\n{\n  cond_libvips_target_finish\n  Memcheck:Cond\n  ...\n  fun:vips_target_finish\n}\n{\n  value8_libvips_target_finish\n  Memcheck:Value8\n  ...\n  fun:vips_target_finish\n}\n{\n  value8_libvips_static\n  Memcheck:Value8\n  obj:*/libvips-cpp.so.*\n}\n{\n  cond_libvips_static\n  Memcheck:Cond\n  obj:*/libvips-cpp.so.*\n}\n{\n  leak_libvips_init\n  Memcheck:Leak\n  match-leak-kinds: reachable\n  fun:malloc\n  ...\n  fun:vips__init\n}\n{\n  leak_libvips_thread_pool_new\n  Memcheck:Leak\n  match-leak-kinds: possible\n  fun:calloc\n  ...\n  fun:g_system_thread_new\n}\n{\n  leak_libvips_thread_pool_push\n  Memcheck:Leak\n  match-leak-kinds: possible\n  fun:calloc\n  ...\n  fun:g_thread_pool_push\n}\n{\n  leak_rsvg_static_data\n  Memcheck:Leak\n  match-leak-kinds: definite\n  fun:malloc\n  ...\n  fun:rsvg_handle_new_from_stream_sync\n}\n{\n  leak_rsvg_rsvg_rust_handle_new_from_gfile_sync\n  Memcheck:Leak\n  match-leak-kinds: definite\n  fun:malloc\n  ...\n  fun:rsvg_handle_new_from_gfile_sync\n}\n{\n  leak_rsvg_rust_handle_new_from_stream_sync\n  Memcheck:Leak\n  match-leak-kinds: possible\n  fun:malloc\n  ...\n  fun:xmlParseElement\n  ...\n  fun:rsvg_handle_new_from_stream_sync\n}\n{\n  leak_rsvg_rust_handle_new_from_gfile_sync\n  Memcheck:Leak\n  match-leak-kinds: possible\n  fun:malloc\n  ...\n  fun:xmlParseElement\n  ...\n  fun:rsvg_handle_new_from_gfile_sync\n}\n{\n  leak_rsvg_rust_280_bytes_static_regex\n  Memcheck:Leak\n  match-leak-kinds: possible\n  fun:malloc\n  ...\n  fun:rsvg_handle_get_dimensions_sub\n}\n\n# libuv warnings\n{\n  free_libuv\n  Memcheck:Free\n  ...\n  fun:uv__work_done\n}\n{\n  param_libuv_fs_work\n  Memcheck:Param\n  write(buf)\n  ...\n  fun:uv__fs_work\n}\n{\n  param_libuv_epoll_ctl\n  Memcheck:Param\n  epoll_ctl(event)\n  fun:epoll_ctl\n  fun:uv__io_poll\n}\n{\n  cond_libuv_work_done\n  Memcheck:Cond\n  ...\n  fun:uv__work_done\n}\n{\n  leak_libuv_FlushForegroundTasks\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node12NodePlatform28FlushForegroundTasksInternalEv\n}\n# nodejs warnings\n{\n  param_nodejs_write_buffer\n  Memcheck:Param\n  write(buf)\n  ...\n  obj:/usr/bin/nodejs\n}\n{\n  param_iojs_write_buffer\n  Memcheck:Param\n  write(buf)\n  ...\n  obj:/usr/bin/iojs\n}\n{\n  value_node_invoke_params\n  Memcheck:Value8\n  ...\n  fun:_ZN2v88internal12_GLOBAL__N_16InvokeEPNS0_7IsolateERKNS1_12InvokeParamsE\n}\n{\n  leak_nodejs_ImmutableAsciiSource_CreateFromLiteral\n  Memcheck:Leak\n  match-leak-kinds: definite\n  ...\n  fun:_ZN4node20ImmutableAsciiSource17CreateFromLiteralEPKcm\n}\n{\n  leak_nodejs_Buffer_New\n  Memcheck:Leak\n  match-leak-kinds: definite\n  ...\n  fun:_ZN4node6Buffer3NewERKN2v89ArgumentsE\n}\n{\n  leak_nodejs_Buffer_Replace\n   Memcheck:Leak\n   match-leak-kinds: indirect,possible\n   ...\n   fun:_ZN4node6Buffer7ReplaceEPcmPFvS1_PvES2_\n}\n{\n  leak_nodejs_SignalWrap_New\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node10SignalWrap3NewERKN2v89ArgumentsE\n}\n{\n  leak_nodejs_TTYWrap_New\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node7TTYWrap3NewERKN2v89ArgumentsE\n}\n{\n  leak_nodejs_ares_init_options\n  Memcheck:Leak\n  match-leak-kinds: reachable\n  fun:malloc\n  fun:strdup\n  ...\n  fun:ares_init_options\n}\n{\n  leak_nodejs_CreateEnvironment_Handle\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node17CreateEnvironmentEPN2v87IsolateEP9uv_loop_sNS0_6HandleINS0_7ContextEEEiPKPKciSB_\n}\n{\n  leak_nodejs_CreateEnvironment_Local\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node17CreateEnvironmentEPN2v87IsolateEP9uv_loop_sNS0_5LocalINS0_7ContextEEEiPKPKciSB_\n}\n{\n  leak_nodejs_CreateEnvironment_IsolateData\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node17CreateEnvironmentEPNS_11IsolateDataEN2v85LocalINS2_7ContextEEERKSt6vectorISsSaISsEESA_NS_16EnvironmentFlags5FlagsENS_8ThreadIdESt10unique_ptrINS_21InspectorParentHandleESt14default_deleteISF_EE\n}\n{\n  leak_nodejs_Environment_Start\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node11Environment5StartEiPKPKciS4_b\n}\n{\n  leak_nodejs_node9inspector5Agent5Start\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node9inspector5Agent5StartEPN2v88PlatformEPKcRKNS_12DebugOptionsE\n}\n{\n  leak_nodejs_node9inspector5Agent5Start_NodePlatform\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node9inspector5Agent5StartEPNS_12NodePlatformEPKcRKNS_12DebugOptionsE\n}\n{\n  leak_nodejs_node9inspector5Agent5StartERKSsRKNS\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node9inspector5Agent5StartERKSsRKNS_12DebugOptionsESt10shared_ptrINS_15ExclusiveAccessINS_8HostPortENS_9MutexBaseINS_16LibuvMutexTraitsEEEEEEb\n}\n{\n  leak_nodejs_node12NodePlatform_TracingController\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node12NodePlatformC1EiP9uv_loop_sPN2v817TracingControllerE\n}\n{\n  leak_nodejs_node11performance24MarkGarbageCollectionEnd\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node11performance24MarkGarbageCollectionEndEPN2v87IsolateENS1_6GCTypeENS1_15GCCallbackFlagsEPv\n}\n{\n  leak_nodejs_icu_getAvailableLocales\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN6icu_568Collator19getAvailableLocalesERi\n}\n{\n  leak_nodejs_thread_start\n  Memcheck:Leak\n  match-leak-kinds: possible\n  fun:calloc\n  fun:allocate_dtv\n  fun:_dl_allocate_tls\n  fun:allocate_stack\n  ...\n  fun:_ZN2v84base6Thread5StartEv\n}\n{\n  leak_nodejs_thread_TracingController\n  Memcheck:Leak\n  match-leak-kinds: possible\n  fun:calloc\n  fun:allocate_dtv\n  fun:_dl_allocate_tls\n  fun:allocate_stack\n  ...\n  fun:_ZN4node12NodePlatformC1EiPN2v817TracingControllerE\n}\n{\n  leak_nodejs_start_isolate_data\n  Memcheck:Leak\n  match-leak-kinds: possible\n  fun:_Znwm\n  ...\n  fun:_ZN4node5StartEPN2v87IsolateEPNS_11IsolateDataERKSt6vectorISsSaISsEES9_\n}\n{\n  leak_nodejs_runtime_stackguard_object_isolate\n  Memcheck:Leak\n  match-leak-kinds: possible\n  fun:_Znwm\n  ...\n  fun:_ZN2v88internal18Runtime_StackGuardEiPPNS0_6ObjectEPNS0_7IsolateE\n}\n{\n  leak_nodejs_builtin_handleapicall_object_isolate\n  Memcheck:Leak\n  match-leak-kinds: possible\n  fun:_Znwm\n  ...\n  fun:_ZN2v88internal21Builtin_HandleApiCallEiPPNS0_6ObjectEPNS0_7IsolateE\n}\n{\n  param_nodejs_delayed_task_scheduler\n  Memcheck:Param\n  epoll_ctl(event)\n  fun:epoll_ctl\n  fun:uv__io_poll\n  fun:uv_run\n  fun:_ZZN4node20BackgroundTaskRunner20DelayedTaskScheduler5StartEvENUlPvE_4_FUNES2_\n}\n{\n  param_nodejs_isolate_data\n  Memcheck:Param\n  epoll_ctl(event)\n  fun:epoll_ctl\n  fun:uv__io_poll\n  fun:uv_run\n  fun:_ZN4node5StartEPN2v87IsolateEPNS_11IsolateDataERKSt6vectorISsSaISsEES9_\n}\n{\n  param_nodejs_try_init_and_run_loop\n  Memcheck:Param\n  epoll_ctl(event)\n  fun:epoll_ctl\n  fun:uv__io_poll\n  fun:uv_run\n  fun:_ZN4node17SyncProcessRunner23TryInitializeAndRunLoopEN2v85LocalINS1_5ValueEEE\n}\n{\n  param_nodejs_run_exit_handlers\n  Memcheck:Param\n  epoll_ctl(event)\n  fun:epoll_ctl\n  fun:uv__io_poll\n  fun:uv_run\n  fun:_ZN4node7tracing5AgentD1Ev\n  fun:_ZN4node5._215D1Ev\n  fun:__run_exit_handlers\n}\n{\n  leak_nodejs_crypto_entropy_source\n  Memcheck:Leak\n  ...\n  fun:_ZN4node6crypto13EntropySourceEPhm\n}\n{\n  leak_nodejs_debug_options\n  Memcheck:Leak\n  ...\n  fun:_ZN4node9inspector5Agent5StartERKSsSt10shared_ptrINS_12DebugOptionsEEb\n}\n{\n  leak_nodejs_debug_host_port\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node9inspector5Agent5StartERKSsRKNS_12DebugOptionsESt10shared_ptrINS_8HostPortEEb\n}\n{\n  leak_nodejs_start\n  Memcheck:Leak\n  match-leak-kinds: definite\n  fun:_Znwm\n  fun:_ZN4node5StartEiPPc\n}\n{\n  leak_nodejs_start_background_task_runner\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN4node20BackgroundTaskRunnerC1Ei\n}\n{\n  leak_napi_module_register\n  Memcheck:Leak\n  match-leak-kinds: definite\n  ...\n  fun:napi_module_register\n  fun:call_init.part.0\n  fun:call_init\n  fun:_dl_init\n}\n{\n  leak_v8_FunctionCallbackInfo\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN2v88internal25FunctionCallbackArguments4CallEPFvRKNS_20FunctionCallbackInfoINS_5ValueEEEE\n}\n{\n  leak_v8_CallInterfaceDescriptorData\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN2v88internal27CallInterfaceDescriptorData10InitializeEiPNS0_8RegisterEPNS0_14RepresentationEPNS0_27PlatformInterfaceDescriptorE\n}\n{\n  leak_v8_Isolate_Init\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN2v88internal7Isolate4InitEPNS0_12DeserializerE\n}\n{\n  leak_v8_StoreDescriptor_Initialize\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN2v88internal15StoreDescriptor10InitializeEPNS0_27CallInterfaceDescriptorDataE\n}\n{\n  leak_v8_CodeStub_GetCode\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN2v88internal8CodeStub7GetCodeEv\n}\n{\n  leak_v8_CreateICUCollator\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN2v88internal12_GLOBAL__N_117CreateICUCollatorEPNS0_7IsolateERKN6icu_556LocaleENS0_6HandleINS0_8JSObjectEEE\n}\n{\n  leak_v8_CallInterfaceDescriptorData\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN2v88internal27CallInterfaceDescriptorData26InitializePlatformSpecificEiPNS0_8RegisterEPNS0_27PlatformInterfaceDescriptorE\n}\n{\n  leak_v8_InitializePlatformSpecific14\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN2v88internal14LoadDescriptor26InitializePlatformSpecificEPNS0_27CallInterfaceDescriptorDataE\n}\n{\n  leak_v8_InitializePlatformSpecific15\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN2v88internal15StoreDescriptor26InitializePlatformSpecificEPNS0_27CallInterfaceDescriptorDataE\n}\n{\n  leak_v8_Malloced\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN2v88internal8Malloced3NewEm\n}\n{\n  leak_v8_inspector10toString\n  Memcheck:Leak\n  match-leak-kinds: possible\n  ...\n  fun:_ZN12v8_inspector10toString16ERKNS_10StringViewE\n}\n{\n  cond_v8_Builtins_InterpreterEntryTrampoline\n  Memcheck:Cond\n  ...\n  fun:Builtins_InterpreterEntryTrampoline\n}\n{\n  cond_v8_ZN2v88internal18ArrayBufferSweeper9SweepFullEv\n  Memcheck:Cond\n  ...\n  fun:_ZN2v88internal18ArrayBufferSweeper9SweepFullEv\n}\n{\n  cond_v8_ZN4node11Environment27RunAndClearNativeImmediatesEb\n  Memcheck:Cond\n  ...\n  fun:_ZN4node11Environment27RunAndClearNativeImmediatesEb\n}\n{\n  cond_v8_ZN2v88internal18ArrayBufferSweeper10ReleaseAllEv\n  Memcheck:Cond\n  ...\n  fun:_ZN2v88internal18ArrayBufferSweeper10ReleaseAllEv\n}\n{\n  cond_v8_ZN2v88internal8compiler12PipelineImpl13OptimizeGraphEPNS1_7LinkageE\n  Memcheck:Cond\n  ...\n  fun:_ZN2v88internal8compiler12PipelineImpl13OptimizeGraphEPNS1_7LinkageE\n}\n{\n  cond_v8_ZN2v88internal4Heap20HasLowAllocationRateEv\n  Memcheck:Cond\n  ...\n  fun:_ZN2v88internal4Heap20HasLowAllocationRateEv\n}\n{\n  cond_v8_ZN2v88internal4Heap15RecomputeLimitsENS0_16GarbageCollectorENS_4base9TimeTicksE\n  Memcheck:Cond\n  ...\n  fun:_ZN2v88internal4Heap15RecomputeLimitsENS0_16GarbageCollectorENS_4base9TimeTicksE\n}\n{\n  cond_node_Builtins_JSEntry\n  Memcheck:Cond\n  ...\n  fun:Builtins_JSEntry\n  ...\n  fun:uv__poll_io_uring\n}\n{\n  cond_node_Builtins_TestEqualStrictHandler\n  Memcheck:Cond\n  fun:Builtins_TestEqualStrictHandler\n  ...\n  fun:uv__poll_io_uring\n}\n{\n  cond_node_Builtins_TestGreaterThanHandler\n  Memcheck:Cond\n  fun:Builtins_TestGreaterThanHandler\n  ...\n  fun:uv__poll_io_uring\n}\n{\n  cond_node_AfterStat\n  Memcheck:Cond\n  ...\n  fun:_ZN4node2fs9AfterStatEP7uv_fs_s\n  ...\n  fun:uv__poll_io_uring\n}\n{\n  cond_node_AfterMkdirp\n  Memcheck:Cond\n  fun:_ZN4node2fs11AfterMkdirpEP7uv_fs_s\n  fun:_ZN4node24MakeLibuvRequestCallbackI7uv_fs_sPFvPS1_EE7WrapperES2_\n  fun:_ZZZN4node2fs11MKDirpAsyncEP9uv_loop_sP7uv_fs_sPKciPFvS4_EENKUlS4_E_clES4_ENUlS4_E_4_FUNES4_\n  fun:uv__poll_io_uring\n}\n{\n  cond_v8_ArrayBufferSweeper_Finalize\n  Memcheck:Cond\n  fun:_ZN2v88internal18ArrayBufferSweeper8FinalizeEv\n}\n{\n  cond_v8_AdjustAmountOfExternalAllocatedMemory\n  Memcheck:Cond\n  fun:_ZN2v87Isolate37AdjustAmountOfExternalAllocatedMemoryEl\n}\n{\n  cond_v8_IncrementalMarkingLimitReached\n  Memcheck:Cond\n  fun:_ZN2v88internal4Heap30IncrementalMarkingLimitReachedEv\n}\n{\n  cond_v8_ShouldExpandOldGenerationOnSlowAllocation\n  Memcheck:Cond\n  fun:_ZN2v88internal4Heap41ShouldExpandOldGenerationOnSlowAllocationEPNS0_9LocalHeapENS0_16AllocationOriginE\n}\n{\n  cond_v8_ArrayBufferSweeper_SweepingJob_SweepListFull\n  Memcheck:Cond\n  fun:_ZN2v88internal18ArrayBufferSweeper11SweepingJob13SweepListFullEPNS0_15ArrayBufferListE\n}\n{\n  cond_v8_ArrayBufferSweeper_SweepingJob_SweepYoung\n  Memcheck:Cond\n  fun:_ZN2v88internal18ArrayBufferSweeper11SweepingJob10SweepYoungEv\n}\n{\n  cond_v8_StartIncrementalMarkingIfAllocationLimitIsReachedBackground\n  Memcheck:Cond\n  fun:_ZN2v88internal4Heap59StartIncrementalMarkingIfAllocationLimitIsReachedBackgroundEv\n}\n{\n  addr_v8_ZN2v88internal12_GLOBAL__N_119HandleApiCallHelperILb0EEENS0\n  Memcheck:Addr8\n  fun:strncmp\n  ...\n  fun:_ZZN4node7binding6DLOpenERKN2v820FunctionCallbackInfoINS1_5ValueEEEENKUlPNS0_4DLibEE_clES8_\n  fun:_ZN4node7binding6DLOpenERKN2v820FunctionCallbackInfoINS1_5ValueEEE\n  fun:_ZN2v88internal12_GLOBAL__N_119HandleApiCallHelperILb0EEENS0_11MaybeHandleINS0_6ObjectEEEPNS0_7IsolateENS0_6HandleINS0_10HeapObjectEEESA_NS8_INS0_20FunctionTemplateInfoEEENS8_IS4_EENS0_16BuiltinArgumentsE\n}\n{\n  addr_node_binding_dlopen_strncmp\n  Memcheck:Addr8\n  fun:strncmp\n  fun:is_dst\n  ...\n  fun:dlopen_implementation\n  ...\n  fun:_ZNSt17_Function_handlerIFbPN4node7binding4DLibEEZNS1_6DLOpenERKN2v820FunctionCallbackInfoINS5_5ValueEEEEUlS3_E_E9_M_invokeERKSt9_Any_dataOS3_\n}\n"
  },
  {
    "path": "test/types/sharp.test-d.ts",
    "content": "// biome-ignore-all lint/correctness/noUnusedFunctionParameters: types only test file\n// biome-ignore-all lint/correctness/noUnusedVariables: types only test file\n\nimport sharp = require('../../');\n\nimport { createReadStream, createWriteStream } from 'node:fs';\n\nconst input: Buffer = Buffer.alloc(0);\nconst readableStream: NodeJS.ReadableStream = createReadStream(input);\nconst writableStream: NodeJS.WritableStream = createWriteStream(input);\n\nsharp(input)\n  .extractChannel('green')\n  .toFile('input_green.jpg', (err, info) => {\n    // info.channels === 1\n    // input_green.jpg contains the green channel of the input image\n  });\n\nsharp('3-channel-rgb-input.png')\n  .bandbool(sharp.bool.and)\n  .toFile('1-channel-output.png', (err, info) => {\n    // The output will be a single channel image where each pixel `P = R & G & B`.\n    // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]`\n    // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`.\n  });\n\nsharp('input.png')\n  .rotate(180)\n  .resize(300)\n  .flatten({ background: '#ff6600' })\n  .composite([{ input: 'overlay.png', gravity: sharp.gravity.southeast, animated: false, failOn: 'warning' }])\n  .sharpen()\n  .withMetadata()\n  .withMetadata({\n    density: 96,\n    orientation: 8,\n    icc: 'some/path',\n    exif: { IFD0: { Copyright: 'Wernham Hogg' } },\n  })\n  .webp({\n    quality: 90,\n  })\n  .toBuffer()\n  .then((outputBuffer: Buffer) => {\n    // outputBuffer contains upside down, 300px wide, alpha channel flattened\n    // onto orange background, composited with overlay.png with SE gravity,\n    // sharpened, with metadata, 90% quality WebP image data. Phew!\n  });\n\nsharp('input.png')\n  .keepMetadata()\n  .toFile('output.png', (err, info) => {\n    // output.png is an image containing input.png along with all metadata(EXIF, ICC, XMP, IPTC) from input.png\n  })\n\nsharp('input.jpg')\n  .resize(300, 200)\n  .toFile('output.jpg', (err: Error) => {\n    // output.jpg is a 300 pixels wide and 200 pixels high image\n    // containing a scaled and cropped version of input.jpg\n  });\n\nsharp('input.jpg').resize({ width: 300 }).blur(false).blur(true).toFile('output.jpg');\n\nsharp().blur();\nsharp().blur(1);\nsharp().blur({ sigma: 1 });\nsharp().blur({ sigma: 1, precision: 'approximate' });\nsharp().blur({ sigma: 1, minAmplitude: 0.8 });\n\nsharp({\n  create: {\n    width: 300,\n    height: 200,\n    channels: 4,\n    background: { r: 255, g: 0, b: 0, alpha: 128 },\n  },\n})\n  .png()\n  .toBuffer();\n\nlet transformer = sharp()\n  .resize(300)\n  .on('info', (info: sharp.OutputInfo) => {\n    console.log(`Image height is ${info.height}`);\n  });\nreadableStream.pipe(transformer).pipe(writableStream);\n\nconsole.log(sharp.format);\nconsole.log(sharp.versions);\n\nsharp.queue.on('change', (queueLength: number) => {\n  console.log(`Queue contains ${queueLength} task(s)`);\n});\n\nlet pipeline: sharp.Sharp = sharp().rotate();\npipeline.clone().resize(800, 600).pipe(writableStream);\npipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(writableStream);\nreadableStream.pipe(pipeline);\n// firstWritableStream receives auto-rotated, resized readableStream\n// secondWritableStream receives auto-rotated, extracted region of readableStream\n\nconst image: sharp.Sharp = sharp(input);\nimage\n  .metadata()\n  .then<Buffer | undefined>((metadata: sharp.Metadata) => {\n    if (metadata.width) {\n      return image\n        .resize(Math.round(metadata.width / 2))\n        .webp()\n        .toBuffer();\n    }\n  })\n  .then((data) => {\n    // data contains a WebP image half the width and height of the original JPEG\n  });\n\npipeline = sharp()\n  .rotate()\n  .resize(undefined, 200)\n  .toBuffer((err: Error, outputBuffer: Buffer, info: sharp.OutputInfo) => {\n    // outputBuffer contains 200px high JPEG image data,\n    // auto-rotated using EXIF Orientation tag\n    // info.width and info.height contain the dimensions of the resized image\n  });\nreadableStream.pipe(pipeline);\n\nsharp(input)\n  .extract({ left: 0, top: 0, width: 100, height: 100 })\n  .toFile('output', (err: Error) => {\n    // Extract a region of the input image, saving in the same format.\n  });\n\nsharp(input)\n  .extract({ left: 0, top: 0, width: 100, height: 100 })\n  .resize(200, 200)\n  .extract({ left: 0, top: 0, width: 100, height: 100 })\n  .toFile('output', (err: Error) => {\n    // Extract a region, resize, then extract from the resized image\n  });\n\n// Resize to 140 pixels wide, then add 10 transparent pixels\n// to the top, left and right edges and 20 to the bottom edge\nsharp(input)\n  .resize(140, null, { background: { r: 0, g: 0, b: 0, alpha: 0 } })\n  .extend({ top: 10, bottom: 20, left: 10, right: 10 });\n\nsharp(input)\n  .convolve({\n    width: 3,\n    height: 3,\n    kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1],\n  })\n  .raw()\n  .toBuffer((err: Error, data: Buffer, info: sharp.OutputInfo) => {\n    // data contains the raw pixel data representing the convolution\n    // of the input image with the horizontal Sobel operator\n  });\n\nsharp('input.tiff')\n  .png()\n  .tile({\n    size: 512,\n  })\n  .toFile('output.dz', (err: Error, info: sharp.OutputInfo) => {\n    // output.dzi is the Deep Zoom XML definition\n    // output_files contains 512x512 tiles grouped by zoom level\n  });\n\nsharp('input.tiff')\n  .png()\n  .tile({\n    size: 512,\n    center: true,\n    layout: 'iiif3',\n    id: 'https://my.image.host/iiif',\n  })\n  .toFile('output');\n\nsharp(input)\n  .resize(200, 300, {\n    fit: 'contain',\n    position: 'north',\n    kernel: sharp.kernel.lanczos2,\n    background: 'white',\n  })\n  .toFile('output.tiff')\n  .then(() => {\n    // output.tiff is a 200 pixels wide and 300 pixels high image\n    // containing a lanczos2/nohalo scaled version, embedded on a white canvas,\n    // of the image data in inputBuffer\n  });\n\nsharp(input).resize({ kernel: 'mks2013' });\n\ntransformer = sharp()\n  .resize(200, 200, {\n    fit: 'cover',\n    position: sharp.strategy.entropy,\n  })\n  .on('error', (err: Error) => {\n    console.log(err);\n  });\n// Read image data from readableStream\n// Write 200px square auto-cropped image data to writableStream\nreadableStream.pipe(transformer).pipe(writableStream);\n\nsharp('input.gif')\n  .resize(200, 300, {\n    fit: 'contain',\n    position: 'north',\n    background: { r: 0, g: 0, b: 0, alpha: 0 },\n  })\n  .toFormat(sharp.format.webp)\n  .toBuffer((err: Error, outputBuffer: Buffer) => {\n    if (err) {\n      throw err;\n    }\n    // outputBuffer contains WebP image data of a 200 pixels wide and 300 pixels high\n    // containing a scaled version, embedded on a transparent canvas, of input.gif\n  });\n\nsharp(input)\n  .resize(200, 200, { fit: 'inside' })\n  .toFormat('jpeg')\n  .toBuffer()\n  .then((outputBuffer: Buffer) => {\n    // outputBuffer contains JPEG image data no wider than 200 pixels and no higher\n    // than 200 pixels regardless of the inputBuffer image dimensions\n  });\n\nsharp(input)\n  .resize(100, 100)\n  .toFormat('jpg')\n  .toBuffer({ resolveWithObject: false })\n  .then((outputBuffer: Buffer) => {\n    // Resolves with a Buffer object when resolveWithObject is false\n  });\n\nsharp(input)\n  .resize(100, 100)\n  .toBuffer({ resolveWithObject: true })\n  .then((object: { data: Buffer; info: sharp.OutputInfo }) => {\n    // Resolve with an object containing data Buffer and an OutputInfo object\n    // when resolveWithObject is true\n  });\n\nsharp(input)\n  .resize(640, 480, { withoutEnlargement: true })\n  .toFormat('jpeg')\n  .toBuffer()\n  .then((outputBuffer: Buffer) => {\n    // outputBuffer contains JPEG image data no larger than the input\n  });\n\nsharp(input)\n  .resize(640, 480, { withoutReduction: true })\n  .toFormat('jpeg')\n  .toBuffer()\n  .then((outputBuffer: Buffer) => {\n    // outputBuffer contains JPEG image data no smaller than the input\n  });\n\n// Output to tif\nsharp(input)\n  .resize(100, 100)\n  .toFormat('tif')\n  .toFormat('tiff')\n  .toFormat(sharp.format.tif)\n  .toFormat(sharp.format.tiff)\n  .toBuffer();\n\nconst stats = sharp.cache();\n\nsharp.cache({ items: 200 });\nsharp.cache({ files: 0 });\nsharp.cache(false);\n\nconst threads = sharp.concurrency(); // 4\nsharp.concurrency(2); // 2\nsharp.concurrency(0); // 4\n\nconst counters = sharp.counters(); // { queue: 2, process: 4 }\n\nlet simd: boolean = sharp.simd();\n// simd is `true` if SIMD is currently enabled\n\nsimd = sharp.simd(true);\n// attempts to enable the use of SIMD, returning true if available\n\nconst vipsVersion: string = sharp.versions.vips;\n\nif (sharp.versions.cairo) {\n  const cairoVersion: string = sharp.versions.cairo;\n}\n\nsharp('input.gif')\n  .linear(1)\n  .linear(1, 0)\n  .linear(null, 0)\n  .linear([0.25, 0.5, 0.75], [150, 100, 50])\n\n  .recomb([\n    [0.3588, 0.7044, 0.1368],\n    [0.299, 0.587, 0.114],\n    [0.2392, 0.4696, 0.0912],\n  ])\n\n  .recomb([\n    [1,0,0,0],\n    [0,1,0,0],\n    [0,0,1,0],\n    [0,0,0,1],\n  ])\n\n  .modulate({ brightness: 2 })\n  .modulate({ hue: 180 })\n  .modulate({ lightness: 10 })\n  .modulate({ brightness: 0.5, saturation: 0.5, hue: 90 });\n\n// From https://sharp.pixelplumbing.com/api-output#examples-9\n// Extract raw RGB pixel data from JPEG input\nsharp('input.jpg')\n  .raw({ depth: 'ushort' })\n  .toBuffer({ resolveWithObject: true })\n  .then(({ data, info }) => {\n    console.log(data);\n    console.log(info);\n  });\n\nsharp(input).jpeg().jpeg({}).jpeg({\n  progressive: false,\n  chromaSubsampling: '4:4:4',\n  trellisQuantisation: false,\n  overshootDeringing: false,\n  optimiseScans: false,\n  optimizeScans: false,\n  optimiseCoding: false,\n  optimizeCoding: false,\n  quantisationTable: 10,\n  quantizationTable: 10,\n  mozjpeg: false,\n  quality: 10,\n  force: false,\n});\n\nsharp(input).png().png({}).png({\n  progressive: false,\n  compressionLevel: 10,\n  adaptiveFiltering: false,\n  force: false,\n  quality: 10,\n  palette: false,\n  colours: 10,\n  colors: 10,\n  dither: 10,\n});\n\nsharp(input)\n  .avif()\n  .avif({})\n  .avif({ quality: 50, lossless: false, effort: 5, chromaSubsampling: '4:2:0' })\n  .heif()\n  .heif({})\n  .heif({ quality: 50, compression: 'hevc', lossless: false, effort: 5, chromaSubsampling: '4:2:0' })\n  .toBuffer({ resolveWithObject: true })\n  .then(({ data, info }) => {\n    console.log(data);\n    console.log(info);\n  });\n\nsharp(input)\n  .gif()\n  .gif({})\n  .gif({ loop: 0, delay: [], force: true })\n  .gif({ delay: 30 })\n  .gif({ reuse: true })\n  .gif({ reuse: false })\n  .gif({ progressive: true })\n  .gif({ progressive: false })\n  .gif({ keepDuplicateFrames: true })\n  .gif({ keepDuplicateFrames: false })\n  .toBuffer({ resolveWithObject: true })\n  .then(({ data, info }) => {\n    console.log(data);\n    console.log(info);\n  });\n\nsharp(input)\n  .tiff({ compression: 'packbits' })\n  .toBuffer({ resolveWithObject: true })\n  .then(({ data, info }) => {\n    console.log(data);\n    console.log(info);\n  });\n\nsharp('input.jpg')\n  .stats()\n  .then(stats => {\n    const {\n      sharpness,\n      dominant: { r, g, b },\n    } = stats;\n    console.log(sharpness);\n    console.log(`${r}, ${g}, ${b}`);\n  });\n\n// From https://sharp.pixelplumbing.com/api-output#examples-9\n// Extract alpha channel as raw pixel data from PNG input\nsharp('input.png').ensureAlpha().ensureAlpha(0).extractChannel(3).toColourspace('b-w').raw().toBuffer();\n\n// From https://sharp.pixelplumbing.com/api-constructor#examples-4\n// Convert an animated GIF to an animated WebP\nsharp('in.gif', { animated: true }).toFile('out.webp');\n\n// From https://github.com/lovell/sharp/issues/2701\n// Type support for limitInputPixels\nsharp({\n  create: {\n    background: 'red',\n    channels: 4,\n    height: 25000,\n    width: 25000,\n    pageHeight: 1000,\n  },\n  limitInputPixels: false,\n})\n  .toFormat('png')\n  .toBuffer()\n  .then(largeImage => sharp(input).composite([{ input: largeImage, limitInputPixels: false }]));\n\n// Taken from API documentation at\n// https://sharp.pixelplumbing.com/api-operation#clahe\n// introduced\nsharp('input.jpg').clahe({ width: 10, height: 10 }).toFile('output.jpg');\n\nsharp('input.jpg').clahe({ width: 10, height: 10, maxSlope: 5 }).toFile('outfile.jpg');\n\n// Support `unlimited` input option\nsharp('input.png', { unlimited: true }).resize(320, 240).toFile('outfile.png');\n\n// Support creating with noise\nsharp({\n  create: {\n    background: 'red',\n    channels: 4,\n    height: 100,\n    width: 100,\n    noise: {\n      type: 'gaussian',\n      mean: 128,\n      sigma: 30,\n    },\n  },\n})\n  .png()\n  .toFile('output.png');\n\nsharp(new Uint8Array(input.buffer)).toFile('output.jpg');\n\n// Support for negate options\nsharp('input.png').negate({ alpha: false }).toFile('output.png');\n\n// From https://github.com/lovell/sharp/pull/2704\n// Type support for pipelineColourspace\nsharp(input)\n  .pipelineColourspace('rgb16')\n  .resize(320, 240)\n  .gamma()\n  .toColourspace('srgb') // this is the default, but included here for clarity\n  .toBuffer();\n\n// From https://github.com/lovell/sharp/pull/1439\n// Second parameter to gamma operation for different output gamma\nsharp(input)\n  .resize(129, 111)\n  .gamma(2.2, 3.0)\n  .toBuffer(err => {\n    if (err) throw err;\n  });\n\n// Support for raw depth specification\nsharp('16bpc.png')\n  .toColourspace('rgb16')\n  .raw({ depth: 'ushort' })\n  .toBuffer((error, data, { width, height, channels, size }) => {\n    console.log((size / width / height / channels) * 8);\n    console.log(new Uint16Array(data.buffer));\n  });\n\n// Output channels are constrained from 1-4, can be used as raw input\nsharp(input)\n  .toBuffer({ resolveWithObject: true })\n  .then(result => {\n    const newImg = sharp(result.data, {\n      raw: {\n        channels: result.info.channels,\n        width: result.info.width,\n        height: result.info.height,\n      },\n    });\n\n    return newImg.toBuffer();\n  });\n\n// Support for specifying a timeout\nsharp('someImage.png').timeout({ seconds: 30 }).resize(300, 300).toBuffer();\n\n// Support for `effort` in different formats\nsharp('input.tiff').png({ effort: 9 }).toFile('out.png');\nsharp('input.tiff').webp({ effort: 9 }).toFile('out.webp');\nsharp('input.tiff').avif({ effort: 9 }).toFile('out.avif');\nsharp('input.tiff').heif({ effort: 9 }).toFile('out.heif');\nsharp('input.tiff').gif({ effort: 9 }).toFile('out.gif');\n\n// Support for `colors`/`colours` for gif output\nsharp('input.gif').gif({ colors: 16 }).toFile('out.gif');\nsharp('input.gif').gif({ colours: 16 }).toFile('out.gif');\n\n// Support for `dither` for gif/png output\nsharp('input.gif').gif({ dither: 0.5 }).toFile('out.gif');\nsharp('input.gif').png({ dither: 0.5 }).toFile('out.png');\n\n// Support for `interFrameMaxError` for gif output\nsharp('input.gif').gif({ interFrameMaxError: 0 }).toFile('out.gif');\n\n// Support for `interPaletteMaxError` for gif output\nsharp('input.gif').gif({ interPaletteMaxError: 0 }).toFile('out.gif');\n\n// Support for `resolutionUnit` for tiff output\nsharp('input.tiff').tiff({ resolutionUnit: 'cm' }).toFile('out.tiff');\n\n// Support for `jp2` output with different options\nsharp('input.tiff').jp2().toFile('out.jp2');\nsharp('input.tiff').jp2({ quality: 50 }).toFile('out.jp2');\nsharp('input.tiff').jp2({ lossless: true }).toFile('out.jp2');\nsharp('input.tiff').jp2({ tileWidth: 128, tileHeight: 128 }).toFile('out.jp2');\nsharp('input.tiff').jp2({ chromaSubsampling: '4:2:0' }).toFile('out.jp2');\n\n// Support for `jxl` output with different options\nsharp('input.tiff').jxl().toFile('out.jxl');\nsharp('input.tiff').jxl({ distance: 15.0 }).toFile('out.jxl');\nsharp('input.tiff').jxl({ quality: 50 }).toFile('out.jxl');\nsharp('input.tiff').jxl({ decodingTier: 4 }).toFile('out.jxl');\nsharp('input.tiff').jxl({ lossless: true }).toFile('out.jxl');\nsharp('input.tiff').jxl({ effort: 7 }).toFile('out.jxl');\n\n// Support `minSize` and `mixed` webp options\nsharp('input.tiff').webp({ minSize: true, mixed: true }).toFile('out.gif');\n\n// 'failOn' input param\nsharp('input.tiff', { failOn: 'none' });\nsharp('input.tiff', { failOn: 'truncated' });\nsharp('input.tiff', { failOn: 'error' });\nsharp('input.tiff', { failOn: 'warning' });\n\n// Sharpen operation taking an object instead of three params\nsharp('input.tiff').sharpen().toBuffer();\nsharp('input.tiff').sharpen({ sigma: 2 }).toBuffer();\nsharp('input.tiff')\n  .sharpen({\n    sigma: 2,\n    m1: 0,\n    m2: 3,\n    x1: 3,\n    y2: 15,\n    y3: 15,\n  })\n  .toBuffer();\n\n// Affine operator + interpolator hash\nsharp().affine(\n  [\n    [1, 0.3],\n    [0.1, 0.7],\n  ],\n  {\n    background: 'white',\n    interpolator: sharp.interpolators.nohalo,\n  },\n);\n\nsharp().affine([1, 1, 1, 1], {\n  background: 'white',\n  idx: 0,\n  idy: 0,\n  odx: 0,\n  ody: 0,\n});\n\nconst bicubic: string = sharp.interpolators.bicubic;\nconst bilinear: string = sharp.interpolators.bilinear;\nconst locallyBoundedBicubic: string = sharp.interpolators.locallyBoundedBicubic;\nconst nearest: string = sharp.interpolators.nearest;\nconst nohalo: string = sharp.interpolators.nohalo;\nconst vertexSplitQuadraticBasisSpline: string = sharp.interpolators.vertexSplitQuadraticBasisSpline;\n\n// Triming\nsharp(input).trim({ background: '#000' }).toBuffer();\nsharp(input).trim({ threshold: 10, lineArt: true }).toBuffer();\nsharp(input).trim({ background: '#bf1942', threshold: 30 }).toBuffer();\n\n// Text input\nsharp({\n  text: {\n    text: 'Hello world',\n    align: 'centre',\n    dpi: 72,\n    font: 'Arial',\n    fontfile: 'path/to/arial.ttf',\n    height: 500,\n    width: 500,\n    rgba: true,\n    justify: true,\n    spacing: 10,\n    wrap: 'word-char',\n  },\n})\n  .png()\n  .toBuffer({ resolveWithObject: true })\n  .then(out => {\n    console.log(out.info.textAutofitDpi);\n  });\n\n// Text composite\nsharp('input.png').composite([\n  {\n    input: {\n      text: {\n        text: 'Okay then',\n        font: 'Comic Sans',\n      },\n    },\n  },\n]);\n\n// From https://github.com/lovell/sharp/pull/1835\nsharp('input.png').composite([\n  {\n    input: {\n      text: {\n        text: 'Okay then',\n        font: 'Comic Sans',\n      },\n    },\n    blend: 'color-burn',\n    top: 0,\n    left: 0,\n    premultiplied: true,\n  },\n]);\n\n// https://github.com/lovell/sharp/pull/402\n(['fs', 'zip'] as const).forEach(container => {\n  sharp().tile({ container });\n});\n\n// From https://github.com/lovell/sharp/issues/2238\nsharp('input.png').tile({\n  basename: 'output.dz.tiles',\n});\n\n// https://github.com/lovell/sharp/issues/3669\nsharp(input).composite([\n  {\n    raw: {\n      width: 1,\n      height: 1,\n      channels: 1,\n      premultiplied: false,\n    },\n    sequentialRead: false,\n    unlimited: true,\n  }\n]);\n\n// Support for webp preset in types\n// https://github.com/lovell/sharp/issues/3747\nsharp('input.tiff').webp({ preset: 'photo' }).toFile('out.webp');\nsharp('input.tiff').webp({ preset: 'picture' }).toFile('out.webp');\nsharp('input.tiff').webp({ preset: 'icon' }).toFile('out.webp');\nsharp('input.tiff').webp({ preset: 'drawing' }).toFile('out.webp');\nsharp('input.tiff').webp({ preset: 'text' }).toFile('out.webp');\nsharp('input.tiff').webp({ preset: 'default' }).toFile('out.webp');\n\nsharp(input)\n  .keepExif()\n  .withExif({\n    IFD0: {\n      k1: 'v1'\n    }\n  })\n  .withExifMerge({\n    IFD1: {\n      k2: 'v2'\n    }\n  })\n  .keepXmp()\n  .withXmp('test')\n  .keepIccProfile()\n  .withIccProfile('filename')\n  .withIccProfile('filename', { attach: false });\n\n// Added missing types for OverlayOptions\n// https://github.com/lovell/sharp/pull/4048\nsharp(input).composite([\n  {\n    input: 'image.gif', \n    animated: true, \n    limitInputPixels: 536805378, \n    density: 144, \n    failOn: \"warning\",\n    autoOrient: true\n  }\n])\nsharp(input).composite([\n  {\n    input: 'image.png',  \n    animated: false,\n    limitInputPixels: 178935126, \n    density: 72, \n    failOn: \"truncated\"\n  }\n])\n\n// Support format-specific input options\nconst colour: sharp.Colour = '#fff';\nconst color: sharp.Color = '#fff';\nsharp({ pdf: { background: colour } });\nsharp({ pdf: { background: color } });\nsharp({ pdfBackground: colour }); // Deprecated\nsharp({ pdfBackground: color }); // Deprecated\nsharp({ tiff: { subifd: 3 } });\nsharp({ subifd: 3 }); // Deprecated\nsharp({ openSlide: { level: 0 } });\nsharp({ level: 0 }); // Deprecated\nsharp({ jp2: { oneshot: true } });\nsharp({ jp2: { oneshot: false } });\nsharp({ svg: { stylesheet: 'test' }});\nsharp({ svg: { highBitdepth: true }});\nsharp({ svg: { highBitdepth: false }});\n\n// Raw input options\nconst raw: sharp.Raw = { width: 1, height: 1, channels: 3 };\nsharp({ raw });\nsharp({ raw: { ...raw, premultiplied: true } });\nsharp({ raw: { ...raw, premultiplied: false } });\nsharp({ raw: { ...raw, pageHeight: 1 } });\n\nsharp({ autoOrient: true });\nsharp({ autoOrient: false });\nsharp().autoOrient();\n\nsharp([input, input]);\nsharp([input, input], {\n  join: {\n    animated: true\n  }\n});\nsharp([input, input], {\n  join: {\n    across: 2,\n    shim: 5,\n    background: colour,\n    halign: 'centre',\n    valign: 'bottom'\n  }\n});\n\nsharp().erode();\nsharp().erode(1);\nsharp().dilate();\nsharp().dilate(1);\n"
  },
  {
    "path": "test/types/tsconfig.json",
    "content": "{\n  \"module\": \"commonjs\",\n  \"strict\": true\n}\n"
  },
  {
    "path": "test/unit/affine.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Affine transform', () => {\n  describe('Invalid input', () => {\n    it('Missing matrix', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg)\n          .affine();\n      });\n    });\n    it('Invalid 1d matrix', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg)\n          .affine(['123', 123, 123, 123]);\n      });\n    });\n    it('Invalid 2d matrix', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg)\n          .affine([[123, 123], [null, 123]]);\n      });\n    });\n    it('Invalid options parameter type', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg)\n          .affine([[1, 0], [0, 1]], 'invalid options type');\n      });\n    });\n    it('Invalid background color', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg)\n          .affine([4, 4, 4, 4], { background: 'not a color' });\n      });\n    });\n    it('Invalid idx offset type', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg)\n          .affine([[4, 4], [4, 4]], { idx: 'invalid idx type' });\n      });\n    });\n    it('Invalid idy offset type', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg)\n          .affine([4, 4, 4, 4], { idy: 'invalid idy type' });\n      });\n    });\n    it('Invalid odx offset type', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg)\n          .affine([[4, 4], [4, 4]], { odx: 'invalid odx type' });\n      });\n    });\n    it('Invalid ody offset type', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg)\n          .affine([[4, 4], [4, 4]], { ody: 'invalid ody type' });\n      });\n    });\n    it('Invalid interpolator', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg)\n          .affine([[4, 4], [4, 4]], { interpolator: 'cubic' });\n      });\n    });\n  });\n  it('Applies identity matrix', done => {\n    const input = fixtures.inputJpg;\n    sharp(input)\n      .affine([[1, 0], [0, 1]])\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(input, data, done);\n      });\n  });\n  it('Applies resize affine matrix', done => {\n    const input = fixtures.inputJpg;\n    const inputWidth = 2725;\n    const inputHeight = 2225;\n    sharp(input)\n      .affine([[0.2, 0], [0, 1.5]])\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        fixtures.assertSimilar(input, data, done);\n        assert.strictEqual(info.width, Math.ceil(inputWidth * 0.2));\n        assert.strictEqual(info.height, Math.ceil(inputHeight * 1.5));\n      });\n  });\n  it('Resizes and applies affine transform', done => {\n    const input = fixtures.inputJpg;\n    sharp(input)\n      .resize(500, 500)\n      .affine([[0.5, 1], [1, 0.5]])\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(data, fixtures.expected('affine-resize-expected.jpg'), done);\n      });\n  });\n  it('Extracts and applies affine transform', done => {\n    sharp(fixtures.inputJpg)\n      .extract({ left: 300, top: 300, width: 600, height: 600 })\n      .affine([0.3, 0, -0.5, 0.3])\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(data, fixtures.expected('affine-extract-expected.jpg'), done);\n      });\n  });\n  it('Rotates and applies affine transform', done => {\n    sharp(fixtures.inputJpg320x240)\n      .rotate(90)\n      .affine([[-1.2, 0], [0, -1.2]])\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(data, fixtures.expected('affine-rotate-expected.jpg'), done);\n      });\n  });\n  it('Extracts, rotates and applies affine transform', done => {\n    sharp(fixtures.inputJpg)\n      .extract({ left: 1000, top: 1000, width: 200, height: 200 })\n      .rotate(45, { background: 'blue' })\n      .affine([[2, 1], [2, -0.5]], { background: 'red' })\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('affine-extract-rotate-expected.jpg'), data, done);\n      });\n  });\n  it('Applies affine transform with background color', done => {\n    sharp(fixtures.inputJpg320x240)\n      .rotate(180)\n      .affine([[-1.5, 1.2], [-1, 1]], { background: 'red' })\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('affine-background-expected.jpg'), data, done);\n      });\n  });\n  it('Applies affine transform with background color and output offsets', done => {\n    sharp(fixtures.inputJpg320x240)\n      .rotate(180)\n      .affine([[-2, 1.5], [-1, 2]], { background: 'blue', odx: 40, ody: -100 })\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('affine-background-output-offsets-expected.jpg'), data, done);\n      });\n  });\n  it('Applies affine transform with background color and all offsets', done => {\n    sharp(fixtures.inputJpg320x240)\n      .rotate(180)\n      .affine([[-1.2, 1.8], [-1, 2]], { background: 'yellow', idx: 10, idy: -40, odx: 10, ody: -50 })\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('affine-background-all-offsets-expected.jpg'), data, done);\n      });\n  });\n\n  it('Animated image rejects', () =>\n    assert.rejects(() => sharp(fixtures.inputGifAnimated, { animated: true })\n      .affine([1, 1, 1, 1])\n      .toBuffer(),\n    /Affine is not supported for multi-page images/\n    )\n  );\n\n  describe('Interpolations', () => {\n    const input = fixtures.inputJpg320x240;\n    const inputWidth = 320;\n    const inputHeight = 240;\n    for (const interp in sharp.interpolators) {\n      it(`Performs 2x upscale with ${interp} interpolation`, done => {\n        sharp(input)\n          .affine([[2, 0], [0, 2]], { interpolator: sharp.interpolators[interp] })\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            assert.strictEqual(info.width, Math.ceil(inputWidth * 2));\n            assert.strictEqual(info.height, Math.ceil(inputHeight * 2));\n            fixtures.assertSimilar(fixtures.expected(`affine-${sharp.interpolators[interp]}-2x-upscale-expected.jpg`), data, done);\n          });\n      });\n    }\n  });\n});\n"
  },
  {
    "path": "test/unit/alpha.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\nconst fixtures = require('../fixtures');\nconst sharp = require('../../');\n\ndescribe('Alpha transparency', () => {\n  it('Flatten to black', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency)\n      .flatten()\n      .resize(400, 300)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(400, info.width);\n        assert.strictEqual(300, info.height);\n        fixtures.assertSimilar(fixtures.expected('flatten-black.jpg'), data, done);\n      });\n  });\n\n  it('Flatten to RGB orange', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency)\n      .resize(400, 300)\n      .flatten({\n        background: { r: 255, g: 102, b: 0 }\n      })\n      .jpeg({ chromaSubsampling: '4:4:4' })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(400, info.width);\n        assert.strictEqual(300, info.height);\n        fixtures.assertSimilar(fixtures.expected('flatten-orange.jpg'), data, done);\n      });\n  });\n\n  it('Flatten to CSS/hex orange', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency)\n      .resize(400, 300)\n      .flatten({ background: '#ff6600' })\n      .jpeg({ chromaSubsampling: '4:4:4' })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(400, info.width);\n        assert.strictEqual(300, info.height);\n        fixtures.assertSimilar(fixtures.expected('flatten-orange.jpg'), data, done);\n      });\n  });\n\n  it('Flatten 16-bit PNG with transparency to orange', (_t, done) => {\n    const output = fixtures.path('output.flatten-rgb16-orange.jpg');\n    sharp(fixtures.inputPngWithTransparency16bit)\n      .flatten({\n        background: { r: 255, g: 102, b: 0 }\n      })\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, info.size > 0);\n        assert.strictEqual(32, info.width);\n        assert.strictEqual(32, info.height);\n        fixtures.assertMaxColourDistance(output, fixtures.expected('flatten-rgb16-orange.jpg'), 10);\n        done();\n      });\n  });\n\n  it('Do not flatten', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency)\n      .flatten(false)\n      .toBuffer((err, _data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(4, info.channels);\n        done();\n      });\n  });\n\n  it('Ignored for JPEG', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .flatten({ background: '#ff0000' })\n      .toBuffer((err, _data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(3, info.channels);\n        done();\n      });\n  });\n\n  it('Flatten with options but without colour does not throw', () => {\n    assert.doesNotThrow(() => {\n      sharp().flatten({});\n    });\n  });\n\n  it('Flatten to invalid colour throws', () => {\n    assert.throws(() => {\n      sharp().flatten({ background: 1 });\n    });\n  });\n\n  it('Enlargement with non-nearest neighbor interpolation shouldn’t cause dark edges', () => {\n    const base = 'alpha-premultiply-enlargement-2048x1536-paper.png';\n    const actual = fixtures.path(`output.${base}`);\n    const expected = fixtures.expected(base);\n    return sharp(fixtures.inputPngAlphaPremultiplicationSmall)\n      .resize(2048, 1536)\n      .toFile(actual)\n      .then(() => {\n        fixtures.assertMaxColourDistance(actual, expected, 102);\n      });\n  });\n\n  it('Reduction with non-nearest neighbor interpolation shouldn’t cause dark edges', () => {\n    const base = 'alpha-premultiply-reduction-1024x768-paper.png';\n    const actual = fixtures.path(`output.${base}`);\n    const expected = fixtures.expected(base);\n    return sharp(fixtures.inputPngAlphaPremultiplicationLarge)\n      .resize(1024, 768)\n      .toFile(actual)\n      .then(() => {\n        fixtures.assertMaxColourDistance(actual, expected, 102);\n      });\n  });\n\n  it('Removes alpha from fixtures with transparency, ignores those without', () => Promise.all([\n      fixtures.inputPngWithTransparency,\n      fixtures.inputPngWithTransparency16bit,\n      fixtures.inputWebPWithTransparency,\n      fixtures.inputJpg,\n      fixtures.inputPng,\n      fixtures.inputWebP\n    ].map((input) => sharp(input)\n        .resize(10)\n        .removeAlpha()\n        .toBuffer({ resolveWithObject: true })\n        .then((result) => {\n          assert.strictEqual(3, result.info.channels);\n        }))));\n\n  it('Ensures alpha from fixtures without transparency, ignores those with', () => Promise.all([\n      fixtures.inputPngWithTransparency,\n      fixtures.inputPngWithTransparency16bit,\n      fixtures.inputWebPWithTransparency,\n      fixtures.inputJpg,\n      fixtures.inputPng,\n      fixtures.inputWebP\n    ].map((input) => sharp(input)\n        .resize(10)\n        .ensureAlpha()\n        .png()\n        .toBuffer({ resolveWithObject: true })\n        .then((result) => {\n          assert.strictEqual(4, result.info.channels);\n        }))));\n\n  it('Valid ensureAlpha value used for alpha channel', async () => {\n    const background = { r: 255, g: 0, b: 0 };\n    const [r, g, b, alpha] = await sharp({\n      create: {\n        width: 8,\n        height: 8,\n        channels: 3,\n        background\n      }\n    })\n      .ensureAlpha(0.5)\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual({ r, g, b, alpha }, { ...background, alpha: 127 });\n  });\n\n  it('Invalid ensureAlpha value throws', async () => {\n    assert.throws(() => {\n      sharp().ensureAlpha('fail');\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/avif.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst { inputAvif, inputJpg, inputGifAnimated } = require('../fixtures');\n\ndescribe('AVIF', () => {\n  it('called without options does not throw an error', () => {\n    assert.doesNotThrow(() => {\n      sharp().avif();\n    });\n  });\n\n  it('can convert AVIF to JPEG', async () => {\n    const data = await sharp(inputAvif)\n      .resize(32)\n      .jpeg()\n      .toBuffer();\n    const { size, ...metadata } = await sharp(data).metadata();\n    void size;\n    assert.deepStrictEqual(metadata, {\n      autoOrient: {\n        height: 13,\n        width: 32\n      },\n      channels: 3,\n      chromaSubsampling: '4:2:0',\n      density: 72,\n      depth: 'uchar',\n      format: 'jpeg',\n      hasAlpha: false,\n      hasProfile: false,\n      // 32 / (2048 / 858) = 13.40625\n      // Math.round(13.40625) = 13\n      height: 13,\n      isProgressive: false,\n      isPalette: false,\n      space: 'srgb',\n      width: 32\n    });\n  });\n\n  it('can convert JPEG to AVIF', async () => {\n    const data = await sharp(inputJpg)\n      .resize(32)\n      .avif({ effort: 0 })\n      .toBuffer();\n    const { size, ...metadata } = await sharp(data).metadata();\n    void size;\n    assert.deepStrictEqual(metadata, {\n      autoOrient: {\n        height: 26,\n        width: 32\n      },\n      channels: 3,\n      compression: 'av1',\n      depth: 'uchar',\n      format: 'heif',\n      hasAlpha: false,\n      hasProfile: false,\n      height: 26,\n      isProgressive: false,\n      isPalette: false,\n      bitsPerSample: 8,\n      pagePrimary: 0,\n      pages: 1,\n      space: 'srgb',\n      width: 32\n    });\n  });\n\n  it('can passthrough AVIF', async () => {\n    const data = await sharp(inputAvif)\n      .resize(32)\n      .toBuffer();\n    const { size, ...metadata } = await sharp(data).metadata();\n    void size;\n    assert.deepStrictEqual(metadata, {\n      autoOrient: {\n        height: 13,\n        width: 32\n      },\n      channels: 3,\n      compression: 'av1',\n      depth: 'uchar',\n      format: 'heif',\n      hasAlpha: false,\n      hasProfile: false,\n      height: 13,\n      isProgressive: false,\n      isPalette: false,\n      bitsPerSample: 8,\n      pagePrimary: 0,\n      pages: 1,\n      space: 'srgb',\n      width: 32\n    });\n  });\n\n  it('can convert animated GIF to non-animated AVIF', async () => {\n    const data = await sharp(inputGifAnimated, { animated: true })\n      .resize(10)\n      .avif({ effort: 0 })\n      .toBuffer();\n    const { size, ...metadata } = await sharp(data).metadata();\n    void size;\n    assert.deepStrictEqual(metadata, {\n      autoOrient: {\n        height: 300,\n        width: 10\n      },\n      channels: 4,\n      compression: 'av1',\n      depth: 'uchar',\n      format: 'heif',\n      hasAlpha: true,\n      hasProfile: false,\n      height: 300,\n      isProgressive: false,\n      isPalette: false,\n      bitsPerSample: 8,\n      pagePrimary: 0,\n      pages: 1,\n      space: 'srgb',\n      width: 10\n    });\n  });\n\n  it('should cast to uchar', async () => {\n    const data = await sharp(inputJpg)\n      .resize(32)\n      .sharpen()\n      .avif({ effort: 0 })\n      .toBuffer();\n    const { size, ...metadata } = await sharp(data).metadata();\n    void size;\n    assert.deepStrictEqual(metadata, {\n      autoOrient: {\n        height: 26,\n        width: 32\n      },\n      channels: 3,\n      compression: 'av1',\n      depth: 'uchar',\n      format: 'heif',\n      hasAlpha: false,\n      hasProfile: false,\n      height: 26,\n      isProgressive: false,\n      isPalette: false,\n      bitsPerSample: 8,\n      pagePrimary: 0,\n      pages: 1,\n      space: 'srgb',\n      width: 32\n    });\n  });\n\n  it('Invalid width - too large', async () =>\n    assert.rejects(\n      () => sharp({ create: { width: 16385, height: 16, channels: 3, background: 'red' } }).avif().toBuffer(),\n      /Processed image is too large for the HEIF format/\n    )\n  );\n\n  it('Invalid height - too large', async () =>\n    assert.rejects(\n      () => sharp({ create: { width: 16, height: 16385, channels: 3, background: 'red' } }).avif().toBuffer(),\n      /Processed image is too large for the HEIF format/\n    )\n  );\n\n  it('Invalid bitdepth value throws error', () =>\n    assert.throws(\n      () => sharp().avif({ bitdepth: 11 }),\n      /Expected 8, 10 or 12 for bitdepth but received 11 of type number/\n    )\n  );\n});\n"
  },
  {
    "path": "test/unit/bandbool.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\nconst fixtures = require('../fixtures');\nconst sharp = require('../../');\n\ndescribe('Bandbool per-channel boolean operations', () => {\n  [\n    sharp.bool.and,\n    sharp.bool.or,\n    sharp.bool.eor\n  ]\n    .forEach((op) => {\n      it(`${op} operation`, (_t, done) => {\n        sharp(fixtures.inputPngBooleanNoAlpha)\n          .bandbool(op)\n          .toColourspace('b-w')\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            assert.strictEqual(200, info.width);\n            assert.strictEqual(200, info.height);\n            assert.strictEqual(1, info.channels);\n            fixtures.assertSimilar(fixtures.expected(`bandbool_${op}_result.png`), data, done);\n          });\n      });\n    });\n\n  it('sRGB image retains 3 channels', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .bandbool('and')\n      .toBuffer((err, _data, info) => {\n        if (err) throw err;\n        assert.strictEqual(3, info.channels);\n        done();\n      });\n  });\n\n  it('Invalid operation', () => {\n    assert.throws(() => {\n      sharp().bandbool('fail');\n    });\n  });\n\n  it('Missing operation', () => {\n    assert.throws(() => {\n      sharp().bandbool();\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/blur.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Blur', () => {\n  it('specific radius 1', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .blur(1)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('blur-1.jpg'), data, done);\n      });\n  });\n\n  it('specific radius 10', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .blur(10)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('blur-10.jpg'), data, done);\n      });\n  });\n\n  it('specific options.sigma 10', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .blur({ sigma: 10 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('blur-10.jpg'), data, done);\n      });\n  });\n\n  it('specific radius 0.3', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .blur(0.3)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('blur-0.3.jpg'), data, done);\n      });\n  });\n\n  it('mild blur', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .blur()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('blur-mild.jpg'), data, done);\n      });\n  });\n\n  it('invalid radius', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).blur(0.1);\n    });\n  });\n\n  it('blurred image is smaller than non-blurred', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .blur(false)\n      .toBuffer((err, notBlurred, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, notBlurred.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .blur(true)\n          .toBuffer((err, blurred, info) => {\n            if (err) throw err;\n            assert.strictEqual(true, blurred.length > 0);\n            assert.strictEqual(true, blurred.length < notBlurred.length);\n            assert.strictEqual('jpeg', info.format);\n            assert.strictEqual(320, info.width);\n            assert.strictEqual(240, info.height);\n            done();\n          });\n      });\n  });\n\n  it('invalid precision', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).blur({ sigma: 1, precision: 'invalid' });\n    }, /Expected one of: integer, float, approximate for precision but received invalid of type string/);\n  });\n\n  it('invalid minAmplitude', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).blur({ sigma: 1, minAmplitude: 0 });\n    }, /Expected number between 0.001 and 1 for minAmplitude but received 0 of type number/);\n\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).blur({ sigma: 1, minAmplitude: 1.01 });\n    }, /Expected number between 0.001 and 1 for minAmplitude but received 1.01 of type number/);\n  });\n\n  it('specific radius 10 and precision approximate', async () => {\n    const approximate = await sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .blur({ sigma: 10, precision: 'approximate' })\n      .toBuffer();\n    const integer = await sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .blur(10)\n      .toBuffer();\n\n    assert.notDeepEqual(approximate, integer);\n    await fixtures.assertSimilar(fixtures.expected('blur-10.jpg'), approximate);\n  });\n\n  it('specific radius 10 and minAmplitude 0.01', async () => {\n    const minAmplitudeLow = await sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .blur({ sigma: 10, minAmplitude: 0.01 })\n      .toBuffer();\n    const minAmplitudeDefault = await sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .blur(10)\n      .toBuffer();\n\n    assert.notDeepEqual(minAmplitudeLow, minAmplitudeDefault);\n    await fixtures.assertSimilar(fixtures.expected('blur-10.jpg'), minAmplitudeLow);\n  });\n\n  it('options.sigma is required if options object is passed', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).blur({ precision: 'invalid' });\n    }, /Expected number between 0.3 and 1000 for options.sigma but received undefined of type undefined/);\n  });\n});\n"
  },
  {
    "path": "test/unit/boolean.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst fixtures = require('../fixtures');\nconst sharp = require('../../');\n\ndescribe('Boolean operation between two images', () => {\n  const inputJpgBooleanTestBuffer = fs.readFileSync(fixtures.inputJpgBooleanTest);\n\n  [\n    sharp.bool.and,\n    sharp.bool.or,\n    sharp.bool.eor\n  ]\n    .forEach((op) => {\n      it(`${op} operation, file`, (_t, done) => {\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .boolean(fixtures.inputJpgBooleanTest, op)\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            assert.strictEqual(320, info.width);\n            assert.strictEqual(240, info.height);\n            fixtures.assertSimilar(fixtures.expected(`boolean_${op}_result.jpg`), data, done);\n          });\n      });\n\n      it(`${op} operation, buffer`, (_t, done) => {\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .boolean(inputJpgBooleanTestBuffer, op)\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            assert.strictEqual(320, info.width);\n            assert.strictEqual(240, info.height);\n            fixtures.assertSimilar(fixtures.expected(`boolean_${op}_result.jpg`), data, done);\n          });\n      });\n\n      it(`${op} operation, raw`, (_t, done) => {\n        sharp(fixtures.inputJpgBooleanTest)\n          .raw()\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            sharp(fixtures.inputJpg)\n              .resize(320, 240)\n              .boolean(data, op, { raw: info })\n              .toBuffer((err, data, info) => {\n                if (err) throw err;\n                assert.strictEqual(320, info.width);\n                assert.strictEqual(240, info.height);\n                fixtures.assertSimilar(fixtures.expected(`boolean_${op}_result.jpg`), data, done);\n              });\n          });\n      });\n    });\n\n  it('Invalid operation', () => {\n    assert.throws(() => {\n      sharp().boolean(fixtures.inputJpgBooleanTest, 'fail');\n    });\n  });\n\n  it('Invalid operation, non-string', () => {\n    assert.throws(() => {\n      sharp().boolean(fixtures.inputJpgBooleanTest, null);\n    });\n  });\n\n  it('Missing input', () => {\n    assert.throws(() => {\n      sharp().boolean();\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/clahe.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../lib');\nconst fixtures = require('../fixtures');\n\ndescribe('Clahe', () => {\n  it('width 5 width 5 maxSlope 0', (_t, done) => {\n    sharp(fixtures.inputJpgClahe)\n      .clahe({ width: 5, height: 5, maxSlope: 0 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        fixtures.assertSimilar(fixtures.expected('clahe-5-5-0.jpg'), data, { threshold: 10 }, done);\n      });\n  });\n\n  it('width 5 width 5 maxSlope 5', (_t, done) => {\n    sharp(fixtures.inputJpgClahe)\n      .clahe({ width: 5, height: 5, maxSlope: 5 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        fixtures.assertSimilar(fixtures.expected('clahe-5-5-5.jpg'), data, done);\n      });\n  });\n\n  it('width 11 width 25 maxSlope 14', (_t, done) => {\n    sharp(fixtures.inputJpgClahe)\n      .clahe({ width: 11, height: 25, maxSlope: 14 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        fixtures.assertSimilar(fixtures.expected('clahe-11-25-14.jpg'), data, done);\n      });\n  });\n\n  it('width 50 width 50 maxSlope 0', (_t, done) => {\n    sharp(fixtures.inputJpgClahe)\n      .clahe({ width: 50, height: 50, maxSlope: 0 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        fixtures.assertSimilar(fixtures.expected('clahe-50-50-0.jpg'), data, done);\n      });\n  });\n\n  it('width 50 width 50 maxSlope 14', (_t, done) => {\n    sharp(fixtures.inputJpgClahe)\n      .clahe({ width: 50, height: 50, maxSlope: 14 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        fixtures.assertSimilar(fixtures.expected('clahe-50-50-14.jpg'), data, done);\n      });\n  });\n\n  it('width 100 width 50 maxSlope 3', (_t, done) => {\n    sharp(fixtures.inputJpgClahe)\n      .clahe({ width: 100, height: 50, maxSlope: 3 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        fixtures.assertSimilar(fixtures.expected('clahe-100-50-3.jpg'), data, done);\n      });\n  });\n\n  it('width 100 width 100 maxSlope 0', (_t, done) => {\n    sharp(fixtures.inputJpgClahe)\n      .clahe({ width: 100, height: 100, maxSlope: 0 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        fixtures.assertSimilar(fixtures.expected('clahe-100-100-0.jpg'), data, done);\n      });\n  });\n\n  it('invalid maxSlope', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe({ width: 100, height: 100, maxSlope: -5 });\n    });\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe({ width: 100, height: 100, maxSlope: 110 });\n    });\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe({ width: 100, height: 100, maxSlope: 5.5 });\n    });\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe({ width: 100, height: 100, maxSlope: 'a string' });\n    });\n  });\n\n  it('invalid width', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe({ width: 100.5, height: 100 });\n    });\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe({ width: -5, height: 100 });\n    });\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe({ width: true, height: 100 });\n    });\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe({ width: 'string test', height: 100 });\n    });\n  });\n\n  it('invalid height', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe({ width: 100, height: 100.5 });\n    });\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe({ width: 100, height: -5 });\n    });\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe({ width: 100, height: true });\n    });\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe({ width: 100, height: 'string test' });\n    });\n  });\n\n  it('invalid options object', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpgClahe).clahe(100, 100, 5);\n    });\n  });\n\n  it('uses default maxSlope of 3', (_t, done) => {\n    sharp(fixtures.inputJpgClahe)\n      .clahe({ width: 100, height: 50 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        fixtures.assertSimilar(fixtures.expected('clahe-100-50-3.jpg'), data, done);\n      });\n  });\n});\n"
  },
  {
    "path": "test/unit/clone.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst { afterEach, beforeEach, describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Clone', () => {\n  beforeEach(() => {\n    sharp.cache(false);\n  });\n  afterEach(() => {\n    sharp.cache(true);\n  });\n\n  it('Read from Stream and write to multiple Streams', (_t, done) => {\n    let finishEventsExpected = 2;\n    // Output stream 1\n    const output1 = fixtures.path('output.multi-stream.1.jpg');\n    const writable1 = fs.createWriteStream(output1);\n    writable1.on('finish', () => {\n      sharp(output1).toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fs.unlinkSync(output1);\n        finishEventsExpected--;\n        if (finishEventsExpected === 0) {\n          done();\n        }\n      });\n    });\n    // Output stream 2\n    const output2 = fixtures.path('output.multi-stream.2.jpg');\n    const writable2 = fs.createWriteStream(output2);\n    writable2.on('finish', () => {\n      sharp(output2).toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(100, info.width);\n        assert.strictEqual(122, info.height);\n        fs.unlinkSync(output2);\n        finishEventsExpected--;\n        if (finishEventsExpected === 0) {\n          done();\n        }\n      });\n    });\n    // Create parent instance\n    const rotator = sharp().rotate(90);\n    // Cloned instances with differing dimensions\n    rotator.clone().resize(320, 240).pipe(writable1);\n    rotator.clone().resize(100, 122).pipe(writable2);\n    // Go\n    fs.createReadStream(fixtures.inputJpg).pipe(rotator);\n  });\n\n  it('Stream-based input attaches finish event listener to original', () => {\n    const original = sharp();\n    const clone = original.clone();\n    assert.strictEqual(1, original.listenerCount('finish'));\n    assert.strictEqual(0, clone.listenerCount('finish'));\n  });\n\n  it('Non Stream-based input does not attach finish event listeners', () => {\n    const original = sharp(fixtures.inputJpg);\n    const clone = original.clone();\n    assert.strictEqual(0, original.listenerCount('finish'));\n    assert.strictEqual(0, clone.listenerCount('finish'));\n  });\n\n  it('Ensure deep clone of properties, including arrays', async () => {\n    const alpha = await sharp({\n      create: { width: 320, height: 240, channels: 3, background: 'red' }\n    }).toColourspace('b-w').png().toBuffer();\n\n    const original = sharp();\n    const joiner = original.clone().joinChannel(alpha);\n    const negater = original.clone().negate();\n\n    fs.createReadStream(fixtures.inputJpg320x240).pipe(original);\n    const joined = await joiner.png({ effort: 1 }).toBuffer();\n    const negated = await negater.png({ effort: 1 }).toBuffer();\n\n    const joinedMetadata = await sharp(joined).metadata();\n    assert.strictEqual(joinedMetadata.channels, 4);\n    assert.strictEqual(joinedMetadata.hasAlpha, true);\n\n    const negatedMetadata = await sharp(negated).metadata();\n    assert.strictEqual(negatedMetadata.channels, 3);\n    assert.strictEqual(negatedMetadata.hasAlpha, false);\n  });\n});\n"
  },
  {
    "path": "test/unit/colourspace.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Colour space conversion', () => {\n  it('To greyscale', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .greyscale()\n      .toFile(fixtures.path('output.greyscale-gamma-0.0.jpg'), done);\n  });\n\n  it('To greyscale with gamma correction', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .gamma()\n      .grayscale()\n      .toFile(fixtures.path('output.greyscale-gamma-2.2.jpg'), done);\n  });\n\n  it('Not to greyscale', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .greyscale(false)\n      .toFile(fixtures.path('output.greyscale-not.jpg'), done);\n  });\n\n  it('Greyscale with single channel output', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .greyscale()\n      .toColourspace('b-w')\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(1, info.channels);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('output.greyscale-single.jpg'), data, done);\n      });\n  });\n\n  it('From 1-bit TIFF to sRGB WebP', async () => {\n    const data = await sharp(fixtures.inputTiff)\n      .resize(8, 8)\n      .webp()\n      .toBuffer();\n\n    const { format } = await sharp(data).metadata();\n    assert.strictEqual(format, 'webp');\n  });\n\n  it('From CMYK to sRGB', (_t, done) => {\n    sharp(fixtures.inputJpgWithCmykProfile)\n      .resize(320)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        done();\n      });\n  });\n\n  it('From CMYK to sRGB with white background, not yellow', (_t, done) => {\n    sharp(fixtures.inputJpgWithCmykProfile)\n      .resize(320, 240, {\n        fit: sharp.fit.contain,\n        background: 'white'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('colourspace.cmyk.jpg'), data, done);\n      });\n  });\n\n  it('From profile-less CMYK to sRGB', (_t, done) => {\n    sharp(fixtures.inputJpgWithCmykNoProfile)\n      .resize(320)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        fixtures.assertSimilar(fixtures.expected('colourspace.cmyk-without-profile.jpg'), data, done);\n      });\n  });\n\n  it('Profile-less CMYK roundtrip', async () => {\n    const [c, m, y, k] = await sharp(fixtures.inputJpgWithCmykNoProfile)\n      .pipelineColourspace('cmyk')\n      .toColourspace('cmyk')\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual(\n      { c, m, y, k },\n      { c: 55, m: 27, y: 0, k: 0 }\n    );\n  });\n\n  it('CMYK profile to CMYK profile conversion using perceptual intent', async () => {\n    const data = await sharp(fixtures.inputTiffFogra)\n      .resize(320, 240)\n      .toColourspace('cmyk')\n      .pipelineColourspace('cmyk')\n      .withIccProfile(fixtures.path('XCMYK 2017.icc'))\n      .raw()\n      .toBuffer();\n\n    const [c, m, y, k] = data;\n    assert.deepStrictEqual(\n      { c, m, y, k },\n      { c: 1, m: 239, y: 227, k: 5 }\n    );\n  });\n\n  it('CMYK profile to CMYK profile with negate', (_t, done) => {\n    sharp(fixtures.inputTiffFogra)\n      .resize(320, 240)\n      .toColourspace('cmyk')\n      .pipelineColourspace('cmyk')\n      .withIccProfile(fixtures.path('XCMYK 2017.icc'))\n      .negate()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('tiff', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(\n          fixtures.expected('colourspace.cmyk-to-cmyk-negated.tif'),\n          data,\n          { threshold: 0 },\n          done\n        );\n      });\n  });\n\n  it('From sRGB with RGB16 pipeline, resize with gamma, to sRGB', (_t, done) => {\n    sharp(fixtures.inputPngGradients)\n      .pipelineColourspace('rgb16')\n      .resize(320)\n      .gamma()\n      .toColourspace('srgb')\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        fixtures.assertSimilar(fixtures.expected('colourspace-gradients-gamma-resize.png'), data, {\n          threshold: 0\n        }, done);\n      });\n  });\n\n  it('Convert P3 to sRGB', async () => {\n    const [r, g, b] = await sharp(fixtures.inputPngP3)\n      .raw()\n      .toBuffer();\n    assert.strictEqual(r, 255);\n    assert.strictEqual(g, 0);\n    assert.strictEqual(b, 0);\n  });\n\n  it('Passthrough P3', async () => {\n    const [r, g, b] = await sharp(fixtures.inputPngP3)\n      .withMetadata({ icc: 'p3' })\n      .raw()\n      .toBuffer();\n    assert.strictEqual(r, 234);\n    assert.strictEqual(g, 51);\n    assert.strictEqual(b, 34);\n  });\n\n  it('Invalid pipelineColourspace input', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg)\n        .pipelineColorspace(null);\n    }, /Expected string for colourspace but received null of type object/);\n  });\n\n  it('Invalid toColourspace input', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg)\n        .toColourspace(null);\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/composite.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst fixtures = require('../fixtures');\nconst sharp = require('../../');\n\nconst red = { r: 255, g: 0, b: 0, alpha: 0.5 };\nconst green = { r: 0, g: 255, b: 0, alpha: 0.5 };\nconst blue = { r: 0, g: 0, b: 255, alpha: 0.5 };\n\nconst redRect = {\n  create: {\n    width: 80,\n    height: 60,\n    channels: 4,\n    background: red\n  }\n};\n\nconst greenRect = {\n  create: {\n    width: 40,\n    height: 40,\n    channels: 4,\n    background: green\n  }\n};\n\nconst blueRect = {\n  create: {\n    width: 60,\n    height: 40,\n    channels: 4,\n    background: blue\n  }\n};\n\nconst blends = [\n  'over',\n  'xor',\n  'saturate',\n  'dest-over'\n];\n\n// Test\ndescribe('composite', () => {\n  blends.forEach(blend => {\n    it(`blend ${blend}`, async () => {\n      const filename = `composite.blend.${blend}.png`;\n      const actual = fixtures.path(`output.${filename}`);\n      const expected = fixtures.expected(filename);\n      await sharp(redRect)\n        .composite([{\n          input: blueRect,\n          blend\n        }])\n        .toFile(actual);\n      fixtures.assertMaxColourDistance(actual, expected);\n    });\n  });\n\n  it('premultiplied true', () => {\n    const filename = 'composite.premultiplied.png';\n    const below = fixtures.path(`input.below.${filename}`);\n    const above = fixtures.path(`input.above.${filename}`);\n    const actual = fixtures.path(`output.true.${filename}`);\n    const expected = fixtures.expected(`expected.true.${filename}`);\n    return sharp(below)\n      .composite([{\n        input: above,\n        blend: 'color-burn',\n        top: 0,\n        left: 0,\n        premultiplied: true\n      }])\n      .toFile(actual)\n      .then(() => {\n        fixtures.assertMaxColourDistance(actual, expected);\n      });\n  });\n\n  it('premultiplied false', () => {\n    const filename = 'composite.premultiplied.png';\n    const below = fixtures.path(`input.below.${filename}`);\n    const above = fixtures.path(`input.above.${filename}`);\n    const actual = fixtures.path(`output.false.${filename}`);\n    const expected = fixtures.expected(`expected.false.${filename}`);\n    return sharp(below)\n      .composite([{\n        input: above,\n        blend: 'color-burn',\n        top: 0,\n        left: 0,\n        premultiplied: false\n      }])\n      .toFile(actual)\n      .then(() => {\n        fixtures.assertMaxColourDistance(actual, expected);\n      });\n  });\n\n  it('premultiplied absent', () => {\n    const filename = 'composite.premultiplied.png';\n    const below = fixtures.path(`input.below.${filename}`);\n    const above = fixtures.path(`input.above.${filename}`);\n    const actual = fixtures.path(`output.absent.${filename}`);\n    const expected = fixtures.expected(`expected.absent.${filename}`);\n    return sharp(below)\n      .composite([{\n        input: above,\n        blend: 'color-burn',\n        top: 0,\n        left: 0\n      }])\n      .toFile(actual)\n      .then(() => {\n        fixtures.assertMaxColourDistance(actual, expected);\n      });\n  });\n\n  it('scrgb pipeline', () => {\n    const filename = 'composite-red-scrgb.png';\n    const actual = fixtures.path(`output.${filename}`);\n    const expected = fixtures.expected(filename);\n    return sharp({\n      create: {\n        width: 32, height: 32, channels: 4, background: red\n      }\n    })\n      .pipelineColourspace('scrgb')\n      .composite([{\n        input: fixtures.inputPngWithTransparency16bit,\n        blend: 'color-burn'\n      }])\n      .toFile(actual)\n      .then(() => {\n        fixtures.assertMaxColourDistance(actual, expected);\n      });\n  });\n\n  it('multiple', async () => {\n    const filename = 'composite-multiple.png';\n    const actual = fixtures.path(`output.${filename}`);\n    const expected = fixtures.expected(filename);\n    await sharp(redRect)\n      .composite([{\n        input: blueRect,\n        gravity: 'northeast'\n      }, {\n        input: greenRect,\n        gravity: 'southwest'\n      }])\n      .toFile(actual);\n    fixtures.assertMaxColourDistance(actual, expected);\n  });\n\n  it('autoOrient', async () => {\n    const data = await sharp({\n      create: {\n        width: 600, height: 600, channels: 4, background: { ...red, alpha: 1 }\n      }\n    })\n      .composite([{\n        input: fixtures.inputJpgWithExif,\n        autoOrient: true\n      }])\n      .jpeg()\n      .toBuffer();\n\n    await fixtures.assertSimilar(fixtures.expected('composite-autoOrient.jpg'), data);\n  });\n\n  it('zero offset', done => {\n    sharp(fixtures.inputJpg)\n      .resize(80)\n      .composite([{\n        input: fixtures.inputPngWithTransparency16bit,\n        top: 0,\n        left: 0\n      }])\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(3, info.channels);\n        fixtures.assertSimilar(fixtures.expected('overlay-offset-0.jpg'), data, done);\n      });\n  });\n\n  it('offset and gravity', done => {\n    sharp(fixtures.inputJpg)\n      .resize(80)\n      .composite([{\n        input: fixtures.inputPngWithTransparency16bit,\n        left: 10,\n        top: 10,\n        gravity: 4\n      }])\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(3, info.channels);\n        fixtures.assertSimilar(fixtures.expected('overlay-offset-with-gravity.jpg'), data, done);\n      });\n  });\n\n  it('negative offset and gravity', done => {\n    sharp(fixtures.inputJpg)\n      .resize(400)\n      .composite([{\n        input: fixtures.inputPngWithTransparency16bit,\n        left: -10,\n        top: -10,\n        gravity: 4\n      }])\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(3, info.channels);\n        fixtures.assertSimilar(\n          fixtures.expected('overlay-negative-offset-with-gravity.jpg'), data, done);\n      });\n  });\n\n  it('offset, gravity and tile', done => {\n    sharp(fixtures.inputJpg)\n      .resize(80)\n      .composite([{\n        input: fixtures.inputPngWithTransparency16bit,\n        left: 10,\n        top: 10,\n        gravity: 4,\n        tile: true\n      }])\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(3, info.channels);\n        fixtures.assertSimilar(fixtures.expected('overlay-offset-with-gravity-tile.jpg'), data, done);\n      });\n  });\n\n  it('offset and tile', done => {\n    sharp(fixtures.inputJpg)\n      .resize(80)\n      .composite([{\n        input: fixtures.inputPngWithTransparency16bit,\n        left: 10,\n        top: 10,\n        tile: true\n      }])\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(3, info.channels);\n        fixtures.assertSimilar(fixtures.expected('overlay-offset-with-tile.jpg'), data, done);\n      });\n  });\n\n  it('centre gravity should replicate correct number of tiles', async () => {\n    const red = { r: 255, g: 0, b: 0 };\n    const [r, g, b] = await sharp({\n      create: {\n        width: 40, height: 40, channels: 4, background: red\n      }\n    })\n      .composite([{\n        input: fixtures.inputPngWithTransparency16bit,\n        gravity: 'centre',\n        tile: true\n      }])\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual({ r, g, b }, red);\n  });\n\n  it('cutout via dest-in', done => {\n    sharp(fixtures.inputJpg)\n      .resize(300, 300)\n      .composite([{\n        input: Buffer.from('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"200\" height=\"200\"><rect x=\"0\" y=\"0\" width=\"200\" height=\"200\" rx=\"50\" ry=\"50\"/></svg>'),\n        density: 96,\n        blend: 'dest-in',\n        cutout: true\n      }])\n      .png()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(300, info.width);\n        assert.strictEqual(300, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('composite-cutout.png'), data, done);\n      });\n  });\n\n  describe('numeric gravity', () => {\n    Object.keys(sharp.gravity).forEach(gravity => {\n      it(gravity, done => {\n        sharp(fixtures.inputJpg)\n          .resize(80)\n          .composite([{\n            input: fixtures.inputPngWithTransparency16bit,\n            gravity\n          }])\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            assert.strictEqual('jpeg', info.format);\n            assert.strictEqual(80, info.width);\n            assert.strictEqual(65, info.height);\n            assert.strictEqual(3, info.channels);\n            fixtures.assertSimilar(fixtures.expected(`overlay-gravity-${gravity}.jpg`), data, done);\n          });\n      });\n    });\n  });\n\n  describe('string gravity', () => {\n    Object.keys(sharp.gravity).forEach(gravity => {\n      it(gravity, done => {\n        const expected = fixtures.expected(`overlay-gravity-${gravity}.jpg`);\n        sharp(fixtures.inputJpg)\n          .resize(80)\n          .composite([{\n            input: fixtures.inputPngWithTransparency16bit,\n            gravity: sharp.gravity[gravity]\n          }])\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            assert.strictEqual('jpeg', info.format);\n            assert.strictEqual(80, info.width);\n            assert.strictEqual(65, info.height);\n            assert.strictEqual(3, info.channels);\n            fixtures.assertSimilar(expected, data, done);\n          });\n      });\n    });\n  });\n\n  describe('tile and gravity', () => {\n    Object.keys(sharp.gravity).forEach(gravity => {\n      it(gravity, done => {\n        const expected = fixtures.expected(`overlay-tile-gravity-${gravity}.jpg`);\n        sharp(fixtures.inputJpg)\n          .resize(80)\n          .composite([{\n            input: fixtures.inputPngWithTransparency16bit,\n            tile: true,\n            gravity\n          }])\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            assert.strictEqual('jpeg', info.format);\n            assert.strictEqual(80, info.width);\n            assert.strictEqual(65, info.height);\n            assert.strictEqual(3, info.channels);\n            fixtures.assertSimilar(expected, data, done);\n          });\n      });\n    });\n  });\n\n  describe('validation', () => {\n    it('missing images', () => {\n      assert.throws(() => {\n        sharp().composite();\n      }, /Expected array for images to composite but received undefined of type undefined/);\n    });\n\n    it('invalid images', () => {\n      assert.throws(() => {\n        sharp().composite(['invalid']);\n      }, /Expected object for image to composite but received invalid of type string/);\n    });\n\n    it('missing input', () => {\n      assert.throws(() => {\n        sharp().composite([{}]);\n      }, /Unsupported input/);\n    });\n\n    it('invalid blend', () => {\n      assert.throws(() => {\n        sharp().composite([{ input: 'test', blend: 'invalid' }]);\n      }, /Expected valid blend name for blend but received invalid of type string/);\n    });\n\n    it('invalid tile', () => {\n      assert.throws(() => {\n        sharp().composite([{ input: 'test', tile: 'invalid' }]);\n      }, /Expected boolean for tile but received invalid of type string/);\n    });\n\n    it('invalid premultiplied', () => {\n      assert.throws(() => {\n        sharp().composite([{ input: 'test', premultiplied: 'invalid' }]);\n      }, /Expected boolean for premultiplied but received invalid of type string/);\n    });\n\n    it('invalid left', () => {\n      assert.throws(() => {\n        sharp().composite([{ input: 'test', left: 0.5 }]);\n      }, /Expected integer for left but received 0.5 of type number/);\n      assert.throws(() => {\n        sharp().composite([{ input: 'test', left: 'invalid' }]);\n      }, /Expected integer for left but received invalid of type string/);\n      assert.throws(() => {\n        sharp().composite([{ input: 'test', left: 'invalid', top: 10 }]);\n      }, /Expected integer for left but received invalid of type string/);\n    });\n\n    it('invalid top', () => {\n      assert.throws(() => {\n        sharp().composite([{ input: 'test', top: 0.5 }]);\n      }, /Expected integer for top but received 0.5 of type number/);\n      assert.throws(() => {\n        sharp().composite([{ input: 'test', top: 'invalid' }]);\n      }, /Expected integer for top but received invalid of type string/);\n      assert.throws(() => {\n        sharp().composite([{ input: 'test', top: 'invalid', left: 10 }]);\n      }, /Expected integer for top but received invalid of type string/);\n    });\n\n    it('left but no top', () => {\n      assert.throws(() => {\n        sharp().composite([{ input: 'test', left: 1 }]);\n      }, /Expected both left and top to be set/);\n    });\n\n    it('top but no left', () => {\n      assert.throws(() => {\n        sharp().composite([{ input: 'test', top: 1 }]);\n      }, /Expected both left and top to be set/);\n    });\n\n    it('invalid gravity', () => {\n      assert.throws(() => {\n        sharp().composite([{ input: 'test', gravity: 'invalid' }]);\n      }, /Expected valid gravity for gravity but received invalid of type string/);\n    });\n  });\n\n  it('Allow offset beyond bottom/right edge', async () => {\n    const red = { r: 255, g: 0, b: 0 };\n    const blue = { r: 0, g: 0, b: 255 };\n\n    const [r, g, b] = await sharp({ create: { width: 2, height: 2, channels: 4, background: red } })\n      .composite([{\n        input: { create: { width: 2, height: 2, channels: 4, background: blue } },\n        top: 1,\n        left: 1\n      }])\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual(red, { r, g, b });\n  });\n\n  it('Ensure tiled composition works with resized fit=outside', async () => {\n    const { info } = await sharp({\n      create: {\n        width: 41, height: 41, channels: 3, background: 'red'\n      }\n    })\n      .resize({\n        width: 10,\n        height: 40,\n        fit: 'outside'\n      })\n      .composite([\n        {\n          input: {\n            create: {\n              width: 16, height: 16, channels: 3, background: 'green'\n            }\n          },\n          tile: true\n        }\n      ])\n      .toBuffer({ resolveWithObject: true });\n\n    assert.strictEqual(info.width, 40);\n    assert.strictEqual(info.height, 40);\n  });\n\n  it('Ensure implicit unpremultiply after resize but before composite', async () => {\n    const [r, g, b, a] = await sharp({\n      create: {\n        width: 1, height: 1, channels: 4, background: 'saddlebrown'\n      }\n    })\n      .resize({ width: 8 })\n      .composite([{\n        input: Buffer.from([255, 255, 255, 128]),\n        raw: { width: 1, height: 1, channels: 4 },\n        tile: true,\n        blend: 'dest-in'\n      }])\n      .raw()\n      .toBuffer();\n\n    assert.strictEqual(r, 139);\n    assert.strictEqual(g, 69);\n    assert.strictEqual(b, 19);\n    assert.strictEqual(a, 128);\n  });\n\n  it('Ensure tiled overlay is fully decoded', async () => {\n    const tile = await sharp({\n      create: {\n        width: 8, height: 513, channels: 3, background: 'red'\n      }\n    })\n      .png({ compressionLevel: 0 })\n      .toBuffer();\n\n    const { info } = await sharp({\n      create: {\n        width: 8, height: 514, channels: 3, background: 'green'\n      }\n    })\n      .composite([{\n        input: tile,\n        tile: true\n      }])\n      .toBuffer({ resolveWithObject: true });\n\n    assert.strictEqual(info.width, 8);\n    assert.strictEqual(info.height, 514);\n  });\n});\n"
  },
  {
    "path": "test/unit/convolve.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Convolve', () => {\n  it('specific convolution kernel 1', (_t, done) => {\n    sharp(fixtures.inputPngStripesV)\n      .convolve({\n        width: 3,\n        height: 3,\n        scale: 50,\n        offset: 0,\n        kernel: [\n          10, 20, 10,\n          0, 0, 0,\n          10, 20, 10\n        ]\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('conv-1.png'), data, done);\n      });\n  });\n\n  it('specific convolution kernel 2', (_t, done) => {\n    sharp(fixtures.inputPngStripesH)\n      .convolve({\n        width: 3,\n        height: 3,\n        kernel: [\n          1, 0, 1,\n          2, 0, 2,\n          1, 0, 1\n        ]\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('conv-2.png'), data, done);\n      });\n  });\n\n  it('horizontal Sobel operator', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .convolve({\n        width: 3,\n        height: 3,\n        kernel: [\n          -1, 0, 1,\n          -2, 0, 2,\n          -1, 0, 1\n        ]\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('conv-sobel-horizontal.jpg'), data, done);\n      });\n  });\n\n  describe('invalid kernel specification', () => {\n    it('missing', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg).convolve({});\n      });\n    });\n    it('incorrect data format', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg).convolve({\n          width: 3,\n          height: 3,\n          kernel: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n        });\n      });\n    });\n    it('incorrect dimensions', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg).convolve({\n          width: 3,\n          height: 4,\n          kernel: [1, 2, 3, 4, 5, 6, 7, 8, 9]\n        });\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/dilate.js",
    "content": "const { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Dilate', () => {\n  it('dilate 1 png', (_t, done) => {\n    sharp(fixtures.inputPngDotAndLines)\n      .dilate(1)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(100, info.width);\n        assert.strictEqual(100, info.height);\n        fixtures.assertSimilar(fixtures.expected('dilate-1.png'), data, done);\n      });\n  });\n\n  it('dilate 1 png - default width', (_t, done) => {\n    sharp(fixtures.inputPngDotAndLines)\n      .dilate()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(100, info.width);\n        assert.strictEqual(100, info.height);\n        fixtures.assertSimilar(fixtures.expected('dilate-1.png'), data, done);\n      });\n  });\n\n  it('invalid dilation width', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).dilate(-1);\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/erode.js",
    "content": "const { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Erode', () => {\n  it('erode 1 png', (_t, done) => {\n    sharp(fixtures.inputPngDotAndLines)\n      .erode(1)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(100, info.width);\n        assert.strictEqual(100, info.height);\n        fixtures.assertSimilar(fixtures.expected('erode-1.png'), data, done);\n      });\n  });\n\n  it('erode 1 png - default width', (_t, done) => {\n    sharp(fixtures.inputPngDotAndLines)\n      .erode()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(100, info.width);\n        assert.strictEqual(100, info.height);\n        fixtures.assertSimilar(fixtures.expected('erode-1.png'), data, done);\n      });\n  });\n\n  it('invalid erosion width', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).erode(-1);\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/extend.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Extend', () => {\n  describe('extend all sides equally via a single value', () => {\n    it('JPEG', (_t, done) => {\n      sharp(fixtures.inputJpg)\n        .resize(120)\n        .extend(10)\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(140, info.width);\n          assert.strictEqual(118, info.height);\n          fixtures.assertSimilar(fixtures.expected('extend-equal-single.jpg'), data, done);\n        });\n    });\n\n    it('Animated WebP', (_t, done) => {\n      sharp(fixtures.inputWebPAnimated, { pages: -1 })\n        .resize(120)\n        .extend(10)\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(140, info.width);\n          assert.strictEqual(140 * 9, info.height);\n          fixtures.assertSimilar(fixtures.expected('extend-equal-single.webp'), data, done);\n        });\n    });\n  });\n\n  ['background', 'copy', 'mirror', 'repeat'].forEach(extendWith => {\n    it(`extends all sides with animated WebP (${extendWith})`, (_t, done) => {\n      sharp(fixtures.inputWebPAnimated, { pages: -1 })\n        .resize(120)\n        .extend({\n          extendWith,\n          top: 40,\n          bottom: 40,\n          left: 40,\n          right: 40\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(200, info.width);\n          assert.strictEqual(200 * 9, info.height);\n          fixtures.assertSimilar(fixtures.expected(`extend-equal-${extendWith}.webp`), data, done);\n        });\n    });\n\n    it(`extend all sides equally with RGB (${extendWith})`, (_t, done) => {\n      sharp(fixtures.inputJpg)\n        .resize(120)\n        .extend({\n          extendWith,\n          top: 10,\n          bottom: 10,\n          left: 10,\n          right: 10,\n          background: { r: 255, g: 0, b: 0 }\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(140, info.width);\n          assert.strictEqual(118, info.height);\n          fixtures.assertSimilar(fixtures.expected(`extend-equal-${extendWith}.jpg`), data, done);\n        });\n    });\n\n    it(`extend sides unequally with RGBA (${extendWith})`, (_t, done) => {\n      sharp(fixtures.inputPngWithTransparency16bit)\n        .resize(120)\n        .extend({\n          extendWith,\n          top: 50,\n          left: 10,\n          right: 35,\n          background: { r: 0, g: 0, b: 0, alpha: 0 }\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(165, info.width);\n          assert.strictEqual(170, info.height);\n          fixtures.assertSimilar(fixtures.expected(`extend-unequal-${extendWith}.png`), data, done);\n        });\n    });\n\n    it(`PNG with 2 channels (${extendWith})`, (_t, done) => {\n      sharp(fixtures.inputPngWithGreyAlpha)\n        .extend({\n          extendWith,\n          top: 50,\n          bottom: 50,\n          left: 80,\n          right: 80,\n          background: 'transparent'\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(true, data.length > 0);\n          assert.strictEqual('png', info.format);\n          assert.strictEqual(560, info.width);\n          assert.strictEqual(400, info.height);\n          assert.strictEqual(4, info.channels);\n          fixtures.assertSimilar(fixtures.expected(`extend-2channel-${extendWith}.png`), data, done);\n        });\n    });\n  });\n\n  it('extend top with mirroring uses ordered read', async () => {\n    const data = await sharp(fixtures.inputJpg)\n      .extend({\n        extendWith: 'mirror',\n        top: 1\n      })\n      .png({ compressionLevel: 0 })\n      .toBuffer();\n\n    const { width, height } = await sharp(data).metadata();\n    assert.strictEqual(2725, width);\n    assert.strictEqual(2226, height);\n  });\n\n  it('multi-page extend uses ordered read', async () => {\n    const multiPageTiff = await sharp(fixtures.inputGifAnimated, { animated: true })\n      .resize({ width: 8, height: 48 })\n      .tiff()\n      .toBuffer();\n\n    const data = await sharp(multiPageTiff, { pages: -1 })\n      .extend({\n        background: 'red',\n        top: 1\n      })\n      .png({ compressionLevel: 0 })\n      .toBuffer();\n\n    const { width, height } = await sharp(data).metadata();\n    assert.strictEqual(8, width);\n    assert.strictEqual(1470, height);\n  });\n\n  it('missing parameter fails', () => {\n    assert.throws(() => {\n      sharp().extend();\n    });\n  });\n  it('negative fails', () => {\n    assert.throws(() => {\n      sharp().extend(-1);\n    });\n  });\n  it('invalid top fails', () => {\n    assert.throws(\n      () => sharp().extend({ top: 'fail' }),\n      /Expected positive integer for top but received fail of type string/\n    );\n  });\n  it('invalid bottom fails', () => {\n    assert.throws(\n      () => sharp().extend({ bottom: -1 }),\n      /Expected positive integer for bottom but received -1 of type number/\n    );\n  });\n  it('invalid left fails', () => {\n    assert.throws(\n      () => sharp().extend({ left: 0.1 }),\n      /Expected positive integer for left but received 0.1 of type number/\n    );\n  });\n  it('invalid right fails', () => {\n    assert.throws(\n      () => sharp().extend({ right: {} }),\n      /Expected positive integer for right but received \\[object Object\\] of type object/\n    );\n  });\n  it('invalid extendWith fails', () => {\n    assert.throws(\n      () => sharp().extend({ extendWith: 'invalid-value' }),\n      /Expected one of: background, copy, repeat, mirror for extendWith but received invalid-value of type string/\n    );\n  });\n  it('can set all edges apart from right', () => {\n    assert.doesNotThrow(() => sharp().extend({ top: 1, left: 2, bottom: 3 }));\n  });\n\n  it('should add alpha channel before extending with a transparent Background', (_t, done) => {\n    sharp(fixtures.inputJpgWithLandscapeExif1)\n      .extend({\n        bottom: 10,\n        right: 10,\n        background: { r: 0, g: 0, b: 0, alpha: 0 }\n      })\n      .toFormat(sharp.format.png)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(610, info.width);\n        assert.strictEqual(460, info.height);\n        fixtures.assertSimilar(fixtures.expected('addAlphaChanelBeforeExtend.png'), data, done);\n      });\n  });\n\n  it('Premultiply background when compositing', async () => {\n    const background = { r: 191, g: 25, b: 66, alpha: 0.8 };\n    const data = await sharp({\n      create: {\n        width: 1, height: 1, channels: 4, background: '#fff0'\n      }\n    })\n      .composite([{\n        input: {\n          create: {\n            width: 1, height: 1, channels: 4, background\n          }\n        }\n      }])\n      .extend({\n        left: 1, background\n      })\n      .raw()\n      .toBuffer();\n    assert.deepStrictEqual(Array.from(data), [191, 25, 66, 204, 191, 25, 66, 204]);\n  });\n});\n"
  },
  {
    "path": "test/unit/extract.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Partial image extraction', () => {\n  it('JPEG', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .extract({ left: 2, top: 2, width: 20, height: 20 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(20, info.width);\n        assert.strictEqual(20, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract.jpg'), data, done);\n      });\n  });\n\n  it('PNG', (_t, done) => {\n    sharp(fixtures.inputPng)\n      .extract({ left: 200, top: 300, width: 400, height: 200 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(400, info.width);\n        assert.strictEqual(200, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract.png'), data, done);\n      });\n  });\n\n  it('WebP', (_t, done) => {\n    sharp(fixtures.inputWebP)\n      .extract({ left: 100, top: 50, width: 125, height: 200 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(125, info.width);\n        assert.strictEqual(200, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract.webp'), data, done);\n      });\n  });\n\n  describe('Animated WebP', () => {\n    it('Before resize', (_t, done) => {\n      sharp(fixtures.inputWebPAnimated, { pages: -1 })\n        .extract({ left: 0, top: 30, width: 80, height: 20 })\n        .resize(320, 80)\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80 * 9, info.height);\n          fixtures.assertSimilar(fixtures.expected('gravity-center-height.webp'), data, done);\n        });\n    });\n\n    it('After resize', (_t, done) => {\n      sharp(fixtures.inputWebPAnimated, { pages: -1 })\n        .resize(320, 320)\n        .extract({ left: 0, top: 120, width: 320, height: 80 })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80 * 9, info.height);\n          fixtures.assertSimilar(fixtures.expected('gravity-center-height.webp'), data, done);\n        });\n    });\n  });\n\n  it('TIFF', (_t, done) => {\n    sharp(fixtures.inputTiff)\n      .extract({ left: 34, top: 63, width: 341, height: 529 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(341, info.width);\n        assert.strictEqual(529, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract.tiff'), data, done);\n      });\n  });\n\n  it('Before resize', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .extract({ left: 10, top: 10, width: 10, height: 500 })\n      .resize(100, 100)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(100, info.width);\n        assert.strictEqual(100, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract-resize.jpg'), data, done);\n      });\n  });\n\n  it('After resize and crop', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(500, 500, {\n        position: sharp.gravity.north\n      })\n      .extract({ left: 10, top: 10, width: 100, height: 100 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(100, info.width);\n        assert.strictEqual(100, info.height);\n        fixtures.assertSimilar(fixtures.expected('resize-crop-extract.jpg'), data, done);\n      });\n  });\n\n  it('Before and after resize and crop', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .extract({ left: 0, top: 0, width: 700, height: 700 })\n      .resize(500, 500, {\n        position: sharp.gravity.north\n      })\n      .extract({ left: 10, top: 10, width: 100, height: 100 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(100, info.width);\n        assert.strictEqual(100, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract-resize-crop-extract.jpg'), data, done);\n      });\n  });\n\n  it('Extract then rotate', (_t, done) => {\n    sharp(fixtures.inputPngWithGreyAlpha)\n      .extract({ left: 20, top: 10, width: 380, height: 280 })\n      .rotate(90)\n      .jpeg()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(280, info.width);\n        assert.strictEqual(380, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract-rotate.jpg'), data, done);\n      });\n  });\n\n  it('Rotate then extract', (_t, done) => {\n    sharp(fixtures.inputPngWithGreyAlpha)\n      .rotate(90)\n      .extract({ left: 20, top: 10, width: 280, height: 380 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(280, info.width);\n        assert.strictEqual(380, info.height);\n        fixtures.assertSimilar(fixtures.expected('rotate-extract.jpg'), data, done);\n      });\n  });\n\n  it('Extract then rotate then extract', (_t, done) => {\n    sharp(fixtures.inputPngWithGreyAlpha)\n      .extract({ left: 20, top: 10, width: 180, height: 280 })\n      .rotate(90)\n      .extract({ left: 20, top: 10, width: 200, height: 100 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract-rotate-extract.jpg'), data, done);\n      });\n  });\n\n  it('Extract then rotate non-90 anagle', (_t, done) => {\n    sharp(fixtures.inputPngWithGreyAlpha)\n      .extract({ left: 20, top: 10, width: 380, height: 280 })\n      .rotate(45)\n      .jpeg()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(467, info.width);\n        assert.strictEqual(467, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract-rotate-45.jpg'), data, done);\n      });\n  });\n\n  it('Rotate then extract non-90 angle', (_t, done) => {\n    sharp(fixtures.inputPngWithGreyAlpha)\n      .rotate(45)\n      .extract({ left: 20, top: 10, width: 380, height: 280 })\n      .jpeg()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(380, info.width);\n        assert.strictEqual(280, info.height);\n        fixtures.assertSimilar(fixtures.expected('rotate-extract-45.jpg'), data, done);\n      });\n  });\n\n  describe('Apply exif orientation and mirroring then extract', () => {\n    [\n      {\n        name: 'EXIF-1',\n        image: fixtures.inputJpgWithLandscapeExif1\n      },\n      {\n        name: 'EXIF-2',\n        image: fixtures.inputJpgWithLandscapeExif2\n      },\n      {\n        name: 'EXIF-3',\n        image: fixtures.inputJpgWithLandscapeExif3\n      },\n      {\n        name: 'EXIF-4',\n        image: fixtures.inputJpgWithLandscapeExif4\n      },\n      {\n        name: 'EXIF-5',\n        image: fixtures.inputJpgWithLandscapeExif5\n      },\n      {\n        name: 'EXIF-6',\n        image: fixtures.inputJpgWithLandscapeExif6\n      },\n      {\n        name: 'EXIF-7',\n        image: fixtures.inputJpgWithLandscapeExif7\n      },\n      {\n        name: 'EXIF-8',\n        image: fixtures.inputJpgWithLandscapeExif8\n      }\n    ].forEach(({ name, image }) => {\n      it(name, (_t, done) => {\n        sharp(image)\n          .rotate()\n          .extract({ left: 0, top: 208, width: 60, height: 40 })\n          .toBuffer((err, data) => {\n            if (err) throw err;\n            fixtures.assertSimilar(fixtures.expected('rotate-mirror-extract.jpg'), data, done);\n          });\n      });\n    });\n  });\n\n  describe('Invalid parameters', () => {\n    describe('using the legacy extract(top,left,width,height) syntax', () => {\n      it('String top', () => {\n        assert.throws(() => {\n          sharp(fixtures.inputJpg).extract('spoons', 10, 10, 10);\n        });\n      });\n\n      it('Non-integral left', () => {\n        assert.throws(() => {\n          sharp(fixtures.inputJpg).extract(10, 10.2, 10, 10);\n        });\n      });\n\n      it('Negative width - negative', () => {\n        assert.throws(() => {\n          sharp(fixtures.inputJpg).extract(10, 10, -10, 10);\n        });\n      });\n\n      it('Null height', () => {\n        assert.throws(() => {\n          sharp(fixtures.inputJpg).extract(10, 10, 10, null);\n        });\n      });\n    });\n\n    it('Undefined', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg).extract();\n      });\n    });\n\n    it('String top', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg).extract({ left: 10, top: 'spoons', width: 10, height: 10 });\n      });\n    });\n\n    it('Non-integral left', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg).extract({ left: 10.2, top: 10, width: 10, height: 10 });\n      });\n    });\n\n    it('Negative width - negative', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg).extract({ left: 10, top: 10, width: -10, height: 10 });\n      });\n    });\n\n    it('Null height', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg).extract({ left: 10, top: 10, width: 10, height: null });\n      });\n    });\n\n    it('Bad image area', (_t, done) => {\n      sharp(fixtures.inputJpg)\n        .extract({ left: 3000, top: 10, width: 10, height: 10 })\n        .toBuffer((err) => {\n          assert(err instanceof Error);\n          assert.strictEqual(err.message, 'extract_area: bad extract area');\n          done();\n        });\n    });\n\n    it('Multiple extract emits warning', () => {\n      let warningMessage = '';\n      const s = sharp();\n      s.on('warning', (msg) => { warningMessage = msg; });\n      const options = { top: 0, left: 0, width: 1, height: 1 };\n      s.extract(options).extract(options);\n      assert.strictEqual(warningMessage, '');\n      s.extract(options);\n      assert.strictEqual(warningMessage, 'ignoring previous extract options');\n    });\n\n    it('Multiple rotate+extract emits warning', () => {\n      let warningMessage = '';\n      const s = sharp().rotate();\n      s.on('warning', (msg) => { warningMessage = msg; });\n      const options = { top: 0, left: 0, width: 1, height: 1 };\n      s.extract(options).extract(options);\n      assert.strictEqual(warningMessage, '');\n      s.extract(options);\n      assert.strictEqual(warningMessage, 'ignoring previous extract options');\n    });\n\n    it('Multiple extract+resize emits warning', () => {\n      let warningMessage = '';\n      const s = sharp();\n      s.on('warning', (msg) => { warningMessage = msg; });\n      const options = { top: 0, left: 0, width: 1, height: 1 };\n      s.extract(options).extract(options);\n      assert.strictEqual(warningMessage, '');\n      s.resize(1);\n      assert.strictEqual(warningMessage, 'operation order will be: extract, resize, extract');\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/extractChannel.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Image channel extraction', () => {\n  it('Red channel', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .extractChannel('red')\n      .resize(320, 240)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract-red.jpg'), data, done);\n      });\n  });\n\n  it('Green channel', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .extractChannel('green')\n      .resize(320, 240)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract-green.jpg'), data, done);\n      });\n  });\n\n  it('Blue channel', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .extractChannel('blue')\n      .resize(320, 240)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract-blue.jpg'), data, done);\n      });\n  });\n\n  it('Blue channel by number', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .extractChannel(2)\n      .resize(320, 240)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('extract-blue.jpg'), data, done);\n      });\n  });\n\n  it('With colorspace conversion', async () => {\n    const [chroma] = await sharp({ create: { width: 1, height: 1, channels: 3, background: 'red' } })\n      .toColourspace('lch')\n      .extractChannel(1)\n      .toBuffer();\n\n    assert.strictEqual(chroma, 104);\n  });\n\n  it('Alpha from 16-bit PNG', (_t, done) => {\n    const output = fixtures.path('output.extract-alpha-16bit.png');\n    sharp(fixtures.inputPngWithTransparency16bit)\n      .resize(16)\n      .extractChannel(3)\n      .toFile(output, (err) => {\n        if (err) throw err;\n        fixtures.assertMaxColourDistance(output, fixtures.expected('extract-alpha-16bit.png'));\n        done();\n      });\n  });\n\n  it('Alpha from 2-channel input', (_t, done) => {\n    const output = fixtures.path('output.extract-alpha-2-channel.png');\n    sharp(fixtures.inputPngWithGreyAlpha)\n      .extractChannel('alpha')\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual(1, info.channels);\n        fixtures.assertMaxColourDistance(output, fixtures.expected('extract-alpha-2-channel.png'));\n        done();\n      });\n  });\n\n  it('Invalid channel number', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg)\n        .extractChannel(-1);\n    });\n  });\n\n  it('No arguments', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg)\n        .extractChannel();\n    });\n  });\n\n  it('Non-existent channel', async () =>\n    await assert.rejects(\n      () => sharp({ create: { width: 1, height: 1, channels: 3, background: 'red' } })\n        .extractChannel(3)\n        .toBuffer(),\n      /Cannot extract channel 3 from image with channels 0-2/\n    )\n  );\n});\n"
  },
  {
    "path": "test/unit/failOn.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\nconst fs = require('node:fs');\n\nconst sharp = require('../../lib');\nconst fixtures = require('../fixtures');\n\ndescribe('failOn', () => {\n  it('handles truncated JPEG', (_t, done) => {\n    sharp(fixtures.inputJpgTruncated, { failOn: 'none' })\n      .resize(32, 24)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(32, info.width);\n        assert.strictEqual(24, info.height);\n        fixtures.assertSimilar(fixtures.expected('truncated.jpg'), data, done);\n      });\n  });\n\n  it('handles truncated PNG, emits warnings', (_t, done) => {\n    let isWarningEmitted = false;\n    sharp(fixtures.inputPngTruncated, { failOn: 'none' })\n      .on('warning', (warning) => {\n        assert.ok(\n          ['read gave 2 warnings', 'not enough data', 'end of stream']\n            .some(m => warning.includes(m)));\n        isWarningEmitted = true;\n      })\n      .resize(32, 24)\n      .toBuffer((err, _data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, isWarningEmitted);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(32, info.width);\n        assert.strictEqual(24, info.height);\n        done();\n      });\n  });\n\n  it('throws for invalid options', () => {\n    assert.throws(\n      () => sharp({ failOn: 'zoinks' }),\n      /Expected one of: none, truncated, error, warning for failOn but received zoinks of type string/\n    );\n    assert.throws(\n      () => sharp({ failOn: 1 }),\n      /Expected one of: none, truncated, error, warning for failOn but received 1 of type number/\n    );\n  });\n\n  it('deprecated failOnError', () => {\n    assert.doesNotThrow(\n      () => sharp({ failOnError: true })\n    );\n    assert.doesNotThrow(\n      () => sharp({ failOnError: false })\n    );\n    assert.throws(\n      () => sharp({ failOnError: 'zoinks' }),\n      /Expected boolean for failOnError but received zoinks of type string/\n    );\n    assert.throws(\n      () => sharp({ failOnError: 1 }),\n      /Expected boolean for failOnError but received 1 of type number/\n    );\n  });\n\n  it('returns errors to callback for truncated JPEG', (_t, done) => {\n    sharp(fixtures.inputJpgTruncated, { failOn: 'truncated' }).toBuffer((err, data, info) => {\n      assert.ok(err.message.includes('VipsJpeg: premature end of'), err);\n      assert.strictEqual(data, undefined);\n      assert.strictEqual(info, undefined);\n      done();\n    });\n  });\n\n  it('returns errors to callback for truncated PNG', (_t, done) => {\n    sharp(fixtures.inputPngTruncated, { failOn: 'truncated' }).toBuffer((err, data, info) => {\n      assert.ok(err.message.includes('read error'), err);\n      assert.strictEqual(data, undefined);\n      assert.strictEqual(info, undefined);\n      done();\n    });\n  });\n\n  it('rejects promises for truncated JPEG', (_t, done) => {\n    sharp(fixtures.inputJpgTruncated, { failOn: 'error' })\n      .toBuffer()\n      .then(() => {\n        throw new Error('Expected rejection');\n      })\n      .catch(err => {\n        done(err.message.includes('VipsJpeg: premature end of') ? undefined : err);\n      });\n  });\n\n  it('handles stream-based input', async () => {\n    const writable = sharp({ failOn: 'none' }).resize(32, 24);\n    fs.createReadStream(fixtures.inputJpgTruncated).pipe(writable);\n    return writable.toBuffer();\n  });\n\n  it('converts warnings to error for GeoTIFF', async () => {\n    await assert.rejects(\n      sharp(fixtures.inputTiffGeo).toBuffer(),\n      /Tag 34737/\n    );\n  });\n});\n"
  },
  {
    "path": "test/unit/fixtures.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\nconst fixtures = require('../fixtures');\n\ndescribe('Test fixtures', () => {\n  describe('assertMaxColourDistance', () => {\n    it('should throw an Error when images have a different number of channels', () => {\n      assert.throws(() => {\n        fixtures.assertMaxColourDistance(fixtures.inputPngOverlayLayer1, fixtures.inputJpg);\n      });\n    });\n    it('should throw an Error when images have different dimensions', () => {\n      assert.throws(() => {\n        fixtures.assertMaxColourDistance(fixtures.inputJpg, fixtures.inputJpgWithExif);\n      });\n    });\n    it('should accept a zero threshold when comparing an image to itself', () => {\n      const image = fixtures.inputPngOverlayLayer0;\n      fixtures.assertMaxColourDistance(image, image, 0);\n    });\n    it('should accept a numeric threshold for two different images', () => {\n      fixtures.assertMaxColourDistance(fixtures.inputPngOverlayLayer0, fixtures.inputPngOverlayLayer1, 100);\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/gamma.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Gamma correction', () => {\n  it('value of 0.0 (disabled)', (_t, done) => {\n    sharp(fixtures.inputJpgWithGammaHoliness)\n      .resize(129, 111)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(129, info.width);\n        assert.strictEqual(111, info.height);\n        fixtures.assertSimilar(fixtures.expected('gamma-0.0.jpg'), data, { threshold: 9 }, done);\n      });\n  });\n\n  it('value of 2.2 (default)', (_t, done) => {\n    sharp(fixtures.inputJpgWithGammaHoliness)\n      .resize(129, 111)\n      .gamma()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(129, info.width);\n        assert.strictEqual(111, info.height);\n        fixtures.assertSimilar(fixtures.expected('gamma-2.2.jpg'), data, done);\n      });\n  });\n\n  it('value of 3.0', (_t, done) => {\n    sharp(fixtures.inputJpgWithGammaHoliness)\n      .resize(129, 111)\n      .gamma(3)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(129, info.width);\n        assert.strictEqual(111, info.height);\n        fixtures.assertSimilar(fixtures.expected('gamma-3.0.jpg'), data, { threshold: 6 }, done);\n      });\n  });\n\n  it('input value of 2.2, output value of 3.0', (_t, done) => {\n    sharp(fixtures.inputJpgWithGammaHoliness)\n      .resize(129, 111)\n      .gamma(2.2, 3.0)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(129, info.width);\n        assert.strictEqual(111, info.height);\n        fixtures.assertSimilar(fixtures.expected('gamma-in-2.2-out-3.0.jpg'), data, { threshold: 6 }, done);\n      });\n  });\n\n  it('alpha transparency', (_t, done) => {\n    sharp(fixtures.inputPngOverlayLayer1)\n      .resize(320)\n      .gamma()\n      .jpeg()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        fixtures.assertSimilar(fixtures.expected('gamma-alpha.jpg'), data, done);\n      });\n  });\n\n  it('invalid first parameter value', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpgWithGammaHoliness).gamma(4);\n    });\n  });\n\n  it('invalid second parameter value', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpgWithGammaHoliness).gamma(2.2, 4);\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/gif.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('GIF input', () => {\n  it('GIF Buffer to JPEG Buffer', () =>\n    sharp(fs.readFileSync(fixtures.inputGif))\n      .resize(8, 4)\n      .jpeg()\n      .toBuffer({ resolveWithObject: true })\n      .then(({ data, info }) => {\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(8, info.width);\n        assert.strictEqual(4, info.height);\n      })\n  );\n\n  it('2 channel GIF file to PNG Buffer', () =>\n    sharp(fixtures.inputGifGreyPlusAlpha)\n      .resize(8, 4)\n      .png()\n      .toBuffer({ resolveWithObject: true })\n      .then(({ data, info }) => {\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(8, info.width);\n        assert.strictEqual(4, info.height);\n        assert.strictEqual(4, info.channels);\n      })\n  );\n\n  it('Animated GIF first page to non-animated GIF', () =>\n    sharp(fixtures.inputGifAnimated)\n      .toBuffer({ resolveWithObject: true })\n      .then(({ data, info }) => {\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('gif', info.format);\n        assert.strictEqual(80, info.width);\n        assert.strictEqual(80, info.height);\n        assert.strictEqual(4, info.channels);\n        assert.strictEqual(undefined, info.pages);\n        assert.strictEqual(undefined, info.pageHeight);\n      })\n  );\n\n  it('Animated GIF round trip', () =>\n    sharp(fixtures.inputGifAnimated, { pages: -1 })\n      .toBuffer({ resolveWithObject: true })\n      .then(({ data, info }) => {\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('gif', info.format);\n        assert.strictEqual(80, info.width);\n        assert.strictEqual(2400, info.height);\n        assert.strictEqual(4, info.channels);\n        assert.strictEqual(30, info.pages);\n        assert.strictEqual(80, info.pageHeight);\n      })\n  );\n\n  it('GIF with reduced colours, no dither, low effort reduces file size', async () => {\n    const original = await sharp(fixtures.inputJpg)\n      .resize(120, 80)\n      .gif()\n      .toBuffer();\n\n    const reduced = await sharp(fixtures.inputJpg)\n      .resize(120, 80)\n      .gif({\n        colours: 128,\n        dither: 0,\n        effort: 1\n      })\n      .toBuffer();\n\n    assert.strictEqual(true, reduced.length < original.length);\n  });\n\n  it('valid reuse', () => {\n    assert.doesNotThrow(() => sharp().gif({ reuse: true }));\n    assert.doesNotThrow(() => sharp().gif({ reuse: false }));\n  });\n\n  it('invalid reuse throws', () => {\n    assert.throws(\n      () => sharp().gif({ reuse: -1 }),\n      /Expected boolean for gifReuse but received -1 of type number/\n    );\n    assert.throws(\n      () => sharp().gif({ reuse: 'fail' }),\n      /Expected boolean for gifReuse but received fail of type string/\n    );\n  });\n\n  it('progressive changes file size', async () => {\n    const nonProgressive = await sharp(fixtures.inputGif).gif({ progressive: false }).toBuffer();\n    const progressive = await sharp(fixtures.inputGif).gif({ progressive: true }).toBuffer();\n    assert(nonProgressive.length !== progressive.length);\n  });\n\n  it('invalid progressive throws', () => {\n    assert.throws(\n      () => sharp().gif({ progressive: -1 }),\n      /Expected boolean for gifProgressive but received -1 of type number/\n    );\n    assert.throws(\n      () => sharp().gif({ progressive: 'fail' }),\n      /Expected boolean for gifProgressive but received fail of type string/\n    );\n  });\n\n  it('invalid loop throws', () => {\n    assert.throws(() => {\n      sharp().gif({ loop: -1 });\n    });\n    assert.throws(() => {\n      sharp().gif({ loop: 65536 });\n    });\n  });\n\n  it('invalid delay throws', () => {\n    assert.throws(() => {\n      sharp().gif({ delay: -1 });\n    });\n    assert.throws(() => {\n      sharp().gif({ delay: [65536] });\n    });\n  });\n\n  it('invalid colour throws', () => {\n    assert.throws(() => {\n      sharp().gif({ colours: 1 });\n    });\n    assert.throws(() => {\n      sharp().gif({ colours: 'fail' });\n    });\n  });\n\n  it('invalid effort throws', () => {\n    assert.throws(() => {\n      sharp().gif({ effort: 0 });\n    });\n    assert.throws(() => {\n      sharp().gif({ effort: 'fail' });\n    });\n  });\n\n  it('invalid dither throws', () => {\n    assert.throws(() => {\n      sharp().gif({ dither: 1.1 });\n    });\n    assert.throws(() => {\n      sharp().gif({ effort: 'fail' });\n    });\n  });\n\n  it('invalid interFrameMaxError throws', () => {\n    assert.throws(\n      () => sharp().gif({ interFrameMaxError: 33 }),\n      /Expected number between 0.0 and 32.0 for interFrameMaxError but received 33 of type number/\n    );\n    assert.throws(\n      () => sharp().gif({ interFrameMaxError: 'fail' }),\n      /Expected number between 0.0 and 32.0 for interFrameMaxError but received fail of type string/\n    );\n  });\n\n  it('invalid interPaletteMaxError throws', () => {\n    assert.throws(\n      () => sharp().gif({ interPaletteMaxError: 257 }),\n      /Expected number between 0.0 and 256.0 for interPaletteMaxError but received 257 of type number/\n    );\n    assert.throws(\n      () => sharp().gif({ interPaletteMaxError: 'fail' }),\n      /Expected number between 0.0 and 256.0 for interPaletteMaxError but received fail of type string/\n    );\n  });\n\n  it('invalid keepDuplicateFrames throws', () => {\n    assert.throws(\n      () => sharp().gif({ keepDuplicateFrames: -1 }),\n      /Expected boolean for keepDuplicateFrames but received -1 of type number/\n    );\n    assert.throws(\n      () => sharp().gif({ keepDuplicateFrames: 'fail' }),\n      /Expected boolean for keepDuplicateFrames but received fail of type string/\n    );\n  });\n\n  it('should work with streams when only animated is set', (_t, done) => {\n    fs.createReadStream(fixtures.inputGifAnimated)\n      .pipe(sharp({ animated: true }))\n      .gif()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('gif', info.format);\n        fixtures.assertSimilar(fixtures.inputGifAnimated, data, done);\n      });\n  });\n\n  it('should work with streams when only pages is set', (_t, done) => {\n    fs.createReadStream(fixtures.inputGifAnimated)\n      .pipe(sharp({ pages: -1 }))\n      .gif()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('gif', info.format);\n        fixtures.assertSimilar(fixtures.inputGifAnimated, data, done);\n      });\n  });\n\n  it('should optimise file size via interFrameMaxError', async () => {\n    const input = sharp(fixtures.inputGifAnimated, { animated: true });\n    const before = await input.gif({ interFrameMaxError: 0 }).toBuffer();\n    const after = await input.gif({ interFrameMaxError: 10 }).toBuffer();\n    assert.strict(before.length > after.length);\n  });\n\n  it('should optimise file size via interPaletteMaxError', async () => {\n    const input = sharp(fixtures.inputGifAnimated, { animated: true });\n    const before = await input.gif({ interPaletteMaxError: 0 }).toBuffer();\n    const after = await input.gif({ interPaletteMaxError: 100 }).toBuffer();\n    assert.strict(before.length > after.length);\n  });\n\n  it('should keep duplicate frames via keepDuplicateFrames', async () => {\n    const create = { width: 8, height: 8, channels: 4, background: 'blue' };\n    const input = sharp([{ create }, { create }], { join: { animated: true } });\n\n    const before = await input.gif({ keepDuplicateFrames: false }).toBuffer();\n    const after = await input.gif({ keepDuplicateFrames: true }).toBuffer();\n    assert.strict(before.length < after.length);\n\n    const beforeMeta = await sharp(before).metadata();\n    const afterMeta = await sharp(after).metadata();\n    assert.strictEqual(beforeMeta.pages, 1);\n    assert.strictEqual(afterMeta.pages, 2);\n  });\n\n  it('non-animated input defaults to no-loop', async () => {\n    for (const input of [fixtures.inputGif, fixtures.inputPng]) {\n      const data = await sharp(input)\n        .resize(8)\n        .gif({ effort: 1 })\n        .toBuffer();\n\n      const { format, pages, loop } = await sharp(data).metadata();\n      assert.strictEqual('gif', format);\n      assert.strictEqual(1, pages);\n      assert.strictEqual(1, loop);\n    }\n  });\n\n  it('Animated GIF to animated WebP merges identical frames', async () => {\n    const webp = await sharp(fixtures.inputGifAnimated, { animated: true })\n      .webp()\n      .toBuffer();\n\n    const { delay, loop, pages } = await sharp(webp).metadata();\n    assert.deepStrictEqual([120, 120, 90, 120, 120, 90, 120, 90, 30], delay);\n    assert.strictEqual(0, loop);\n    assert.strictEqual(9, pages);\n  });\n});\n"
  },
  {
    "path": "test/unit/heif.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\n\ndescribe('HEIF', () => {\n  it('called without options throws an error', () => {\n    assert.throws(() => {\n      sharp().heif();\n    });\n  });\n  it('valid quality does not throw an error', () => {\n    assert.doesNotThrow(() => {\n      sharp().heif({ compression: 'av1', quality: 80 });\n    });\n  });\n  it('invalid quality should throw an error', () => {\n    assert.throws(() => {\n      sharp().heif({ compression: 'av1', quality: 101 });\n    });\n  });\n  it('non-numeric quality should throw an error', () => {\n    assert.throws(() => {\n      sharp().heif({ compression: 'av1', quality: 'fail' });\n    });\n  });\n  it('valid lossless does not throw an error', () => {\n    assert.doesNotThrow(() => {\n      sharp().heif({ compression: 'av1', lossless: true });\n    });\n  });\n  it('non-boolean lossless should throw an error', () => {\n    assert.throws(() => {\n      sharp().heif({ compression: 'av1', lossless: 'fail' });\n    });\n  });\n  it('valid compression does not throw an error', () => {\n    assert.doesNotThrow(() => {\n      sharp().heif({ compression: 'hevc' });\n    });\n  });\n  it('unknown compression should throw an error', () => {\n    assert.throws(() => {\n      sharp().heif({ compression: 'fail' });\n    });\n  });\n  it('invalid compression should throw an error', () => {\n    assert.throws(() => {\n      sharp().heif({ compression: 1 });\n    });\n  });\n  it('valid effort does not throw an error', () => {\n    assert.doesNotThrow(() => {\n      sharp().heif({ compression: 'av1', effort: 6 });\n    });\n  });\n  it('out of range effort should throw an error', () => {\n    assert.throws(() => {\n      sharp().heif({ compression: 'av1', effort: 10 });\n    });\n  });\n  it('invalid effort should throw an error', () => {\n    assert.throws(() => {\n      sharp().heif({ compression: 'av1', effort: 'fail' });\n    });\n  });\n  it('invalid chromaSubsampling should throw an error', () => {\n    assert.throws(() => {\n      sharp().heif({ compression: 'av1', chromaSubsampling: 'fail' });\n    });\n  });\n  it('valid chromaSubsampling does not throw an error', () => {\n    assert.doesNotThrow(() => {\n      sharp().heif({ compression: 'av1', chromaSubsampling: '4:4:4' });\n    });\n  });\n  it('valid bitdepth value does not throw an error', () => {\n    const { heif } = sharp.versions;\n    delete sharp.versions.heif;\n    assert.doesNotThrow(() => {\n      sharp().heif({ compression: 'av1', bitdepth: 12 });\n    });\n    sharp.versions.heif = '1.2.3';\n    assert.throws(() => {\n      sharp().heif({ compression: 'av1', bitdepth: 10 });\n    }, /Error: Expected 8 for bitdepth when using prebuilt binaries but received 10 of type number/);\n    sharp.versions.heif = heif;\n  });\n  it('invalid bitdepth value should throw an error', () => {\n    assert.throws(() => {\n      sharp().heif({ compression: 'av1', bitdepth: 11 });\n    }, /Error: Expected 8, 10 or 12 for bitdepth but received 11 of type number/);\n  });\n});\n"
  },
  {
    "path": "test/unit/io.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst path = require('node:path');\nconst { afterEach, beforeEach, describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\nconst outputJpg = fixtures.path('output.jpg');\n\ndescribe('Input/output', () => {\n  beforeEach(() => {\n    sharp.cache(false);\n  });\n  afterEach(() => {\n    sharp.cache(true);\n  });\n\n  it('Read from File and write to Stream', (_t, done) => {\n    const writable = fs.createWriteStream(outputJpg);\n    writable.on('close', () => {\n      sharp(outputJpg).toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fs.rm(outputJpg, done);\n      });\n    });\n    sharp(fixtures.inputJpg).resize(320, 240).pipe(writable);\n  });\n\n  it('Read from Buffer and write to Stream', (_t, done) => {\n    const inputJpgBuffer = fs.readFileSync(fixtures.inputJpg);\n    const writable = fs.createWriteStream(outputJpg);\n    writable.on('close', () => {\n      sharp(outputJpg).toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fs.rm(outputJpg, done);\n      });\n    });\n    sharp(inputJpgBuffer).resize(320, 240).pipe(writable);\n  });\n\n  it('Read from Stream and write to File', (_t, done) => {\n    const readable = fs.createReadStream(fixtures.inputJpg);\n    const pipeline = sharp().resize(320, 240).toFile(outputJpg, (err, info) => {\n      if (err) throw err;\n      assert.strictEqual(true, info.size > 0);\n      assert.strictEqual('jpeg', info.format);\n      assert.strictEqual(320, info.width);\n      assert.strictEqual(240, info.height);\n      fs.rm(outputJpg, done);\n    });\n    readable.pipe(pipeline);\n  });\n\n  it('Read from Stream and write to Buffer', (_t, done) => {\n    const readable = fs.createReadStream(fixtures.inputJpg);\n    const pipeline = sharp().resize(320, 240).toBuffer((err, data, info) => {\n      if (err) throw err;\n      assert.strictEqual(true, data.length > 0);\n      assert.strictEqual(data.length, info.size);\n      assert.strictEqual('jpeg', info.format);\n      assert.strictEqual(320, info.width);\n      assert.strictEqual(240, info.height);\n      done();\n    });\n    readable.pipe(pipeline);\n  });\n\n  it('Read from Stream and write to Buffer via Promise resolved with Buffer', () => {\n    const pipeline = sharp().resize(1, 1);\n    fs.createReadStream(fixtures.inputJpg).pipe(pipeline);\n    return pipeline\n      .toBuffer({ resolveWithObject: false })\n      .then((data) => {\n        assert.strictEqual(true, data instanceof Buffer);\n        assert.strictEqual(true, data.length > 0);\n      });\n  });\n\n  it('Read from Stream and write to Buffer via Promise resolved with Object', () => {\n    const pipeline = sharp().resize(1, 1);\n    fs.createReadStream(fixtures.inputJpg).pipe(pipeline);\n    return pipeline\n      .toBuffer({ resolveWithObject: true })\n      .then((object) => {\n        assert.strictEqual('object', typeof object);\n        assert.strictEqual('object', typeof object.info);\n        assert.strictEqual('jpeg', object.info.format);\n        assert.strictEqual(1, object.info.width);\n        assert.strictEqual(1, object.info.height);\n        assert.strictEqual(3, object.info.channels);\n        assert.strictEqual(true, object.data instanceof Buffer);\n        assert.strictEqual(true, object.data.length > 0);\n      });\n  });\n\n  it('Read from File and write to Buffer via Promise resolved with Buffer', () => sharp(fixtures.inputJpg)\n      .resize(1, 1)\n      .toBuffer({ resolveWithObject: false })\n      .then((data) => {\n        assert.strictEqual(true, data instanceof Buffer);\n        assert.strictEqual(true, data.length > 0);\n      }));\n\n  it('Read from File and write to Buffer via Promise resolved with Object', () => sharp(fixtures.inputJpg)\n      .resize(1, 1)\n      .toBuffer({ resolveWithObject: true })\n      .then((object) => {\n        assert.strictEqual('object', typeof object);\n        assert.strictEqual('object', typeof object.info);\n        assert.strictEqual('jpeg', object.info.format);\n        assert.strictEqual(1, object.info.width);\n        assert.strictEqual(1, object.info.height);\n        assert.strictEqual(3, object.info.channels);\n        assert.strictEqual(true, object.data instanceof Buffer);\n        assert.strictEqual(true, object.data.length > 0);\n      }));\n\n  it('Read from Stream and write to Stream', (_t, done) => {\n    const readable = fs.createReadStream(fixtures.inputJpg);\n    const writable = fs.createWriteStream(outputJpg);\n    writable.on('close', () => {\n      sharp(outputJpg).toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fs.rm(outputJpg, done);\n      });\n    });\n    const pipeline = sharp().resize(320, 240);\n    readable.pipe(pipeline).pipe(writable);\n  });\n\n  it('Read from ArrayBuffer and write to Buffer', async () => {\n    const uint8array = Uint8Array.from([255, 255, 255, 0, 0, 0]);\n    const arrayBuffer = new ArrayBuffer(uint8array.byteLength);\n    new Uint8Array(arrayBuffer).set(uint8array);\n    const { data, info } = await sharp(arrayBuffer, {\n      raw: {\n        width: 2,\n        height: 1,\n        channels: 3\n      }\n    }).toBuffer({ resolveWithObject: true });\n\n    assert.deepStrictEqual(uint8array, new Uint8Array(data));\n    assert.strictEqual(info.width, 2);\n    assert.strictEqual(info.height, 1);\n  });\n\n  it('Read from Uint8Array and write to Buffer', async () => {\n    const uint8array = Uint8Array.from([255, 255, 255, 0, 0, 0]);\n    const { data, info } = await sharp(uint8array, {\n      raw: {\n        width: 2,\n        height: 1,\n        channels: 3\n      }\n    }).toBuffer({ resolveWithObject: true });\n\n    assert.deepStrictEqual(uint8array, new Uint8Array(data));\n    assert.strictEqual(info.width, 2);\n    assert.strictEqual(info.height, 1);\n  });\n\n  it('Read from Uint8ClampedArray and output to Buffer', async () => {\n    // since a Uint8ClampedArray is the same as Uint8Array but clamps the values\n    // between 0-255 it seemed good to add this also\n    const uint8array = Uint8ClampedArray.from([255, 255, 255, 0, 0, 0]);\n    const { data, info } = await sharp(uint8array, {\n      raw: {\n        width: 2,\n        height: 1,\n        channels: 3\n      }\n    }).toBuffer({ resolveWithObject: true });\n\n    assert.deepStrictEqual(uint8array, new Uint8ClampedArray(data));\n    assert.strictEqual(info.width, 2);\n    assert.strictEqual(info.height, 1);\n  });\n\n  it('Read from Uint8ClampedArray with byteOffset and output to Buffer', async () => {\n    // since a Uint8ClampedArray is the same as Uint8Array but clamps the values\n    // between 0-255 it seemed good to add this also\n    const uint8array = Uint8ClampedArray.from([0, 0, 0, 255, 255, 255, 0, 0, 0, 255, 255, 255]);\n    const uint8ArrayWithByteOffset = new Uint8ClampedArray(uint8array.buffer, 3, 6);\n    const { data, info } = await sharp(uint8ArrayWithByteOffset, {\n      raw: {\n        width: 2,\n        height: 1,\n        channels: 3\n      }\n    }).toBuffer({ resolveWithObject: true });\n\n    assert.deepStrictEqual(Uint8ClampedArray.from([255, 255, 255, 0, 0, 0]), new Uint8ClampedArray(data));\n    assert.strictEqual(info.width, 2);\n    assert.strictEqual(info.height, 1);\n  });\n\n  it('Stream should emit info event', (_t, done) => {\n    const readable = fs.createReadStream(fixtures.inputJpg);\n    const writable = fs.createWriteStream(outputJpg);\n    const pipeline = sharp().resize(320, 240);\n    let infoEventEmitted = false;\n    pipeline.on('info', (info) => {\n      assert.strictEqual('jpeg', info.format);\n      assert.strictEqual(320, info.width);\n      assert.strictEqual(240, info.height);\n      assert.strictEqual(3, info.channels);\n      infoEventEmitted = true;\n    });\n    writable.on('close', () => {\n      assert.strictEqual(true, infoEventEmitted);\n      fs.rm(outputJpg, done);\n    });\n    readable.pipe(pipeline).pipe(writable);\n  });\n\n  it('Stream should emit close event', (_t, done) => {\n    const readable = fs.createReadStream(fixtures.inputJpg);\n    const writable = fs.createWriteStream(outputJpg);\n    const pipeline = sharp().resize(320, 240);\n    let closeEventEmitted = false;\n    pipeline.on('close', () => {\n      closeEventEmitted = true;\n    });\n    writable.on('close', () => {\n      assert.strictEqual(true, closeEventEmitted);\n      fs.rm(outputJpg, done);\n    });\n    readable.pipe(pipeline).pipe(writable);\n  });\n\n  it('Handle Stream to Stream error ', (_t, done) => {\n    const pipeline = sharp().resize(320, 240);\n    let anErrorWasEmitted = false;\n    pipeline.on('error', (err) => {\n      anErrorWasEmitted = !!err;\n    }).on('end', () => {\n      assert(anErrorWasEmitted);\n      fs.rm(outputJpg, done);\n    });\n    const readableButNotAnImage = fs.createReadStream(__filename);\n    const writable = fs.createWriteStream(outputJpg);\n    readableButNotAnImage.pipe(pipeline).pipe(writable);\n  });\n\n  it('Handle File to Stream error', (_t, done) => {\n    const readableButNotAnImage = sharp(__filename).resize(320, 240);\n    let anErrorWasEmitted = false;\n    readableButNotAnImage.on('error', (err) => {\n      anErrorWasEmitted = !!err;\n    }).on('end', () => {\n      assert(anErrorWasEmitted);\n      fs.rm(outputJpg, done);\n    });\n    const writable = fs.createWriteStream(outputJpg);\n    readableButNotAnImage.pipe(writable);\n  });\n\n  it('Readable side of Stream can start flowing after Writable side has finished', (_t, done) => {\n    const readable = fs.createReadStream(fixtures.inputJpg);\n    const writable = fs.createWriteStream(outputJpg);\n    writable.on('close', () => {\n      sharp(outputJpg).toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fs.rm(outputJpg, done);\n      });\n    });\n    const pipeline = sharp().resize(320, 240);\n    readable.pipe(pipeline);\n    pipeline.on('finish', () => {\n      pipeline.pipe(writable);\n    });\n  });\n\n  it('Non-Stream input generates error when provided Stream-like data', (_t, done) => {\n    sharp('input')._write('fail', null, (err) => {\n      assert.strictEqual(err.message, 'Unexpected data on Writable Stream');\n      done();\n    });\n  });\n\n  it('Non-Buffer chunk on Stream input generates error', (_t, done) => {\n    sharp()._write('fail', null, (err) => {\n      assert.strictEqual(err.message, 'Non-Buffer data on Writable Stream');\n      done();\n    });\n  });\n\n  it('Invalid sequential read option throws', () => {\n    assert.throws(() => {\n      sharp({ sequentialRead: 'fail' });\n    }, /Expected boolean for sequentialRead but received fail of type string/);\n  });\n\n  it('Sequential read, force JPEG', () =>\n    sharp(fixtures.inputJpg, { sequentialRead: true })\n      .resize(320, 240)\n      .toFormat(sharp.format.jpeg)\n      .toBuffer({ resolveWithObject: true })\n      .then(({ data, info }) => {\n        assert.strictEqual(data.length > 0, true);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual(info.format, 'jpeg');\n        assert.strictEqual(info.width, 320);\n        assert.strictEqual(info.height, 240);\n      })\n  );\n\n  it('Not sequential read, force JPEG', () =>\n    sharp(fixtures.inputJpg, { sequentialRead: false })\n      .resize(320, 240)\n      .toFormat('jpeg')\n      .toBuffer({ resolveWithObject: true })\n      .then(({ data, info }) => {\n        assert.strictEqual(data.length > 0, true);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual(info.format, 'jpeg');\n        assert.strictEqual(info.width, 320);\n        assert.strictEqual(info.height, 240);\n      })\n  );\n\n  it('Support output to jpg format', (_t, done) => {\n    sharp(fixtures.inputPng)\n      .resize(320, 240)\n      .toFormat('jpg')\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        done();\n      });\n  });\n\n  it('Support output to tif format', (_t, done) => {\n    sharp(fixtures.inputTiff)\n      .resize(320, 240)\n      .toFormat('tif')\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('tiff', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        done();\n      });\n  });\n\n  it('Allow use of toBuffer and toFile with same instance', async () => {\n    const instance = sharp({\n      create: {\n        width: 8,\n        height: 8,\n        channels: 3,\n        background: 'red'\n      }\n    });\n    await instance.toFile(fixtures.path('output.jpg'));\n    const data = await instance.toBuffer();\n    assert.strictEqual(Buffer.isBuffer(data), true);\n  });\n\n  it('Fail when output File is input File', (_t, done) => {\n    sharp(fixtures.inputJpg).toFile(fixtures.inputJpg, (err) => {\n      assert(err instanceof Error);\n      assert.strictEqual('Cannot use same file for input and output', err.message);\n      done();\n    });\n  });\n\n  it('Fail when output File is input File via Promise', (_t, done) => {\n    sharp(fixtures.inputJpg).toFile(fixtures.inputJpg).then(() => {\n      done(new Error('Unexpectedly resolved Promise'));\n    }).catch((err) => {\n      assert(err instanceof Error);\n      assert.strictEqual('Cannot use same file for input and output', err.message);\n      done();\n    });\n  });\n\n  it('Fail when output File is input File (relative output, absolute input)', (_t, done) => {\n    const relativePath = path.relative(process.cwd(), fixtures.inputJpg);\n    sharp(fixtures.inputJpg).toFile(relativePath, (err) => {\n      assert(err instanceof Error);\n      assert.strictEqual('Cannot use same file for input and output', err.message);\n      done();\n    });\n  });\n\n  it('Fail when output File is input File via Promise (relative output, absolute input)', (_t, done) => {\n    const relativePath = path.relative(process.cwd(), fixtures.inputJpg);\n    sharp(fixtures.inputJpg).toFile(relativePath).then(() => {\n      done(new Error('Unexpectedly resolved Promise'));\n    }).catch((err) => {\n      assert(err instanceof Error);\n      assert.strictEqual('Cannot use same file for input and output', err.message);\n      done();\n    });\n  });\n\n  it('Fail when output File is input File (relative input, absolute output)', (_t, done) => {\n    const relativePath = path.relative(process.cwd(), fixtures.inputJpg);\n    sharp(relativePath).toFile(fixtures.inputJpg, (err) => {\n      assert(err instanceof Error);\n      assert.strictEqual('Cannot use same file for input and output', err.message);\n      done();\n    });\n  });\n\n  it('Fail when output File is input File via Promise (relative input, absolute output)', (_t, done) => {\n    const relativePath = path.relative(process.cwd(), fixtures.inputJpg);\n    sharp(relativePath).toFile(fixtures.inputJpg).then(() => {\n      done(new Error('Unexpectedly resolved Promise'));\n    }).catch((err) => {\n      assert(err instanceof Error);\n      assert.strictEqual('Cannot use same file for input and output', err.message);\n      done();\n    });\n  });\n\n  it('Fail when output File is empty', (_t, done) => {\n    sharp(fixtures.inputJpg).toFile('', (err) => {\n      assert(err instanceof Error);\n      assert.strictEqual('Missing output file path', err.message);\n      done();\n    });\n  });\n\n  it('Fail when output File is empty via Promise', (_t, done) => {\n    sharp(fixtures.inputJpg).toFile('').then(() => {\n      done(new Error('Unexpectedly resolved Promise'));\n    }).catch((err) => {\n      assert(err instanceof Error);\n      assert.strictEqual('Missing output file path', err.message);\n      done();\n    });\n  });\n\n  it('Fail when input is invalid Buffer', async () =>\n    assert.rejects(\n      () => sharp(Buffer.from([0x1, 0x2, 0x3, 0x4])).toBuffer(),\n      (err) => {\n        assert.strictEqual(err.message, 'Input buffer contains unsupported image format');\n        assert(err.stack.includes('at Sharp.toBuffer'));\n        assert(err.stack.includes(__filename));\n        return true;\n      }\n    )\n  );\n\n  it('Fail when input file path is missing', async () =>\n    assert.rejects(\n      () => sharp('does-not-exist').toFile('fail'),\n      (err) => {\n        assert.strictEqual(err.message, 'Input file is missing: does-not-exist');\n        assert(err.stack.includes('at Sharp.toFile'));\n        assert(err.stack.includes(__filename));\n        return true;\n      }\n    )\n  );\n\n  describe('Fail for unsupported input', () => {\n    it('Undefined', () => {\n      assert.throws(() => {\n        sharp(undefined);\n      });\n    });\n    it('Null', () => {\n      assert.throws(() => {\n        sharp(null);\n      });\n    });\n    it('Numeric', () => {\n      assert.throws(() => {\n        sharp(1);\n      });\n    });\n    it('Boolean', () => {\n      assert.throws(() => {\n        sharp(true);\n      });\n    });\n    it('Error Object', () => {\n      assert.throws(() => {\n        sharp(new Error());\n      });\n    });\n  });\n\n  it('Promises/A+', () => sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .toBuffer());\n\n  it('Invalid output format', (_t, done) => {\n    let isValid = false;\n    try {\n      sharp().toFormat('zoinks');\n      isValid = true;\n    } catch (_err) {}\n    assert(!isValid);\n    done();\n  });\n\n  it('File input with corrupt header fails gracefully', (_t, done) => {\n    sharp(fixtures.inputJpgWithCorruptHeader)\n      .toBuffer((err) => {\n        assert.strictEqual(true, !!err);\n        done();\n      });\n  });\n\n  it('Buffer input with corrupt header fails gracefully', (_t, done) => {\n    sharp(fs.readFileSync(fixtures.inputJpgWithCorruptHeader))\n      .toBuffer((err) => {\n        assert.strictEqual(true, !!err);\n        done();\n      });\n  });\n\n  it('Stream input with corrupt header fails gracefully', (_t, done) => {\n    const transformer = sharp();\n    transformer\n      .toBuffer()\n      .then(() => {\n        done(new Error('Unexpectedly resolved Promise'));\n      })\n      .catch((err) => {\n        assert.strictEqual(true, !!err);\n        done();\n      });\n    fs\n      .createReadStream(fixtures.inputJpgWithCorruptHeader)\n      .pipe(transformer);\n  });\n\n  describe('Output filename with unknown extension', () => {\n    const outputZoinks = fixtures.path('output.zoinks');\n\n    it('Match JPEG input', (_t, done) => {\n      sharp(fixtures.inputJpg)\n        .resize(320, 80)\n        .toFile(outputZoinks, (err, info) => {\n          if (err) throw err;\n          assert.strictEqual(true, info.size > 0);\n          assert.strictEqual('jpeg', info.format);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80, info.height);\n          fs.rm(outputZoinks, done);\n        });\n    });\n\n    it('Match PNG input', (_t, done) => {\n      sharp(fixtures.inputPng)\n        .resize(320, 80)\n        .toFile(outputZoinks, (err, info) => {\n          if (err) throw err;\n          assert.strictEqual(true, info.size > 0);\n          assert.strictEqual('png', info.format);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80, info.height);\n          fs.rm(outputZoinks, done);\n        });\n    });\n\n    it('Match WebP input', (_t, done) => {\n      sharp(fixtures.inputWebP)\n        .resize(320, 80)\n        .toFile(outputZoinks, (err, info) => {\n          if (err) throw err;\n          assert.strictEqual(true, info.size > 0);\n          assert.strictEqual('webp', info.format);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80, info.height);\n          fs.rm(outputZoinks, done);\n        });\n    });\n\n    it('Match TIFF input', (_t, done) => {\n      sharp(fixtures.inputTiff)\n        .resize(320, 80)\n        .toFile(outputZoinks, (err, info) => {\n          if (err) throw err;\n          assert.strictEqual(true, info.size > 0);\n          assert.strictEqual('tiff', info.format);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80, info.height);\n          fs.rm(outputZoinks, done);\n        });\n    });\n\n    it('Force JPEG format for PNG input', (_t, done) => {\n      sharp(fixtures.inputPng)\n        .resize(320, 80)\n        .jpeg()\n        .toFile(outputZoinks, (err, info) => {\n          if (err) throw err;\n          assert.strictEqual(true, info.size > 0);\n          assert.strictEqual('jpeg', info.format);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80, info.height);\n          fs.rm(outputZoinks, done);\n        });\n    });\n  });\n\n  it('Input and output formats match when not forcing', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .png({ compressionLevel: 1, force: false })\n      .toBuffer((err, _data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        done();\n      });\n  });\n\n  it('Can force output format with output chaining', () => sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .png({ force: true })\n      .jpeg({ force: false })\n      .toBuffer({ resolveWithObject: true })\n      .then((out) => {\n        assert.strictEqual('png', out.info.format);\n      }));\n\n  it('toFormat=JPEG takes precedence over WebP extension', (_t, done) => {\n    const outputWebP = fixtures.path('output.webp');\n    sharp(fixtures.inputPng)\n      .resize(8)\n      .jpeg()\n      .toFile(outputWebP, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        fs.rm(outputWebP, done);\n      });\n  });\n\n  it('toFormat=WebP takes precedence over JPEG extension', (_t, done) => {\n    sharp(fixtures.inputPng)\n      .resize(8)\n      .webp()\n      .toFile(outputJpg, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('webp', info.format);\n        done();\n      });\n  });\n\n  it('Load Vips V file', (_t, done) => {\n    sharp(fixtures.inputV)\n      .jpeg()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(70, info.width);\n        assert.strictEqual(60, info.height);\n        fixtures.assertSimilar(fixtures.expected('vfile.jpg'), data, done);\n      });\n  });\n\n  it('Save Vips V file', (_t, done) => {\n    const outputV = fixtures.path('output.v');\n    sharp(fixtures.inputJpg)\n      .extract({ left: 910, top: 1105, width: 70, height: 60 })\n      .toFile(outputV, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, info.size > 0);\n        assert.strictEqual('v', info.format);\n        assert.strictEqual(70, info.width);\n        assert.strictEqual(60, info.height);\n        fs.rm(outputV, done);\n      });\n  });\n\n  it('can ignore ICC profile', async () => {\n    const [r1, g1, b1] = await sharp(fixtures.inputJpgWithPortraitExif5, { ignoreIcc: true })\n      .extract({ width: 1, height: 1, top: 16, left: 16 })\n      .raw()\n      .toBuffer();\n\n    const [r2, g2, b2] = await sharp(fixtures.inputJpgWithPortraitExif5, { ignoreIcc: false })\n      .extract({ width: 1, height: 1, top: 16, left: 16 })\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual({ r1, g1, b1, r2, g2, b2 }, {\n      r1: 60,\n      r2: 77,\n      g1: 54,\n      g2: 69,\n      b1: 20,\n      b2: 25\n    });\n  });\n\n  describe('Switch off safety limits for certain formats', () => {\n    it('Valid', () => {\n      assert.doesNotThrow(() => {\n        sharp({ unlimited: true });\n      });\n    });\n    it('Invalid', () => {\n      assert.throws(() => {\n        sharp({ unlimited: -1 });\n      }, /Expected boolean for unlimited but received -1 of type number/);\n    });\n  });\n\n  describe('Limit pixel count of input image', () => {\n    it('Invalid fails - negative', () => {\n      assert.throws(() => {\n        sharp({ limitInputPixels: -1 });\n      });\n    });\n\n    it('Invalid fails - float', () => {\n      assert.throws(() => {\n        sharp({ limitInputPixels: 12.3 });\n      });\n    });\n\n    it('Invalid fails - integer overflow', () => {\n      assert.throws(() => {\n        sharp({ limitInputPixels: Number.MAX_SAFE_INTEGER + 1 });\n      });\n    });\n\n    it('Invalid fails - string', () => {\n      assert.throws(() => {\n        sharp({ limitInputPixels: 'fail' });\n      });\n    });\n\n    it('Same size as input works', () =>\n      sharp(fixtures.inputJpg)\n        .metadata()\n        .then(({ width, height }) =>\n          sharp(fixtures.inputJpg, { limitInputPixels: width * height })\n            .resize(2)\n            .toBuffer()\n        )\n    );\n\n    it('Disabling limit works', () =>\n      sharp(fixtures.inputJpgLarge, { limitInputPixels: false })\n        .resize(2)\n        .toBuffer()\n    );\n\n    it('Enabling default limit works and fails with a large image', () =>\n      sharp(fixtures.inputJpgLarge, { limitInputPixels: true })\n        .toBuffer()\n        .then(() => {\n          assert.fail('Expected to fail');\n        })\n        .catch(err => {\n          assert.strictEqual(err.message, 'Input image exceeds pixel limit');\n        })\n    );\n\n    it('Enabling default limit works and fails for an image with resolution higher than uint32 limit', () =>\n      sharp(fixtures.inputPngUint32Limit, { limitInputPixels: true })\n        .toBuffer()\n        .then(() => {\n          assert.fail('Expected to fail');\n        })\n        .catch(err => {\n          assert.strictEqual(err.message, 'Input image exceeds pixel limit');\n        })\n    );\n\n    it('Smaller than input fails', () =>\n      sharp(fixtures.inputJpg)\n        .metadata()\n        .then(({ width, height }) =>\n          sharp(fixtures.inputJpg, { limitInputPixels: width * height - 1 })\n            .toBuffer()\n            .then(() => {\n              assert.fail('Expected to fail');\n            })\n            .catch(err => {\n              assert.strictEqual(err.message, 'Input image exceeds pixel limit');\n            })\n        )\n    );\n  });\n\n  describe('Input options', () => {\n    it('Option-less', () => {\n      sharp();\n    });\n    it('Ignore unknown attribute', () => {\n      sharp({ unknown: true });\n    });\n    it('undefined with options fails', () => {\n      assert.throws(() => {\n        sharp(undefined, {});\n      }, /Unsupported input 'undefined' of type undefined when also providing options of type object/);\n    });\n    it('null with options fails', () => {\n      assert.throws(() => {\n        sharp(null, {});\n      }, /Unsupported input 'null' of type object when also providing options of type object/);\n    });\n    it('Non-Object options fails', () => {\n      assert.throws(() => {\n        sharp('test', 'zoinks');\n      }, /Invalid input options zoinks/);\n    });\n    it('Invalid density: string', () => {\n      assert.throws(() => {\n        sharp({ density: 'zoinks' });\n      }, /Expected number between 1 and 100000 for density but received zoinks of type string/);\n    });\n    it('Invalid ignoreIcc: string', () => {\n      assert.throws(() => {\n        sharp({ ignoreIcc: 'zoinks' });\n      }, /Expected boolean for ignoreIcc but received zoinks of type string/);\n    });\n    it('Setting animated property updates pages property', () => {\n      assert.strictEqual(sharp({ animated: false }).options.input.pages, 1);\n      assert.strictEqual(sharp({ animated: true }).options.input.pages, -1);\n    });\n    it('Invalid animated property throws', () => {\n      assert.throws(() => {\n        sharp({ animated: -1 });\n      }, /Expected boolean for animated but received -1 of type number/);\n    });\n    it('Invalid page property throws', () => {\n      assert.throws(() => {\n        sharp({ page: -1 });\n      }, /Expected integer between 0 and 100000 for page but received -1 of type number/);\n    });\n    it('Invalid pages property throws', () => {\n      assert.throws(() => {\n        sharp({ pages: '1' });\n      }, /Expected integer between -1 and 100000 for pages but received 1 of type string/);\n    });\n    it('Valid openSlide.level property', () => {\n      sharp({ openSlide: { level: 1 } });\n      sharp({ level: 1 });\n    });\n    it('Invalid openSlide.level property (string) throws', () => {\n      assert.throws(\n        () => sharp({ openSlide: { level: '1' } }),\n        /Expected integer between 0 and 256 for openSlide.level but received 1 of type string/\n      );\n      assert.throws(\n        () => sharp({ level: '1' }),\n        /Expected integer between 0 and 256 for level but received 1 of type string/\n      );\n    });\n    it('Invalid openSlide.level property (negative) throws', () => {\n      assert.throws(\n        () => sharp({ openSlide: { level: -1 } }),\n        /Expected integer between 0 and 256 for openSlide\\.level but received -1 of type number/\n      );\n      assert.throws(\n        () => sharp({ level: -1 }),\n        /Expected integer between 0 and 256 for level but received -1 of type number/\n      );\n    });\n    it('Valid tiff.subifd property', () => {\n      sharp({ tiff: { subifd: 1 } });\n      sharp({ subifd: 1 });\n    });\n    it('Invalid tiff.subifd property (string) throws', () => {\n      assert.throws(\n        () => sharp({ tiff: { subifd: '1' } }),\n        /Expected integer between -1 and 100000 for tiff\\.subifd but received 1 of type string/\n      );\n      assert.throws(\n        () => sharp({ subifd: '1' }),\n        /Expected integer between -1 and 100000 for subifd but received 1 of type string/\n      );\n    });\n    it('Invalid tiff.subifd property (float) throws', () => {\n      assert.throws(\n        () => sharp({ tiff: { subifd: 1.2 } }),\n        /Expected integer between -1 and 100000 for tiff\\.subifd but received 1.2 of type number/\n      );\n      assert.throws(\n        () => sharp({ subifd: 1.2 }),\n        /Expected integer between -1 and 100000 for subifd but received 1.2 of type number/\n      );\n    });\n    it('Valid pdf.background property (string)', () => {\n      sharp({ pdf: { background: '#00ff00' } });\n      sharp({ pdfBackground: '#00ff00' });\n    });\n    it('Valid pdf.background property (object)', () => {\n      sharp({ pdf: { background: { r: 0, g: 255, b: 0 } } });\n      sharp({ pdfBackground: { r: 0, g: 255, b: 0 } });\n    });\n    it('Invalid pdf.background property (string) throws', () => {\n      assert.throws(\n        () => sharp({ pdf: { background: '00ff00' } }),\n        /Unable to parse color from string/\n      );\n      assert.throws(\n        () => sharp({ pdfBackground: '00ff00' }),\n        /Unable to parse color from string/\n      );\n    });\n    it('Invalid pdf.background property (number) throws', () => {\n      assert.throws(\n        () => sharp({ pdf: { background: 255 } }),\n        /Expected object or string for background/\n      );\n      assert.throws(\n        () => sharp({ pdf: { background: 255 } }),\n        /Expected object or string for background/\n      );\n    });\n    it('Invalid pdf.background property (object)', () => {\n      assert.throws(\n        () => sharp({ pdf: { background: { red: 0, green: 255, blue: 0 } } }),\n        /Unable to parse color from object/\n      );\n      assert.throws(\n        () => sharp({ pdfBackground: { red: 0, green: 255, blue: 0 } }),\n        /Unable to parse color from object/\n      );\n    });\n  });\n\n  it('Fails when writing to missing directory', async () => {\n    const create = {\n      width: 8,\n      height: 8,\n      channels: 3,\n      background: { r: 0, g: 0, b: 0 }\n    };\n    await assert.rejects(\n      () => sharp({ create }).toFile('does-not-exist/out.jpg'),\n      /unable to open for write/\n    );\n  });\n\n  describe('create new image', () => {\n    it('RGB', (_t, done) => {\n      const create = {\n        width: 10,\n        height: 20,\n        channels: 3,\n        background: { r: 0, g: 255, b: 0 }\n      };\n      sharp({ create })\n        .jpeg()\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(create.width, info.width);\n          assert.strictEqual(create.height, info.height);\n          assert.strictEqual(create.channels, info.channels);\n          assert.strictEqual('jpeg', info.format);\n          fixtures.assertSimilar(fixtures.expected('create-rgb.jpg'), data, done);\n        });\n    });\n    it('RGBA', (_t, done) => {\n      const create = {\n        width: 20,\n        height: 10,\n        channels: 4,\n        background: { r: 255, g: 0, b: 0, alpha: 128 }\n      };\n      sharp({ create })\n        .png()\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(create.width, info.width);\n          assert.strictEqual(create.height, info.height);\n          assert.strictEqual(create.channels, info.channels);\n          assert.strictEqual('png', info.format);\n          fixtures.assertSimilar(fixtures.expected('create-rgba.png'), data, done);\n        });\n    });\n    it('Invalid channels', () => {\n      const create = {\n        width: 10,\n        height: 20,\n        channels: 2,\n        background: { r: 0, g: 0, b: 0 }\n      };\n      assert.throws(() => {\n        sharp({ create });\n      });\n    });\n    it('Missing background', () => {\n      const create = {\n        width: 10,\n        height: 20,\n        channels: 3\n      };\n      assert.throws(() => {\n        sharp({ create });\n      });\n    });\n  });\n\n  it('Queue length change events', (_t, done) => {\n    let eventCounter = 0;\n    const queueListener = (queueLength) => {\n      assert.strictEqual(true, queueLength === 0 || queueLength === 1);\n      eventCounter++;\n    };\n    sharp.queue.on('change', queueListener);\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .toBuffer((err) => {\n        process.nextTick(() => {\n          sharp.queue.removeListener('change', queueListener);\n          if (err) throw err;\n          assert.strictEqual(2, eventCounter);\n          done();\n        });\n      });\n  });\n\n  it('Info event data', (_t, done) => {\n    const readable = fs.createReadStream(fixtures.inputJPGBig);\n    const inPipeline = sharp()\n      .resize(840, 472)\n      .raw()\n      .on('info', (info) => {\n        assert.strictEqual(840, info.width);\n        assert.strictEqual(472, info.height);\n        assert.strictEqual(3, info.channels);\n      });\n    const badPipeline = sharp({ raw: { width: 840, height: 500, channels: 3 } })\n      .toFormat('jpeg')\n      .toBuffer((err) => {\n        assert.strictEqual(err.message.indexOf('memory area too small') > 0, true);\n        const readable = fs.createReadStream(fixtures.inputJPGBig);\n        const inPipeline = sharp()\n          .resize(840, 472)\n          .raw();\n        const goodPipeline = sharp({ raw: { width: 840, height: 472, channels: 3 } })\n          .toFormat('jpeg')\n          .toBuffer(done);\n        readable.pipe(inPipeline).pipe(goodPipeline);\n      });\n    readable.pipe(inPipeline).pipe(badPipeline);\n  });\n\n  it('supports wide-character filenames', async () => {\n    const filename = fixtures.path('output.图片.jpg');\n    const create = {\n      width: 8,\n      height: 8,\n      channels: 3,\n      background: 'green'\n    };\n    await sharp({ create }).toFile(filename);\n\n    const { width, height, channels, format } = await sharp(filename).metadata();\n    assert.strictEqual(width, 8);\n    assert.strictEqual(height, 8);\n    assert.strictEqual(channels, 3);\n    assert.strictEqual(format, 'jpeg');\n  });\n});\n"
  },
  {
    "path": "test/unit/join.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Join input images together', () => {\n  it('Join two images horizontally', async () => {\n    const data = await sharp([\n      fixtures.inputPngPalette,\n      { create: { width: 68, height: 68, channels: 3, background: 'green' } }\n    ], { join: { across: 2 } }).toBuffer();\n\n    const metadata = await sharp(data).metadata();\n    assert.strictEqual(metadata.format, 'png');\n    assert.strictEqual(metadata.width, 136);\n    assert.strictEqual(metadata.height, 68);\n    assert.strictEqual(metadata.space, 'srgb');\n    assert.strictEqual(metadata.channels, 3);\n    assert.strictEqual(metadata.hasAlpha, false);\n  });\n\n  it('Join two images vertically with shim and alpha channel', async () => {\n    const data = await sharp([\n      fixtures.inputPngPalette,\n      { create: { width: 68, height: 68, channels: 4, background: 'green' } }\n    ], { join: { across: 1, shim: 8 } }).toBuffer();\n\n    const metadata = await sharp(data).metadata();\n    assert.strictEqual(metadata.format, 'png');\n    assert.strictEqual(metadata.width, 68);\n    assert.strictEqual(metadata.height, 144);\n    assert.strictEqual(metadata.space, 'srgb');\n    assert.strictEqual(metadata.channels, 4);\n    assert.strictEqual(metadata.hasAlpha, true);\n  });\n\n  it('Join four images in 2x2 grid, with centre alignment', async () => {\n    const output = fixtures.path('output.join2x2.png');\n    const info = await sharp([\n      fixtures.inputPngPalette,\n      { create: { width: 128, height: 128, channels: 3, background: 'green' } },\n      { create: { width: 128, height: 128, channels: 3, background: 'red' } },\n      fixtures.inputPngPalette\n    ], { join: { across: 2, halign: 'centre', valign: 'centre', background: 'blue' } })\n      .toFile(output);\n\n    fixtures.assertMaxColourDistance(output, fixtures.expected('join2x2.png'));\n\n    assert.strictEqual(info.format, 'png');\n    assert.strictEqual(info.width, 256);\n    assert.strictEqual(info.height, 256);\n    assert.strictEqual(info.channels, 3);\n  });\n\n  it('Join two images as animation', async () => {\n    const data = await sharp([\n      fixtures.inputPngPalette,\n      { create: { width: 68, height: 68, channels: 3, background: 'green' } }\n    ], { join: { animated: true } }).gif().toBuffer();\n\n    const metadata = await sharp(data).metadata();\n    assert.strictEqual(metadata.format, 'gif');\n    assert.strictEqual(metadata.width, 68);\n    assert.strictEqual(metadata.height, 68);\n    assert.strictEqual(metadata.pages, 2);\n  });\n\n  it('Empty array of inputs throws', () => {\n    assert.throws(\n      () => sharp([]),\n      /Expected at least two images to join/\n    );\n  });\n  it('Attempt to recursively join throws', () => {\n    assert.throws(\n      () => sharp([fixtures.inputJpg, [fixtures.inputJpg, fixtures.inputJpg]]),\n      /Recursive join is unsupported/\n    );\n  });\n  it('Attempt to set join props on non-array input throws', () => {\n    assert.throws(\n      () => sharp(fixtures.inputJpg, { join: { across: 2 } }),\n      /Expected input to be an array of images to join/\n    );\n  });\n  it('Invalid animated throws', () => {\n    assert.throws(\n      () => sharp([fixtures.inputJpg, fixtures.inputJpg], { join: { animated: 'fail' } }),\n      /Expected boolean for join.animated but received fail of type string/\n    );\n  });\n  it('Invalid across throws', () => {\n    assert.throws(\n      () => sharp([fixtures.inputJpg, fixtures.inputJpg], { join: { across: 'fail' } }),\n      /Expected integer between 1 and 100000 for join.across but received fail of type string/\n    );\n    assert.throws(\n      () => sharp([fixtures.inputJpg, fixtures.inputJpg], { join: { across: 0 } }),\n      /Expected integer between 1 and 100000 for join.across but received 0 of type number/\n    );\n  });\n  it('Invalid shim throws', () => {\n    assert.throws(\n      () => sharp([fixtures.inputJpg, fixtures.inputJpg], { join: { shim: 'fail' } }),\n      /Expected integer between 0 and 100000 for join.shim but received fail of type string/\n    );\n    assert.throws(\n      () => sharp([fixtures.inputJpg, fixtures.inputJpg], { join: { shim: -1 } }),\n      /Expected integer between 0 and 100000 for join.shim but received -1 of type number/\n    );\n  });\n  it('Invalid halign', () => {\n    assert.throws(\n      () => sharp([fixtures.inputJpg, fixtures.inputJpg], { join: { halign: 'fail' } }),\n      /Expected valid alignment for join.halign but received fail of type string/\n    );\n  });\n  it('Invalid valign', () => {\n    assert.throws(\n      () => sharp([fixtures.inputJpg, fixtures.inputJpg], { join: { valign: 'fail' } }),\n      /Expected valid alignment for join.valign but received fail of type string/\n    );\n  });\n});\n"
  },
  {
    "path": "test/unit/joinChannel.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\nconst fs = require('node:fs');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Image channel insertion', () => {\n  it('Grayscale to RGB, buffer', (_t, done) => {\n    sharp(fixtures.inputPng) // gray -> red\n      .resize(320, 240)\n      .joinChannel(fixtures.inputPngTestJoinChannel) // new green channel\n      .joinChannel(fixtures.inputPngStripesH) // new blue channel\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        assert.strictEqual(3, info.channels);\n        fixtures.assertSimilar(fixtures.expected('joinChannel-rgb.jpg'), data, done);\n      });\n  });\n\n  it('Grayscale to RGB, file', (_t, done) => {\n    sharp(fixtures.inputPng) // gray -> red\n      .resize(320, 240)\n      .joinChannel(fs.readFileSync(fixtures.inputPngTestJoinChannel)) // new green channel\n      .joinChannel(fs.readFileSync(fixtures.inputPngStripesH)) // new blue channel\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        assert.strictEqual(3, info.channels);\n        fixtures.assertSimilar(fixtures.expected('joinChannel-rgb.jpg'), data, done);\n      });\n  });\n\n  it('Grayscale to RGBA, buffer', (_t, done) => {\n    sharp(fixtures.inputPng) // gray -> red\n      .resize(320, 240)\n      .joinChannel([\n        fixtures.inputPngTestJoinChannel,\n        fixtures.inputPngStripesH,\n        fixtures.inputPngStripesV\n      ]) // new green + blue + alpha channel\n      .toColourspace(sharp.colourspace.srgb)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('joinChannel-rgba.png'), data, done);\n      });\n  });\n\n  it('Grayscale to RGBA, file', (_t, done) => {\n    sharp(fixtures.inputPng) // gray -> red\n      .resize(320, 240)\n      .joinChannel([\n        fs.readFileSync(fixtures.inputPngTestJoinChannel), // new green channel\n        fs.readFileSync(fixtures.inputPngStripesH), // new blue channel\n        fs.readFileSync(fixtures.inputPngStripesV) // new alpha channel\n      ])\n      .toColourspace('srgb')\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('joinChannel-rgba.png'), data, done);\n      });\n  });\n\n  it('Grayscale to CMYK, buffers', (_t, done) => {\n    sharp(fixtures.inputPng) // gray -> magenta\n      .resize(320, 240)\n      .joinChannel([\n        fs.readFileSync(fixtures.inputPngTestJoinChannel), // new cyan channel\n        fs.readFileSync(fixtures.inputPngStripesH), // new yellow channel\n        fs.readFileSync(fixtures.inputPngStripesV) // new black channel\n      ])\n      .toColorspace('cmyk')\n      .toFormat('jpeg')\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('joinChannel-cmyk.jpg'), data, done);\n      });\n  });\n\n  it('Join raw buffers to RGB', (_t, done) => {\n    Promise.all([\n      sharp(fixtures.inputPngTestJoinChannel).toColourspace('b-w').raw().toBuffer(),\n      sharp(fixtures.inputPngStripesH).toColourspace('b-w').raw().toBuffer()\n    ])\n      .then((buffers) => {\n        sharp(fixtures.inputPng)\n          .resize(320, 240)\n          .joinChannel(buffers, {\n            raw: {\n              width: 320,\n              height: 240,\n              channels: 1\n            }\n          })\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            assert.strictEqual(320, info.width);\n            assert.strictEqual(240, info.height);\n            assert.strictEqual(3, info.channels);\n            fixtures.assertSimilar(fixtures.expected('joinChannel-rgb.jpg'), data, done);\n          });\n      })\n      .catch((err) => {\n        throw err;\n      });\n  });\n\n  it('Grayscale to RGBA, files, two arrays', (_t, done) => {\n    sharp(fixtures.inputPng) // gray -> red\n      .resize(320, 240)\n      .joinChannel([fs.readFileSync(fixtures.inputPngTestJoinChannel)]) // new green channel\n      .joinChannel([\n        fs.readFileSync(fixtures.inputPngStripesH), // new blue channel\n        fs.readFileSync(fixtures.inputPngStripesV) // new alpha channel\n      ])\n      .toColourspace('srgb')\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('joinChannel-rgba.png'), data, done);\n      });\n  });\n\n  it('Invalid raw buffer description', () => {\n    assert.throws(() => {\n      sharp().joinChannel(fs.readFileSync(fixtures.inputPng), { raw: {} });\n    });\n  });\n\n  it('Invalid input', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).joinChannel(1);\n    });\n  });\n\n  it('No arguments', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).joinChannel();\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/jp2.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('JP2 output', () => {\n  if (!sharp.format.jp2k.input.buffer) {\n    it('JP2 output should fail due to missing OpenJPEG', () =>\n      assert.rejects(async () =>\n        sharp(fixtures.inputJpg)\n          .jp2()\n          .toBuffer(),\n      /JP2 output requires libvips with support for OpenJPEG/\n      )\n    );\n\n    it('JP2 file output should fail due to missing OpenJPEG', () =>\n      assert.rejects(async () => sharp(fixtures.inputJpg).toFile('test.jp2'),\n        /JP2 output requires libvips with support for OpenJPEG/\n      )\n    );\n\n    it('File with JP2-like suffix should not fail due to missing OpenJPEG', () => {\n      const output = fixtures.path('output.failj2c');\n      return assert.doesNotReject(\n        async () => sharp(fixtures.inputPngWithOneColor).toFile(output)\n      );\n    });\n  } else {\n    it('JP2 Buffer to PNG Buffer', () => {\n      sharp(fs.readFileSync(fixtures.inputJp2))\n        .resize(8, 15)\n        .png()\n        .toBuffer({ resolveWithObject: true })\n        .then(({ data, info }) => {\n          assert.strictEqual(true, data.length > 0);\n          assert.strictEqual(data.length, info.size);\n          assert.strictEqual('png', info.format);\n          assert.strictEqual(8, info.width);\n          assert.strictEqual(15, info.height);\n          assert.strictEqual(3, info.channels);\n        });\n    });\n\n    it('JP2 quality', (_t, done) => {\n      sharp(fixtures.inputJp2)\n        .resize(320, 240)\n        .jp2({ quality: 70 })\n        .toBuffer((err, buffer70) => {\n          if (err) throw err;\n          sharp(fixtures.inputJp2)\n            .resize(320, 240)\n            .toBuffer((err, buffer80) => {\n              if (err) throw err;\n              assert(buffer70.length < buffer80.length);\n              done();\n            });\n        });\n    });\n\n    it('Without chroma subsampling generates larger file', (_t, done) => {\n      // First generate with chroma subsampling (default)\n      sharp(fixtures.inputJp2)\n        .resize(320, 240)\n        .jp2({ chromaSubsampling: '4:2:0' })\n        .toBuffer((err, withChromaSubsamplingData, withChromaSubsamplingInfo) => {\n          if (err) throw err;\n          assert.strictEqual(true, withChromaSubsamplingData.length > 0);\n          assert.strictEqual(withChromaSubsamplingData.length, withChromaSubsamplingInfo.size);\n          assert.strictEqual('jp2', withChromaSubsamplingInfo.format);\n          assert.strictEqual(320, withChromaSubsamplingInfo.width);\n          assert.strictEqual(240, withChromaSubsamplingInfo.height);\n          // Then generate without\n          sharp(fixtures.inputJp2)\n            .resize(320, 240)\n            .jp2({ chromaSubsampling: '4:4:4' })\n            .toBuffer((err, withoutChromaSubsamplingData, withoutChromaSubsamplingInfo) => {\n              if (err) throw err;\n              assert.strictEqual(true, withoutChromaSubsamplingData.length > 0);\n              assert.strictEqual(withoutChromaSubsamplingData.length, withoutChromaSubsamplingInfo.size);\n              assert.strictEqual('jp2', withoutChromaSubsamplingInfo.format);\n              assert.strictEqual(320, withoutChromaSubsamplingInfo.width);\n              assert.strictEqual(240, withoutChromaSubsamplingInfo.height);\n              assert.strictEqual(true, withChromaSubsamplingData.length <= withoutChromaSubsamplingData.length);\n              done();\n            });\n        });\n    });\n\n    it('can use the jp2Oneshot option to handle multi-part tiled JPEG 2000 file', async () => {\n      const outputJpg = fixtures.path('output.jpg');\n      await assert.rejects(\n        () => sharp(fixtures.inputJp2TileParts).toFile(outputJpg)\n      );\n      await assert.doesNotReject(async () => {\n        await sharp(fixtures.inputJp2TileParts, { jp2Oneshot: true }).toFile(outputJpg);\n        const { format, width, height } = await sharp(outputJpg).metadata();\n        assert.strictEqual(format, 'jpeg');\n        assert.strictEqual(width, 320);\n        assert.strictEqual(height, 240);\n      });\n    });\n\n    it('Invalid JP2 chromaSubsampling value throws error', () => {\n      assert.throws(\n        () => sharp().jp2({ chromaSubsampling: '4:2:2' }),\n        /Expected one of: 4:2:0, 4:4:4 for chromaSubsampling but received 4:2:2 of type string/\n      );\n    });\n  }\n\n  it('valid JP2 oneshot value does not throw error', () => {\n    assert.doesNotThrow(\n      () => sharp({ jp2: { oneshot: true } })\n    );\n  });\n\n  it('invalid JP2 oneshot value throws error', () => {\n    assert.throws(\n      () => sharp({ jp2: { oneshot: 'fail' } }),\n      /Expected boolean for jp2.oneshot but received fail of type string/\n    );\n  });\n});\n"
  },
  {
    "path": "test/unit/jpeg.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('JPEG', () => {\n  it('JPEG quality', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .jpeg({ quality: 70 })\n      .toBuffer((err, buffer70) => {\n        if (err) throw err;\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .toBuffer((err, buffer80) => {\n            if (err) throw err;\n            sharp(fixtures.inputJpg)\n              .resize(320, 240)\n              .jpeg({ quality: 90 })\n              .toBuffer((err, buffer90) => {\n                if (err) throw err;\n                assert(buffer70.length < buffer80.length);\n                assert(buffer80.length < buffer90.length);\n                done();\n              });\n          });\n      });\n  });\n\n  describe('Invalid JPEG quality', () => {\n    [-1, 88.2, 'test'].forEach((quality) => {\n      it(quality.toString(), () => {\n        assert.throws(() => {\n          sharp().jpeg({ quality });\n        });\n      });\n    });\n  });\n\n  describe('Invalid JPEG quantisation table', () => {\n    [-1, 88.2, 'test'].forEach((table) => {\n      it(table.toString(), () => {\n        assert.throws(() => {\n          sharp().jpeg({ quantisationTable: table });\n        });\n      });\n    });\n  });\n\n  it('Progressive JPEG image', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .jpeg({ progressive: false })\n      .toBuffer((err, nonProgressiveData, nonProgressiveInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, nonProgressiveData.length > 0);\n        assert.strictEqual(nonProgressiveData.length, nonProgressiveInfo.size);\n        assert.strictEqual('jpeg', nonProgressiveInfo.format);\n        assert.strictEqual(320, nonProgressiveInfo.width);\n        assert.strictEqual(240, nonProgressiveInfo.height);\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .jpeg({ progressive: true })\n          .toBuffer((err, progressiveData, progressiveInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, progressiveData.length > 0);\n            assert.strictEqual(progressiveData.length, progressiveInfo.size);\n            assert.strictEqual(false, progressiveData.length === nonProgressiveData.length);\n            assert.strictEqual('jpeg', progressiveInfo.format);\n            assert.strictEqual(320, progressiveInfo.width);\n            assert.strictEqual(240, progressiveInfo.height);\n            done();\n          });\n      });\n  });\n\n  it('Without chroma subsampling generates larger file', (_t, done) => {\n    // First generate with chroma subsampling (default)\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .jpeg({ chromaSubsampling: '4:2:0' })\n      .toBuffer((err, withChromaSubsamplingData, withChromaSubsamplingInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, withChromaSubsamplingData.length > 0);\n        assert.strictEqual(withChromaSubsamplingData.length, withChromaSubsamplingInfo.size);\n        assert.strictEqual('jpeg', withChromaSubsamplingInfo.format);\n        assert.strictEqual(320, withChromaSubsamplingInfo.width);\n        assert.strictEqual(240, withChromaSubsamplingInfo.height);\n        // Then generate without\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .jpeg({ chromaSubsampling: '4:4:4' })\n          .toBuffer((err, withoutChromaSubsamplingData, withoutChromaSubsamplingInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, withoutChromaSubsamplingData.length > 0);\n            assert.strictEqual(withoutChromaSubsamplingData.length, withoutChromaSubsamplingInfo.size);\n            assert.strictEqual('jpeg', withoutChromaSubsamplingInfo.format);\n            assert.strictEqual(320, withoutChromaSubsamplingInfo.width);\n            assert.strictEqual(240, withoutChromaSubsamplingInfo.height);\n            assert.strictEqual(true, withChromaSubsamplingData.length < withoutChromaSubsamplingData.length);\n            done();\n          });\n      });\n  });\n\n  it('Invalid JPEG chromaSubsampling value throws error', () => {\n    assert.throws(() => {\n      sharp().jpeg({ chromaSubsampling: '4:2:2' });\n    });\n  });\n\n  it('Trellis quantisation', (_t, done) => {\n    // First generate without\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .jpeg({ trellisQuantisation: false })\n      .toBuffer((err, withoutData, withoutInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, withoutData.length > 0);\n        assert.strictEqual(withoutData.length, withoutInfo.size);\n        assert.strictEqual('jpeg', withoutInfo.format);\n        assert.strictEqual(320, withoutInfo.width);\n        assert.strictEqual(240, withoutInfo.height);\n        // Then generate with\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .jpeg({ trellisQuantization: true })\n          .toBuffer((err, withData, withInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, withData.length > 0);\n            assert.strictEqual(withData.length, withInfo.size);\n            assert.strictEqual('jpeg', withInfo.format);\n            assert.strictEqual(320, withInfo.width);\n            assert.strictEqual(240, withInfo.height);\n            // Verify image is same (as mozjpeg may not be present) size or less\n            assert.strictEqual(true, withData.length <= withoutData.length);\n            done();\n          });\n      });\n  });\n\n  it('Overshoot deringing', (_t, done) => {\n    // First generate without\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .jpeg({ overshootDeringing: false })\n      .toBuffer((err, withoutData, withoutInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, withoutData.length > 0);\n        assert.strictEqual(withoutData.length, withoutInfo.size);\n        assert.strictEqual('jpeg', withoutInfo.format);\n        assert.strictEqual(320, withoutInfo.width);\n        assert.strictEqual(240, withoutInfo.height);\n        // Then generate with\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .jpeg({ overshootDeringing: true })\n          .toBuffer((err, withData, withInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, withData.length > 0);\n            assert.strictEqual(withData.length, withInfo.size);\n            assert.strictEqual('jpeg', withInfo.format);\n            assert.strictEqual(320, withInfo.width);\n            assert.strictEqual(240, withInfo.height);\n            done();\n          });\n      });\n  });\n\n  it('Optimise scans generates different output length', (_t, done) => {\n    // First generate without\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .jpeg({ optimiseScans: false })\n      .toBuffer((err, withoutData, withoutInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, withoutData.length > 0);\n        assert.strictEqual(withoutData.length, withoutInfo.size);\n        assert.strictEqual('jpeg', withoutInfo.format);\n        assert.strictEqual(320, withoutInfo.width);\n        assert.strictEqual(240, withoutInfo.height);\n        // Then generate with\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .jpeg({ optimizeScans: true })\n          .toBuffer((err, withData, withInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, withData.length > 0);\n            assert.strictEqual(withData.length, withInfo.size);\n            assert.strictEqual('jpeg', withInfo.format);\n            assert.strictEqual(320, withInfo.width);\n            assert.strictEqual(240, withInfo.height);\n            // Verify image is of a different size (progressive output even without mozjpeg)\n            assert.notStrictEqual(withData.length, withoutData.length);\n            done();\n          });\n      });\n  });\n\n  it('Optimise coding generates smaller output length', (_t, done) => {\n    // First generate with optimize coding enabled (default)\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .jpeg()\n      .toBuffer((err, withOptimiseCoding, withInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, withOptimiseCoding.length > 0);\n        assert.strictEqual(withOptimiseCoding.length, withInfo.size);\n        assert.strictEqual('jpeg', withInfo.format);\n        assert.strictEqual(320, withInfo.width);\n        assert.strictEqual(240, withInfo.height);\n        // Then generate with coding disabled\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .jpeg({ optimizeCoding: false })\n          .toBuffer((err, withoutOptimiseCoding, withoutInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, withoutOptimiseCoding.length > 0);\n            assert.strictEqual(withoutOptimiseCoding.length, withoutInfo.size);\n            assert.strictEqual('jpeg', withoutInfo.format);\n            assert.strictEqual(320, withoutInfo.width);\n            assert.strictEqual(240, withoutInfo.height);\n            // Verify optimised image is of a smaller size\n            assert.strictEqual(true, withOptimiseCoding.length < withoutOptimiseCoding.length);\n            done();\n          });\n      });\n  });\n\n  it('Specifying quantisation table provides different JPEG', (_t, done) => {\n    // First generate with default quantisation table\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .jpeg({ optimiseCoding: false })\n      .toBuffer((err, withDefaultQuantisationTable, withInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, withDefaultQuantisationTable.length > 0);\n        assert.strictEqual(withDefaultQuantisationTable.length, withInfo.size);\n        assert.strictEqual('jpeg', withInfo.format);\n        assert.strictEqual(320, withInfo.width);\n        assert.strictEqual(240, withInfo.height);\n        // Then generate with different quantisation table\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .jpeg({ optimiseCoding: false, quantisationTable: 3 })\n          .toBuffer((err, withQuantTable3, withoutInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, withQuantTable3.length > 0);\n            assert.strictEqual(withQuantTable3.length, withoutInfo.size);\n            assert.strictEqual('jpeg', withoutInfo.format);\n            assert.strictEqual(320, withoutInfo.width);\n            assert.strictEqual(240, withoutInfo.height);\n\n            // Verify image is same (as mozjpeg may not be present) size or less\n            assert.strictEqual(true, withQuantTable3.length <= withDefaultQuantisationTable.length);\n            done();\n          });\n      });\n  });\n\n  it('Specifying quantization table provides different JPEG', (_t, done) => {\n    // First generate with default quantization table\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .jpeg({ optimiseCoding: false })\n      .toBuffer((err, withDefaultQuantizationTable, withInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, withDefaultQuantizationTable.length > 0);\n        assert.strictEqual(withDefaultQuantizationTable.length, withInfo.size);\n        assert.strictEqual('jpeg', withInfo.format);\n        assert.strictEqual(320, withInfo.width);\n        assert.strictEqual(240, withInfo.height);\n        // Then generate with different quantization table\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .jpeg({ optimiseCoding: false, quantizationTable: 3 })\n          .toBuffer((err, withQuantTable3, withoutInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, withQuantTable3.length > 0);\n            assert.strictEqual(withQuantTable3.length, withoutInfo.size);\n            assert.strictEqual('jpeg', withoutInfo.format);\n            assert.strictEqual(320, withoutInfo.width);\n            assert.strictEqual(240, withoutInfo.height);\n\n            // Verify image is same (as mozjpeg may not be present) size or less\n            assert.strictEqual(true, withQuantTable3.length <= withDefaultQuantizationTable.length);\n            done();\n          });\n      });\n  });\n\n  it('Can use mozjpeg defaults', async () => {\n    const withoutData = await sharp(fixtures.inputJpg)\n      .resize(32, 24)\n      .jpeg({ mozjpeg: false })\n      .toBuffer();\n    const withoutMeta = await sharp(withoutData).metadata();\n    assert.strictEqual(false, withoutMeta.isProgressive);\n\n    const withData = await sharp(fixtures.inputJpg)\n      .resize(32, 24)\n      .jpeg({ mozjpeg: true })\n      .toBuffer();\n    const withMeta = await sharp(withData).metadata();\n    assert.strictEqual(true, withMeta.isProgressive);\n  });\n\n  it('Invalid mozjpeg value throws error', () => {\n    assert.throws(() => sharp().jpeg({ mozjpeg: 'fail' }));\n  });\n});\n"
  },
  {
    "path": "test/unit/jxl.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\n\ndescribe('JXL', () => {\n  it('called without options does not throw an error', () => {\n    assert.doesNotThrow(() => {\n      sharp().jxl();\n    });\n  });\n  it('valid distance does not throw an error', () => {\n    assert.doesNotThrow(() => {\n      sharp().jxl({ distance: 2.3 });\n    });\n  });\n  it('invalid distance should throw an error', () => {\n    assert.throws(() => {\n      sharp().jxl({ distance: 15.1 });\n    });\n  });\n  it('non-numeric distance should throw an error', () => {\n    assert.throws(() => {\n      sharp().jxl({ distance: 'fail' });\n    });\n  });\n  it('valid quality > 30 does not throw an error', () => {\n    const s = sharp();\n    assert.doesNotThrow(() => {\n      s.jxl({ quality: 80 });\n    });\n    assert.strictEqual(s.options.jxlDistance, 1.9);\n  });\n  it('valid quality < 30 does not throw an error', () => {\n    const s = sharp();\n    assert.doesNotThrow(() => {\n      s.jxl({ quality: 20 });\n    });\n    assert.strictEqual(s.options.jxlDistance, 9.066666666666666);\n  });\n  it('valid quality does not throw an error', () => {\n    assert.doesNotThrow(() => {\n      sharp().jxl({ quality: 80 });\n    });\n  });\n  it('invalid quality should throw an error', () => {\n    assert.throws(() => {\n      sharp().jxl({ quality: 101 });\n    });\n  });\n  it('non-numeric quality should throw an error', () => {\n    assert.throws(() => {\n      sharp().jxl({ quality: 'fail' });\n    });\n  });\n  it('valid decodingTier does not throw an error', () => {\n    assert.doesNotThrow(() => {\n      sharp().jxl({ decodingTier: 2 });\n    });\n  });\n  it('invalid decodingTier should throw an error', () => {\n    assert.throws(() => {\n      sharp().jxl({ decodingTier: 5 });\n    });\n  });\n  it('non-numeric decodingTier should throw an error', () => {\n    assert.throws(() => {\n      sharp().jxl({ decodingTier: 'fail' });\n    });\n  });\n  it('valid lossless does not throw an error', () => {\n    assert.doesNotThrow(() => {\n      sharp().jxl({ lossless: true });\n    });\n  });\n  it('non-boolean lossless should throw an error', () => {\n    assert.throws(() => {\n      sharp().jxl({ lossless: 'fail' });\n    });\n  });\n  it('valid effort does not throw an error', () => {\n    assert.doesNotThrow(() => {\n      sharp().jxl({ effort: 6 });\n    });\n  });\n  it('out of range effort should throw an error', () => {\n    assert.throws(() => {\n      sharp().jxl({ effort: 10 });\n    });\n  });\n  it('invalid effort should throw an error', () => {\n    assert.throws(() => {\n      sharp().jxl({ effort: 'fail' });\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/libvips.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { after, before, describe, it } = require('node:test');\nconst assert = require('node:assert');\nconst fs = require('node:fs');\nconst semver = require('semver');\nconst libvips = require('../../lib/libvips');\n\nconst originalPlatform = process.platform;\n\nconst setPlatform = (platform) => {\n  Object.defineProperty(process, 'platform', { value: platform });\n};\n\nconst restorePlatform = () => {\n  setPlatform(originalPlatform);\n};\n\ndescribe('libvips binaries', () => {\n  describe('Windows platform', () => {\n    before(() => { setPlatform('win32'); });\n    after(restorePlatform);\n\n    it('pkgConfigPath returns empty string', () => {\n      assert.strictEqual('', libvips.pkgConfigPath());\n    });\n    it('globalLibvipsVersion returns empty string', () => {\n      assert.strictEqual('', libvips.globalLibvipsVersion());\n    });\n    it('globalLibvipsVersion is always false', () => {\n      assert.strictEqual(false, libvips.useGlobalLibvips());\n    });\n  });\n\n  describe('non-Windows platforms', () => {\n    before(() => { setPlatform('linux'); });\n    after(restorePlatform);\n\n    it('pkgConfigPath returns a string', () => {\n      const pkgConfigPath = libvips.pkgConfigPath();\n      assert.strictEqual('string', typeof pkgConfigPath);\n    });\n    it('globalLibvipsVersion returns a string', () => {\n      const globalLibvipsVersion = libvips.globalLibvipsVersion();\n      assert.strictEqual('string', typeof globalLibvipsVersion);\n    });\n    it('globalLibvipsVersion returns a boolean', () => {\n      const useGlobalLibvips = libvips.useGlobalLibvips();\n      assert.strictEqual('boolean', typeof useGlobalLibvips);\n    });\n  });\n\n  describe('platform agnostic', () => {\n    it('minimumLibvipsVersion returns a valid semver', () => {\n      const minimumLibvipsVersion = libvips.minimumLibvipsVersion;\n      assert.strictEqual('string', typeof minimumLibvipsVersion);\n      assert.notStrictEqual(null, semver.valid(minimumLibvipsVersion));\n    });\n    it('useGlobalLibvips can be ignored via an env var', () => {\n      process.env.SHARP_IGNORE_GLOBAL_LIBVIPS = 1;\n\n      const useGlobalLibvips = libvips.useGlobalLibvips();\n      assert.strictEqual(false, useGlobalLibvips);\n\n      delete process.env.SHARP_IGNORE_GLOBAL_LIBVIPS;\n    });\n    it('useGlobalLibvips can be forced via an env var', () => {\n      process.env.SHARP_FORCE_GLOBAL_LIBVIPS = 1;\n\n      const useGlobalLibvips = libvips.useGlobalLibvips();\n      assert.strictEqual(true, useGlobalLibvips);\n\n      let logged = false;\n      const logger = (message) => {\n        assert.strictEqual(message, 'Detected SHARP_FORCE_GLOBAL_LIBVIPS, skipping search for globally-installed libvips');\n        logged = true;\n      };\n      const useGlobalLibvipsWithLogger = libvips.useGlobalLibvips(logger);\n      assert.strictEqual(true, useGlobalLibvipsWithLogger);\n      assert.strictEqual(true, logged);\n\n      delete process.env.SHARP_FORCE_GLOBAL_LIBVIPS;\n    });\n  });\n\n  describe('Build time platform detection', () => {\n    it('Can override platform with npm_config_platform and npm_config_libc', function () {\n      process.env.npm_config_platform = 'testplatform';\n      process.env.npm_config_libc = 'testlibc';\n      const platformArch = libvips.buildPlatformArch();\n      if (platformArch === 'wasm32') {\n        return this.skip();\n      }\n      const [platform] = platformArch.split('-');\n      assert.strictEqual(platform, 'testplatformtestlibc');\n      delete process.env.npm_config_platform;\n      delete process.env.npm_config_libc;\n    });\n    it('Can override arch with npm_config_arch', function () {\n      process.env.npm_config_arch = 'test';\n      const platformArch = libvips.buildPlatformArch();\n      if (platformArch === 'wasm32') {\n        return this.skip();\n      }\n      const [, arch] = platformArch.split('-');\n      assert.strictEqual(arch, 'test');\n      delete process.env.npm_config_arch;\n    });\n  });\n\n  describe('Build time directories', () => {\n    it('sharp-libvips include', () => {\n      const dir = libvips.buildSharpLibvipsIncludeDir();\n      if (dir) {\n        assert.strictEqual(fs.statSync(dir).isDirectory(), true);\n      }\n    });\n    it('sharp-libvips cplusplus', () => {\n      const dir = libvips.buildSharpLibvipsCPlusPlusDir();\n      if (dir) {\n        assert.strictEqual(fs.statSync(dir).isDirectory(), true);\n      }\n    });\n    it('sharp-libvips lib', () => {\n      const dir = libvips.buildSharpLibvipsLibDir();\n      if (dir) {\n        assert.strictEqual(fs.statSync(dir).isDirectory(), true);\n      }\n    });\n  });\n\n  describe('Runtime detection', () => {\n    it('platform', () => {\n      const [platform] = libvips.runtimePlatformArch().split('-');\n      assert.strict(['darwin', 'freebsd', 'linux', 'linuxmusl', 'win32'].includes(platform));\n    });\n    it('arch', () => {\n      const [, arch] = libvips.runtimePlatformArch().split('-');\n      assert.strict(['arm', 'arm64', 'ia32', 'x64', 'ppc64'].includes(arch));\n    });\n    it('isUnsupportedNodeRuntime', () => {\n      assert.strictEqual(libvips.isUnsupportedNodeRuntime(), undefined);\n    });\n  });\n\n  describe('logger', () => {\n    const consoleLog = console.log;\n    const consoleError = console.error;\n\n    after(() => {\n      console.log = consoleLog;\n      console.error = consoleError;\n    });\n\n    it('logs an info message', (_t, done) => {\n      console.log = (msg) => {\n        assert.strictEqual(msg, 'sharp: progress');\n        done();\n      };\n      libvips.log('progress');\n    });\n\n    it('logs an error message', (_t, done) => {\n      console.error = (msg) => {\n        assert.strictEqual(msg, 'sharp: Installation error: problem');\n        done();\n      };\n      libvips.log(new Error('problem'));\n    });\n  });\n\n  describe('yarn locator hash', () => {\n    it('known platform', () => {\n      const cc = process.env.CC;\n      delete process.env.CC;\n      process.env.npm_config_platform = 'linux';\n      process.env.npm_config_arch = 's390x';\n      process.env.npm_config_libc = '';\n      const locatorHash = libvips.yarnLocator();\n      assert.strictEqual(locatorHash, '4ab19140fd');\n      delete process.env.npm_config_platform;\n      delete process.env.npm_config_arch;\n      delete process.env.npm_config_libc;\n      process.env.CC = cc;\n    });\n    it('unknown platform', () => {\n      process.env.npm_config_platform = 'unknown-platform';\n      const locatorHash = libvips.yarnLocator();\n      assert.strictEqual(locatorHash, '');\n      delete process.env.npm_config_platform;\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/linear.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\ndescribe('Linear adjustment', () => {\n  const blackPoint = 70;\n  const whitePoint = 203;\n  const a = 255 / (whitePoint - blackPoint);\n  const b = -blackPoint * a;\n\n  it('applies linear levels adjustment w/o alpha ch', (_t, done) => {\n    sharp(fixtures.inputJpgWithLowContrast)\n      .linear(a, b)\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('low-contrast-linear.jpg'), data, done);\n      });\n  });\n\n  it('applies slope level adjustment w/o alpha ch', (_t, done) => {\n    sharp(fixtures.inputJpgWithLowContrast)\n      .linear(a)\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('low-contrast-slope.jpg'), data, done);\n      });\n  });\n\n  it('applies offset level adjustment w/o alpha ch', (_t, done) => {\n    sharp(fixtures.inputJpgWithLowContrast)\n      .linear(null, b)\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('low-contrast-offset.jpg'), data, done);\n      });\n  });\n\n  it('applies linear levels adjustment w alpha ch', (_t, done) => {\n    sharp(fixtures.inputPngOverlayLayer1)\n      .resize(240)\n      .linear(a, b)\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('alpha-layer-1-fill-linear.png'), data, done);\n      });\n  });\n\n  it('applies linear levels adjustment to 16-bit w alpha ch', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency16bit)\n      .linear(a, b)\n      .png({ compressionLevel: 0 })\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('linear-16bit.png'), data, done);\n      });\n  });\n\n  it('applies slope level adjustment w alpha ch', (_t, done) => {\n    sharp(fixtures.inputPngOverlayLayer1)\n      .resize(240)\n      .linear(a)\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('alpha-layer-1-fill-slope.png'), data, done);\n      });\n  });\n\n  it('applies offset level adjustment w alpha ch', (_t, done) => {\n    sharp(fixtures.inputPngOverlayLayer1)\n      .resize(240)\n      .linear(null, b)\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('alpha-layer-1-fill-offset.png'), data, done);\n      });\n  });\n\n  it('per channel level adjustment', (_t, done) => {\n    sharp(fixtures.inputWebP)\n      .linear([0.25, 0.5, 0.75], [150, 100, 50]).toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('linear-per-channel.jpg'), data, done);\n      });\n  });\n\n  it('output is integer, not float, RGB', async () => {\n    const data = await sharp({ create: { width: 1, height: 1, channels: 3, background: 'red' } })\n      .linear(1, 0)\n      .tiff({ compression: 'none' })\n      .toBuffer();\n\n    const { channels, depth } = await sharp(data).metadata();\n    assert.strictEqual(channels, 3);\n    assert.strictEqual(depth, 'uchar');\n  });\n\n  it('output is integer, not float, RGBA', async () => {\n    const data = await sharp({ create: { width: 1, height: 1, channels: 4, background: '#ff000077' } })\n      .linear(1, 0)\n      .tiff({ compression: 'none' })\n      .toBuffer();\n\n    const { channels, depth } = await sharp(data).metadata();\n    assert.strictEqual(channels, 4);\n    assert.strictEqual(depth, 'uchar');\n  });\n\n  it('Invalid linear arguments', () => {\n    assert.throws(\n      () => sharp().linear('foo'),\n      /Expected number or array of numbers for a but received foo of type string/\n    );\n    assert.throws(\n      () => sharp().linear(undefined, { bar: 'baz' }),\n      /Expected number or array of numbers for b but received \\[object Object\\] of type object/\n    );\n    assert.throws(\n      () => sharp().linear([], [1]),\n      /Expected number or array of numbers for a but received {2}of type object/\n    );\n    assert.throws(\n      () => sharp().linear([1, 2], [1]),\n      /Expected a and b to be arrays of the same length/\n    );\n    assert.throws(\n      () => sharp().linear([1]),\n      /Expected a and b to be arrays of the same length/\n    );\n  });\n});\n"
  },
  {
    "path": "test/unit/median.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\n\nconst row = [0, 3, 15, 63, 127, 255];\nconst input = Buffer.from(Array.from(row, () => row).flat());\nconst raw = {\n  width: 6,\n  height: 6,\n  channels: 1\n};\n\ndescribe('Median filter', () => {\n  it('default window (3x3)', async () => {\n    const data = await sharp(input, { raw })\n      .median()\n      .toColourspace('b-w')\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual(data.subarray(0, 6), Buffer.from(row));\n  });\n\n  it('3x3 window', async () => {\n    const data = await sharp(input, { raw })\n      .median(3)\n      .toColourspace('b-w')\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual(data.subarray(0, 6), Buffer.from(row));\n  });\n\n  it('5x5 window', async () => {\n    const data = await sharp(input, { raw })\n      .median(5)\n      .toColourspace('b-w')\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual(data.subarray(0, 6), Buffer.from(row));\n  });\n\n  it('invalid radius', () => {\n    assert.throws(() => {\n      sharp().median(0.1);\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/metadata.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\nconst exifReader = require('exif-reader');\nconst icc = require('icc');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\nconst create = { width: 1, height: 1, channels: 3, background: 'red' };\n\ndescribe('Image metadata', () => {\n  it('JPEG', (_t, done) => {\n    sharp(fixtures.inputJpg).metadata((err, metadata) => {\n      if (err) throw err;\n      assert.strictEqual('jpeg', metadata.format);\n      assert.strictEqual('undefined', typeof metadata.size);\n      assert.strictEqual(2725, metadata.width);\n      assert.strictEqual(2225, metadata.height);\n      assert.strictEqual('srgb', metadata.space);\n      assert.strictEqual(3, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual(true, ['undefined', 'number'].includes(typeof metadata.density));\n      assert.strictEqual('4:2:0', metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual(false, metadata.hasAlpha);\n      assert.strictEqual('undefined', typeof metadata.orientation);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      done();\n    });\n  });\n\n  it('JPEG with EXIF/ICC', (_t, done) => {\n    sharp(fixtures.inputJpgWithExif).metadata((err, metadata) => {\n      if (err) throw err;\n      assert.strictEqual('jpeg', metadata.format);\n      assert.strictEqual('undefined', typeof metadata.size);\n      assert.strictEqual(450, metadata.width);\n      assert.strictEqual(600, metadata.height);\n      assert.strictEqual('srgb', metadata.space);\n      assert.strictEqual(3, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual(72, metadata.density);\n      assert.strictEqual('4:2:0', metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(true, metadata.hasProfile);\n      assert.strictEqual(false, metadata.hasAlpha);\n      assert.strictEqual(8, metadata.orientation);\n      // EXIF\n      assert.strictEqual('object', typeof metadata.exif);\n      assert.strictEqual(true, metadata.exif instanceof Buffer);\n      const exif = exifReader(metadata.exif);\n      assert.strictEqual('object', typeof exif);\n      assert.strictEqual('object', typeof exif.Image);\n      assert.strictEqual('number', typeof exif.Image.XResolution);\n      // ICC\n      assert.strictEqual('object', typeof metadata.icc);\n      assert.strictEqual(true, metadata.icc instanceof Buffer);\n      const profile = icc.parse(metadata.icc);\n      assert.strictEqual('object', typeof profile);\n      assert.strictEqual('Generic RGB Profile', profile.description);\n      done();\n    });\n  });\n\n  it('JPEG with IPTC/XMP', (_t, done) => {\n    sharp(fixtures.inputJpgWithIptcAndXmp).metadata((err, metadata) => {\n      if (err) throw err;\n      // IPTC\n      assert.strictEqual('object', typeof metadata.iptc);\n      assert.strictEqual(true, metadata.iptc instanceof Buffer);\n      assert.strictEqual(18250, metadata.iptc.byteLength);\n      assert.strictEqual(metadata.iptc.indexOf(Buffer.from('Photoshop')), 0);\n      // XMP\n      assert.strictEqual('object', typeof metadata.xmp);\n      assert.strictEqual(true, metadata.xmp instanceof Buffer);\n      assert.strictEqual(12466, metadata.xmp.byteLength);\n      assert.strictEqual(metadata.xmp.indexOf(Buffer.from('<?xpacket begin=\"')), 0);\n      assert(metadata.xmpAsString.startsWith('<?xpacket begin=\"﻿\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>'));\n      done();\n    });\n  });\n\n  it('TIFF', (_t, done) => {\n    sharp(fixtures.inputTiff).metadata((err, metadata) => {\n      if (err) throw err;\n      assert.strictEqual('tiff', metadata.format);\n      assert.strictEqual('undefined', typeof metadata.size);\n      assert.strictEqual(2464, metadata.width);\n      assert.strictEqual(3248, metadata.height);\n      assert.strictEqual('b-w', metadata.space);\n      assert.strictEqual(1, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual(300, metadata.density);\n      assert.strictEqual('undefined', typeof metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual(false, metadata.hasAlpha);\n      assert.strictEqual(1, metadata.orientation);\n      assert.strictEqual(2464, metadata.autoOrient.width);\n      assert.strictEqual(3248, metadata.autoOrient.height);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      assert.strictEqual('undefined', typeof metadata.xmp);\n      assert.strictEqual('undefined', typeof metadata.xmpAsString);\n      assert.strictEqual('inch', metadata.resolutionUnit);\n      done();\n    });\n  });\n\n  it('Multipage TIFF', (_t, done) => {\n    sharp(fixtures.inputTiffMultipage).metadata((err, metadata) => {\n      if (err) throw err;\n      assert.strictEqual('tiff', metadata.format);\n      assert.strictEqual('undefined', typeof metadata.size);\n      assert.strictEqual(2464, metadata.width);\n      assert.strictEqual(3248, metadata.height);\n      assert.strictEqual('b-w', metadata.space);\n      assert.strictEqual(1, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual(300, metadata.density);\n      assert.strictEqual('undefined', typeof metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(2, metadata.pages);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual(false, metadata.hasAlpha);\n      assert.strictEqual(1, metadata.orientation);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      done();\n    });\n  });\n\n  it('PNG', (_t, done) => {\n    sharp(fixtures.inputPng).metadata((err, metadata) => {\n      if (err) throw err;\n      assert.strictEqual('png', metadata.format);\n      assert.strictEqual('undefined', typeof metadata.size);\n      assert.strictEqual(2809, metadata.width);\n      assert.strictEqual(2074, metadata.height);\n      assert.strictEqual('b-w', metadata.space);\n      assert.strictEqual(1, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual(300, metadata.density);\n      assert.strictEqual('undefined', typeof metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual(false, metadata.hasAlpha);\n      assert.strictEqual('undefined', typeof metadata.orientation);\n      assert.strictEqual(2809, metadata.autoOrient.width);\n      assert.strictEqual(2074, metadata.autoOrient.height);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      done();\n    });\n  });\n\n  it('PNG with comment', (_t, done) => {\n    sharp(fixtures.inputPngTestJoinChannel).metadata((err, metadata) => {\n      if (err) throw err;\n      assert.strictEqual('png', metadata.format);\n      assert.strictEqual('undefined', typeof metadata.size);\n      assert.strictEqual(320, metadata.width);\n      assert.strictEqual(240, metadata.height);\n      assert.strictEqual('b-w', metadata.space);\n      assert.strictEqual(1, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual(72, metadata.density);\n      assert.strictEqual('undefined', typeof metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual(false, metadata.hasAlpha);\n      assert.strictEqual('undefined', typeof metadata.orientation);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      assert.strictEqual(1, metadata.comments.length);\n      assert.strictEqual('Comment', metadata.comments[0].keyword);\n      assert.strictEqual('Created with GIMP', metadata.comments[0].text);\n      done();\n    });\n  });\n\n  it('Transparent PNG', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency).metadata((err, metadata) => {\n      if (err) throw err;\n      assert.strictEqual('png', metadata.format);\n      assert.strictEqual('undefined', typeof metadata.size);\n      assert.strictEqual(2048, metadata.width);\n      assert.strictEqual(1536, metadata.height);\n      assert.strictEqual('srgb', metadata.space);\n      assert.strictEqual(4, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual(72, metadata.density);\n      assert.strictEqual('undefined', typeof metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual(true, metadata.hasAlpha);\n      assert.strictEqual('undefined', typeof metadata.orientation);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      done();\n    });\n  });\n\n  it('PNG with greyscale bKGD chunk - 8 bit', async () => {\n    const data = await sharp(fixtures.inputPng8BitGreyBackground).metadata();\n    assert.deepStrictEqual(data, {\n      background: {\n        gray: 0\n      },\n      bitsPerSample: 8,\n      channels: 2,\n      density: 72,\n      depth: 'uchar',\n      format: 'png',\n      hasAlpha: true,\n      hasProfile: false,\n      height: 32,\n      isPalette: false,\n      isProgressive: false,\n      space: 'b-w',\n      width: 32,\n      autoOrient: {\n        width: 32,\n        height: 32\n      }\n    });\n  });\n\n  it('PNG with greyscale bKGD chunk - 16 bit', async () => {\n    const data = await sharp(fixtures.inputPng16BitGreyBackground).metadata();\n    assert.deepStrictEqual(data, {\n      background: {\n        gray: 67\n      },\n      bitsPerSample: 16,\n      channels: 2,\n      density: 72,\n      depth: 'ushort',\n      format: 'png',\n      hasAlpha: true,\n      hasProfile: false,\n      height: 32,\n      isPalette: false,\n      isProgressive: false,\n      space: 'grey16',\n      width: 32,\n      autoOrient: {\n        width: 32,\n        height: 32\n      }\n    });\n  });\n\n  it('WebP', (_t, done) => {\n    sharp(fixtures.inputWebP).metadata((err, metadata) => {\n      if (err) throw err;\n      assert.strictEqual('webp', metadata.format);\n      assert.strictEqual('undefined', typeof metadata.size);\n      assert.strictEqual(1024, metadata.width);\n      assert.strictEqual(772, metadata.height);\n      assert.strictEqual('srgb', metadata.space);\n      assert.strictEqual(3, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual('undefined', typeof metadata.density);\n      assert.strictEqual('undefined', typeof metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual(false, metadata.hasAlpha);\n      assert.strictEqual('undefined', typeof metadata.orientation);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      done();\n    });\n  });\n\n  it('Animated WebP', () =>\n    sharp(fixtures.inputWebPAnimated)\n      .metadata()\n      .then(({\n        format, width, height, space, channels, depth,\n        isProgressive, pages, loop, delay, hasProfile,\n        hasAlpha\n      }) => {\n        assert.strictEqual(format, 'webp');\n        assert.strictEqual(width, 80);\n        assert.strictEqual(height, 80);\n        assert.strictEqual(space, 'srgb');\n        assert.strictEqual(channels, 4);\n        assert.strictEqual(depth, 'uchar');\n        assert.strictEqual(isProgressive, false);\n        assert.strictEqual(pages, 9);\n        assert.strictEqual(loop, 0);\n        assert.deepStrictEqual(delay, [120, 120, 90, 120, 120, 90, 120, 90, 30]);\n        assert.strictEqual(hasProfile, false);\n        assert.strictEqual(hasAlpha, true);\n      })\n  );\n\n  it('Animated WebP with all pages', () =>\n    sharp(fixtures.inputWebPAnimated, { pages: -1 })\n      .metadata()\n      .then(({\n        format, width, height, space, channels, depth,\n        isProgressive, pages, pageHeight, loop, delay,\n        hasProfile, hasAlpha\n      }) => {\n        assert.strictEqual(format, 'webp');\n        assert.strictEqual(width, 80);\n        assert.strictEqual(height, 720);\n        assert.strictEqual(space, 'srgb');\n        assert.strictEqual(channels, 4);\n        assert.strictEqual(depth, 'uchar');\n        assert.strictEqual(isProgressive, false);\n        assert.strictEqual(pages, 9);\n        assert.strictEqual(pageHeight, 80);\n        assert.strictEqual(loop, 0);\n        assert.deepStrictEqual(delay, [120, 120, 90, 120, 120, 90, 120, 90, 30]);\n        assert.strictEqual(hasProfile, false);\n        assert.strictEqual(hasAlpha, true);\n      })\n  );\n\n  it('Animated WebP with limited looping', () =>\n    sharp(fixtures.inputWebPAnimatedLoop3)\n      .metadata()\n      .then(({\n        format, width, height, space, channels, depth,\n        isProgressive, pages, loop, delay, hasProfile,\n        hasAlpha\n      }) => {\n        assert.strictEqual(format, 'webp');\n        assert.strictEqual(width, 370);\n        assert.strictEqual(height, 285);\n        assert.strictEqual(space, 'srgb');\n        assert.strictEqual(channels, 4);\n        assert.strictEqual(depth, 'uchar');\n        assert.strictEqual(isProgressive, false);\n        assert.strictEqual(pages, 10);\n        assert.strictEqual(loop, 3);\n        assert.deepStrictEqual(delay, [...Array(9).fill(3000), 15000]);\n        assert.strictEqual(hasProfile, false);\n        assert.strictEqual(hasAlpha, true);\n      })\n  );\n\n  it('GIF', (_t, done) => {\n    sharp(fixtures.inputGif).metadata((err, metadata) => {\n      if (err) throw err;\n      assert.strictEqual('gif', metadata.format);\n      assert.strictEqual('undefined', typeof metadata.size);\n      assert.strictEqual(800, metadata.width);\n      assert.strictEqual(533, metadata.height);\n      assert.strictEqual(3, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual('undefined', typeof metadata.density);\n      assert.strictEqual('undefined', typeof metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual('undefined', typeof metadata.orientation);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      assert.deepStrictEqual(metadata.background, { r: 138, g: 148, b: 102 });\n      done();\n    });\n  });\n  it('GIF grey+alpha', (_t, done) => {\n    sharp(fixtures.inputGifGreyPlusAlpha).metadata((err, metadata) => {\n      if (err) throw err;\n      assert.strictEqual('gif', metadata.format);\n      assert.strictEqual('undefined', typeof metadata.size);\n      assert.strictEqual(2, metadata.width);\n      assert.strictEqual(1, metadata.height);\n      assert.strictEqual(4, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual('undefined', typeof metadata.density);\n      assert.strictEqual('undefined', typeof metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual('undefined', typeof metadata.orientation);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      done();\n    });\n  });\n\n  it('Animated GIF', () =>\n    sharp(fixtures.inputGifAnimated)\n      .metadata()\n      .then(({\n        format, width, height, space, channels, depth,\n        isProgressive, pages, loop, delay, background,\n        hasProfile, hasAlpha\n      }) => {\n        assert.strictEqual(format, 'gif');\n        assert.strictEqual(width, 80);\n        assert.strictEqual(height, 80);\n        assert.strictEqual(space, 'srgb');\n        assert.strictEqual(channels, 4);\n        assert.strictEqual(depth, 'uchar');\n        assert.strictEqual(isProgressive, false);\n        assert.strictEqual(pages, 30);\n        assert.strictEqual(loop, 0);\n        assert.deepStrictEqual(delay, Array(30).fill(30));\n        assert.deepStrictEqual(background, { r: 0, g: 0, b: 0 });\n        assert.strictEqual(hasProfile, false);\n        assert.strictEqual(hasAlpha, true);\n      })\n  );\n\n  it('Animated GIF with limited looping', () =>\n    sharp(fixtures.inputGifAnimatedLoop3)\n      .metadata()\n      .then(({\n        format, width, height, space, channels, depth,\n        isProgressive, pages, loop, delay, hasProfile,\n        hasAlpha\n      }) => {\n        assert.strictEqual(format, 'gif');\n        assert.strictEqual(width, 370);\n        assert.strictEqual(height, 285);\n        assert.strictEqual(space, 'srgb');\n        assert.strictEqual(channels, 4);\n        assert.strictEqual(depth, 'uchar');\n        assert.strictEqual(isProgressive, false);\n        assert.strictEqual(pages, 10);\n        assert.strictEqual(loop, 3);\n        assert.deepStrictEqual(delay, [...Array(9).fill(3000), 15000]);\n        assert.strictEqual(hasProfile, false);\n        assert.strictEqual(hasAlpha, true);\n      })\n  );\n\n  it('vips', () =>\n    sharp(fixtures.inputV)\n      .metadata()\n      .then(metadata => {\n        assert.strictEqual('vips', metadata.format);\n        assert.strictEqual('undefined', typeof metadata.size);\n        assert.strictEqual(70, metadata.width);\n        assert.strictEqual(60, metadata.height);\n        assert.strictEqual(3, metadata.channels);\n        assert.strictEqual('uchar', metadata.depth);\n        assert.strictEqual(72, metadata.density);\n        assert.strictEqual('undefined', typeof metadata.chromaSubsampling);\n        assert.strictEqual(false, metadata.isProgressive);\n        assert.strictEqual(false, metadata.hasProfile);\n        assert.strictEqual(false, metadata.hasAlpha);\n        assert.strictEqual('undefined', typeof metadata.orientation);\n        assert.strictEqual('undefined', typeof metadata.exif);\n        assert.strictEqual('undefined', typeof metadata.icc);\n      })\n  );\n\n  it('File in, Promise out', (_t, done) => {\n    sharp(fixtures.inputJpg).metadata().then((metadata) => {\n      assert.strictEqual('jpeg', metadata.format);\n      assert.strictEqual('undefined', typeof metadata.size);\n      assert.strictEqual(2725, metadata.width);\n      assert.strictEqual(2225, metadata.height);\n      assert.strictEqual('srgb', metadata.space);\n      assert.strictEqual(3, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual(true, ['undefined', 'number'].includes(typeof metadata.density));\n      assert.strictEqual('4:2:0', metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual(false, metadata.hasAlpha);\n      assert.strictEqual('undefined', typeof metadata.orientation);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      done();\n    });\n  });\n\n  it('Non-existent file in, Promise out', async () =>\n    assert.rejects(\n      () => sharp('fail').metadata(),\n      (err) => {\n        assert.strictEqual(err.message, 'Input file is missing: fail');\n        assert(err.stack.includes('at Sharp.metadata'));\n        assert(err.stack.includes(__filename));\n        return true;\n      }\n    )\n  );\n\n  it('Invalid stream in, callback out', (_t, done) => {\n    fs.createReadStream(__filename).pipe(\n      sharp().metadata((err) => {\n        assert.strictEqual(err.message, 'Input buffer contains unsupported image format');\n        assert(err.stack.includes('at Sharp.metadata'));\n        assert(err.stack.includes(__filename));\n        done();\n      })\n    );\n  });\n\n  it('Stream in, Promise out', (_t, done) => {\n    const readable = fs.createReadStream(fixtures.inputJpg);\n    const pipeline = sharp();\n    pipeline.metadata().then((metadata) => {\n      assert.strictEqual('jpeg', metadata.format);\n      assert.strictEqual(829183, metadata.size);\n      assert.strictEqual(2725, metadata.width);\n      assert.strictEqual(2225, metadata.height);\n      assert.strictEqual('srgb', metadata.space);\n      assert.strictEqual(3, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual(true, ['undefined', 'number'].includes(typeof metadata.density));\n      assert.strictEqual('4:2:0', metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual(false, metadata.hasAlpha);\n      assert.strictEqual('undefined', typeof metadata.orientation);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      done();\n    }).catch(_t, done);\n    readable.pipe(pipeline);\n  });\n\n  it('Stream in, rejected Promise out', () => {\n    const pipeline = sharp();\n    fs\n      .createReadStream(__filename)\n      .pipe(pipeline);\n\n    return pipeline\n      .metadata()\n      .then(\n        () => Promise.reject(new Error('Expected metadata to reject')),\n        err => assert.strictEqual(err.message, 'Input buffer contains unsupported image format')\n      );\n  });\n\n  it('Stream in, finish event fires before metadata is requested', (_t, done) => {\n    const create = { width: 1, height: 1, channels: 3, background: 'red' };\n    const image1 = sharp({ create }).png().pipe(sharp());\n    const image2 = sharp({ create }).png().pipe(sharp());\n    setTimeout(async () => {\n      const data1 = await image1.metadata();\n      assert.strictEqual('png', data1.format);\n      const data2 = await image2.metadata();\n      assert.strictEqual('png', data2.format);\n      done();\n    }, 500);\n  });\n\n  it('Stream', (_t, done) => {\n    const readable = fs.createReadStream(fixtures.inputJpg);\n    const pipeline = sharp().metadata((err, metadata) => {\n      if (err) throw err;\n      assert.strictEqual('jpeg', metadata.format);\n      assert.strictEqual(829183, metadata.size);\n      assert.strictEqual(2725, metadata.width);\n      assert.strictEqual(2225, metadata.height);\n      assert.strictEqual('srgb', metadata.space);\n      assert.strictEqual(3, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual(true, ['undefined', 'number'].includes(typeof metadata.density));\n      assert.strictEqual('4:2:0', metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual(false, metadata.hasAlpha);\n      assert.strictEqual('undefined', typeof metadata.orientation);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      done();\n    });\n    readable.pipe(pipeline);\n  });\n\n  it('Resize to half width using metadata', (_t, done) => {\n    const image = sharp(fixtures.inputJpg);\n    image.metadata((err, metadata) => {\n      if (err) throw err;\n      assert.strictEqual('jpeg', metadata.format);\n      assert.strictEqual('undefined', typeof metadata.size);\n      assert.strictEqual(2725, metadata.width);\n      assert.strictEqual(2225, metadata.height);\n      assert.strictEqual('srgb', metadata.space);\n      assert.strictEqual(3, metadata.channels);\n      assert.strictEqual('uchar', metadata.depth);\n      assert.strictEqual(true, ['undefined', 'number'].includes(typeof metadata.density));\n      assert.strictEqual('4:2:0', metadata.chromaSubsampling);\n      assert.strictEqual(false, metadata.isProgressive);\n      assert.strictEqual(false, metadata.hasProfile);\n      assert.strictEqual(false, metadata.hasAlpha);\n      assert.strictEqual('undefined', typeof metadata.orientation);\n      assert.strictEqual('undefined', typeof metadata.exif);\n      assert.strictEqual('undefined', typeof metadata.icc);\n      image.resize(Math.floor(metadata.width / 2)).toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(1362, info.width);\n        assert.strictEqual(1112, info.height);\n        done();\n      });\n    });\n  });\n\n  it('Keep EXIF metadata and add sRGB profile after a resize', (_t, done) => {\n    sharp(fixtures.inputJpgWithExif)\n      .resize(320, 240)\n      .withMetadata()\n      .toBuffer((err, buffer) => {\n        if (err) throw err;\n        sharp(buffer).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(true, metadata.hasProfile);\n          assert.strictEqual(8, metadata.orientation);\n          assert.strictEqual(320, metadata.width);\n          assert.strictEqual(240, metadata.height);\n          assert.strictEqual(240, metadata.autoOrient.width);\n          assert.strictEqual(320, metadata.autoOrient.height);\n          assert.strictEqual('object', typeof metadata.exif);\n          assert.strictEqual(true, metadata.exif instanceof Buffer);\n          // EXIF\n          const exif = exifReader(metadata.exif);\n          assert.strictEqual('object', typeof exif);\n          assert.strictEqual('object', typeof exif.Image);\n          assert.strictEqual('number', typeof exif.Image.XResolution);\n          // ICC\n          assert.strictEqual('object', typeof metadata.icc);\n          assert.strictEqual(true, metadata.icc instanceof Buffer);\n          const profile = icc.parse(metadata.icc);\n          assert.strictEqual('object', typeof profile);\n          assert.strictEqual('RGB', profile.colorSpace);\n          assert.strictEqual('Perceptual', profile.intent);\n          assert.strictEqual('Monitor', profile.deviceClass);\n          done();\n        });\n      });\n  });\n\n  it('keep existing ICC profile', async () => {\n    const data = await sharp(fixtures.inputJpgWithExif)\n      .keepIccProfile()\n      .toBuffer();\n\n    const metadata = await sharp(data).metadata();\n    const { description } = icc.parse(metadata.icc);\n    assert.strictEqual(description, 'Generic RGB Profile');\n  });\n\n  it('keep existing CMYK input profile for CMYK output', async () => {\n    const data = await sharp(fixtures.inputJpgWithCmykProfile)\n      .keepIccProfile()\n      .toColourspace('cmyk')\n      .toBuffer();\n\n    const metadata = await sharp(data).metadata();\n    assert.strictEqual(metadata.channels, 4);\n    const { description } = icc.parse(metadata.icc);\n    assert.strictEqual(description, 'U.S. Web Coated (SWOP) v2');\n  });\n\n  it('transform with but discard existing RGB input profile for CMYK output', async () => {\n    const data = await sharp(fixtures.inputJpgWithExif)\n      .keepIccProfile()\n      .toColourspace('cmyk')\n      .toBuffer();\n\n    const metadata = await sharp(data).metadata();\n    assert.strictEqual(metadata.channels, 4);\n    assert.strictEqual(metadata.icc, undefined);\n  });\n\n  it('keep existing ICC profile, avoid colour transform', async () => {\n    const [r, g, b] = await sharp(fixtures.inputPngWithProPhotoProfile)\n      .keepIccProfile()\n      .raw()\n      .toBuffer();\n\n    assert.strictEqual(r, 131);\n    assert.strictEqual(g, 141);\n    assert.strictEqual(b, 192);\n  });\n\n  it('keep existing CMYK ICC profile', async () => {\n    const data = await sharp(fixtures.inputJpgWithCmykProfile)\n      .pipelineColourspace('cmyk')\n      .toColourspace('cmyk')\n      .keepIccProfile()\n      .toBuffer();\n\n    const metadata = await sharp(data).metadata();\n    assert.strictEqual(metadata.channels, 4);\n    const { description } = icc.parse(metadata.icc);\n    assert.strictEqual(description, 'U.S. Web Coated (SWOP) v2');\n  });\n\n  it('transform to ICC profile and attach', async () => {\n    const data = await sharp({ create })\n      .png()\n      .withIccProfile('p3', { attach: true })\n      .toBuffer();\n\n    const metadata = await sharp(data).metadata();\n    const { description } = icc.parse(metadata.icc);\n    assert.strictEqual(description, 'sP3C');\n  });\n\n  it('transform to ICC profile but do not attach', async () => {\n    const data = await sharp({ create })\n      .png()\n      .withIccProfile('p3', { attach: false })\n      .toBuffer();\n\n    const metadata = await sharp(data).metadata();\n    assert.strictEqual(3, metadata.channels);\n    assert.strictEqual(undefined, metadata.icc);\n  });\n\n  it('transform to invalid ICC profile emits warning', async () => {\n    const img = sharp({ create })\n      .png()\n      .withIccProfile(fixtures.path('invalid-illuminant.icc'));\n\n    const warningsEmitted = [];\n    img.on('warning', (warning) => {\n      warningsEmitted.push(warning);\n    });\n\n    const data = await img.toBuffer();\n    assert.strict(warningsEmitted.includes('Invalid profile'));\n\n    const metadata = await sharp(data).metadata();\n    assert.strictEqual(3, metadata.channels);\n    assert.strictEqual(undefined, metadata.icc);\n  });\n\n  it('Apply CMYK output ICC profile', (_t, done) => {\n    const output = fixtures.path('output.icc-cmyk.jpg');\n    sharp(fixtures.inputJpg)\n      .resize(64)\n      .withIccProfile('cmyk')\n      .toFile(output, (err) => {\n        if (err) throw err;\n        sharp(output).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(true, metadata.hasProfile);\n          assert.strictEqual('cmyk', metadata.space);\n          assert.strictEqual(4, metadata.channels);\n          // ICC\n          assert.strictEqual('object', typeof metadata.icc);\n          assert.strictEqual(true, metadata.icc instanceof Buffer);\n          const profile = icc.parse(metadata.icc);\n          assert.strictEqual('object', typeof profile);\n          assert.strictEqual('CMYK', profile.colorSpace);\n          assert.strictEqual('Relative', profile.intent);\n          assert.strictEqual('Printer', profile.deviceClass);\n        });\n        fixtures.assertSimilar(output, fixtures.expected('icc-cmyk.jpg'), { threshold: 1 }, done);\n      });\n  });\n\n  it('Apply custom output ICC profile', (_t, done) => {\n    const output = fixtures.path('output.hilutite.jpg');\n    sharp(fixtures.inputJpg)\n      .resize(64)\n      .withIccProfile(fixtures.path('hilutite.icm'))\n      .toFile(output, (err) => {\n        if (err) throw err;\n        fixtures.assertMaxColourDistance(output, fixtures.expected('hilutite.jpg'), 9);\n        done();\n      });\n  });\n\n  it('Include metadata in output, enabled via empty object', () =>\n    sharp(fixtures.inputJpgWithExif)\n      .withMetadata({})\n      .toBuffer()\n      .then((buffer) => sharp(buffer)\n        .metadata()\n        .then(metadata => {\n          assert.strictEqual(true, metadata.hasProfile);\n          assert.strictEqual(8, metadata.orientation);\n          assert.strictEqual('object', typeof metadata.exif);\n          assert.strictEqual(true, metadata.exif instanceof Buffer);\n          // EXIF\n          const exif = exifReader(metadata.exif);\n          assert.strictEqual('object', typeof exif);\n          assert.strictEqual('object', typeof exif.Image);\n          assert.strictEqual('number', typeof exif.Image.XResolution);\n          // ICC\n          assert.strictEqual('object', typeof metadata.icc);\n          assert.strictEqual(true, metadata.icc instanceof Buffer);\n          const profile = icc.parse(metadata.icc);\n          assert.strictEqual('object', typeof profile);\n          assert.strictEqual('RGB', profile.colorSpace);\n          assert.strictEqual('Perceptual', profile.intent);\n          assert.strictEqual('Monitor', profile.deviceClass);\n        })\n      )\n  );\n\n  it('Remove EXIF metadata after a resize', (_t, done) => {\n    sharp(fixtures.inputJpgWithExif)\n      .resize(320, 240)\n      .toBuffer((err, buffer) => {\n        if (err) throw err;\n        sharp(buffer).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(false, metadata.hasProfile);\n          assert.strictEqual('undefined', typeof metadata.orientation);\n          assert.strictEqual('undefined', typeof metadata.exif);\n          assert.strictEqual('undefined', typeof metadata.icc);\n          done();\n        });\n      });\n  });\n\n  it('Remove metadata from PNG output', (_t, done) => {\n    sharp(fixtures.inputJpgWithExif)\n      .png()\n      .toBuffer((err, buffer) => {\n        if (err) throw err;\n        sharp(buffer).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(false, metadata.hasProfile);\n          assert.strictEqual('undefined', typeof metadata.orientation);\n          assert.strictEqual('undefined', typeof metadata.exif);\n          assert.strictEqual('undefined', typeof metadata.icc);\n          done();\n        });\n      });\n  });\n\n  it('Add EXIF metadata to JPEG', async () => {\n    const data = await sharp({ create })\n      .jpeg()\n      .withMetadata({\n        exif: {\n          IFD0: { Software: 'sharp' },\n          IFD2: { ExposureTime: '0.2' }\n        }\n      })\n      .toBuffer();\n\n    const { exif } = await sharp(data).metadata();\n    const parsedExif = exifReader(exif);\n    assert.strictEqual(parsedExif.Image.Software, 'sharp');\n    assert.strictEqual(parsedExif.Photo.ExposureTime, 0.2);\n  });\n\n  it('Set density of JPEG', async () => {\n    const data = await sharp({ create })\n      .withMetadata({\n        density: 300\n      })\n      .jpeg()\n      .toBuffer();\n\n    const { density } = await sharp(data).metadata();\n    assert.strictEqual(density, 300);\n  });\n\n  it('Set density of PNG', async () => {\n    const data = await sharp({ create })\n      .withMetadata({\n        density: 96\n      })\n      .png()\n      .toBuffer();\n\n    const { density } = await sharp(data).metadata();\n    assert.strictEqual(density, 96);\n  });\n\n  it('chromaSubsampling 4:4:4:4 CMYK JPEG', () => sharp(fixtures.inputJpgWithCmykProfile)\n      .metadata()\n      .then((metadata) => {\n        assert.strictEqual('4:4:4:4', metadata.chromaSubsampling);\n      }));\n\n  it('chromaSubsampling 4:4:4 RGB JPEG', () => sharp(fixtures.inputJpg)\n      .resize(10, 10)\n      .jpeg({ chromaSubsampling: '4:4:4' })\n      .toBuffer()\n      .then((data) => sharp(data)\n          .metadata()\n          .then((metadata) => {\n            assert.strictEqual('4:4:4', metadata.chromaSubsampling);\n          })));\n\n  it('isProgressive JPEG', () => sharp(fixtures.inputJpg)\n      .resize(10, 10)\n      .jpeg({ progressive: true })\n      .toBuffer()\n      .then((data) => sharp(data)\n          .metadata()\n          .then((metadata) => {\n            assert.strictEqual(true, metadata.isProgressive);\n          })));\n\n  it('isProgressive PNG', () => sharp(fixtures.inputJpg)\n      .resize(10, 10)\n      .png({ progressive: true })\n      .toBuffer()\n      .then((data) => sharp(data)\n          .metadata()\n          .then((metadata) => {\n            assert.strictEqual(true, metadata.isProgressive);\n          })));\n\n  it('16-bit TIFF with TIFFTAG_PHOTOSHOP metadata', () =>\n    sharp(fixtures.inputTifftagPhotoshop)\n      .metadata()\n      .then(metadata => {\n        assert.strictEqual(metadata.format, 'tiff');\n        assert.strictEqual(metadata.width, 317);\n        assert.strictEqual(metadata.height, 211);\n        assert.strictEqual(metadata.space, 'rgb16');\n        assert.strictEqual(metadata.channels, 3);\n        assert.strictEqual(typeof metadata.tifftagPhotoshop, 'object');\n        assert.strictEqual(metadata.tifftagPhotoshop instanceof Buffer, true);\n        assert.strictEqual(metadata.tifftagPhotoshop.length, 6634);\n      })\n  );\n\n  it('AVIF', async () => {\n    const metadata = await sharp(fixtures.inputAvif).metadata();\n    assert.deepStrictEqual(metadata, {\n      format: 'heif',\n      width: 2048,\n      height: 858,\n      space: 'srgb',\n      channels: 3,\n      depth: 'uchar',\n      isProgressive: false,\n      isPalette: false,\n      bitsPerSample: 8,\n      pages: 1,\n      pagePrimary: 0,\n      compression: 'av1',\n      hasProfile: false,\n      hasAlpha: false,\n      autoOrient: {\n        width: 2048,\n        height: 858\n      }\n    });\n  });\n\n  it('withMetadata adds default sRGB profile', async () => {\n    const data = await sharp(fixtures.inputJpg)\n      .resize(32, 24)\n      .withMetadata()\n      .toBuffer();\n\n    const metadata = await sharp(data).metadata();\n    const { colorSpace, deviceClass, intent } = icc.parse(metadata.icc);\n    assert.strictEqual(colorSpace, 'RGB');\n    assert.strictEqual(deviceClass, 'Monitor');\n    assert.strictEqual(intent, 'Perceptual');\n  });\n\n  it('withMetadata adds default sRGB profile to RGB16', async () => {\n    const data = await sharp({ create })\n      .toColorspace('rgb16')\n      .png()\n      .withMetadata()\n      .toBuffer();\n\n    const metadata = await sharp(data).metadata();\n    assert.strictEqual(metadata.depth, 'ushort');\n\n    const { description } = icc.parse(metadata.icc);\n    assert.strictEqual(description, 'sRGB');\n  });\n\n  it('withMetadata adds P3 profile to 16-bit PNG', async () => {\n    const data = await sharp({ create })\n      .toColorspace('rgb16')\n      .png()\n      .withMetadata({ icc: 'p3' })\n      .toBuffer();\n\n    const metadata = await sharp(data).metadata();\n    assert.strictEqual(metadata.depth, 'ushort');\n\n    const { description } = icc.parse(metadata.icc);\n    assert.strictEqual(description, 'sP3C');\n  });\n\n  it('File input with corrupt header fails gracefully', (_t, done) => {\n    sharp(fixtures.inputJpgWithCorruptHeader)\n      .metadata((err) => {\n        assert.strictEqual(true, !!err);\n        assert.ok(err.message.includes('Input file has corrupt header: VipsJpeg: premature end of'), err);\n        done();\n      });\n  });\n\n  it('Buffer input with corrupt header fails gracefully', (_t, done) => {\n    sharp(fs.readFileSync(fixtures.inputJpgWithCorruptHeader))\n      .metadata((err) => {\n        assert.strictEqual(true, !!err);\n        assert.ok(err.message.includes('Input buffer has corrupt header: VipsJpeg: premature end of'), err);\n        done();\n      });\n  });\n\n  it('Lossless JPEG', async () => {\n    const metadata = await sharp(fixtures.inputJpgLossless).metadata();\n    assert.deepStrictEqual(metadata, {\n      format: 'jpeg',\n      width: 227,\n      height: 149,\n      space: 'srgb',\n      channels: 3,\n      depth: 'uchar',\n      density: 72,\n      chromaSubsampling: '4:4:4',\n      isProgressive: false,\n      isPalette: false,\n      hasProfile: false,\n      hasAlpha: false,\n      autoOrient: { width: 227, height: 149 }\n    });\n  });\n\n  it('keepExif maintains all EXIF metadata', async () => {\n    const data1 = await sharp({ create })\n      .withExif({\n        IFD0: {\n          Copyright: 'Test 1',\n          Software: 'sharp'\n        }\n      })\n      .jpeg()\n      .toBuffer();\n\n    const data2 = await sharp(data1)\n      .keepExif()\n      .toBuffer();\n\n    const md2 = await sharp(data2).metadata();\n    const exif2 = exifReader(md2.exif);\n    assert.strictEqual(exif2.Image.Copyright, 'Test 1');\n    assert.strictEqual(exif2.Image.Software, 'sharp');\n  });\n\n  it('withExif replaces all EXIF metadata', async () => {\n    const data1 = await sharp({ create })\n      .withExif({\n        IFD0: {\n          Copyright: 'Test 1',\n          Software: 'sharp'\n        }\n      })\n      .jpeg()\n      .toBuffer();\n\n    const md1 = await sharp(data1).metadata();\n    const exif1 = exifReader(md1.exif);\n    assert.strictEqual(exif1.Image.Copyright, 'Test 1');\n    assert.strictEqual(exif1.Image.Software, 'sharp');\n\n    const data2 = await sharp(data1)\n      .withExif({\n        IFD0: {\n          Copyright: 'Test 2'\n        }\n      })\n      .toBuffer();\n\n    const md2 = await sharp(data2).metadata();\n    const exif2 = exifReader(md2.exif);\n    assert.strictEqual(exif2.Image.Copyright, 'Test 2');\n    assert.strictEqual(exif2.Image.Software, undefined);\n  });\n\n  it('withExifMerge merges all EXIF metadata', async () => {\n    const data1 = await sharp({ create })\n      .withExif({\n        IFD0: {\n          Copyright: 'Test 1'\n        }\n      })\n      .jpeg()\n      .toBuffer();\n\n    const md1 = await sharp(data1).metadata();\n    const exif1 = exifReader(md1.exif);\n    assert.strictEqual(exif1.Image.Copyright, 'Test 1');\n    assert.strictEqual(exif1.Image.Software, undefined);\n\n    const data2 = await sharp(data1)\n      .withExifMerge({\n        IFD0: {\n          Copyright: 'Test 2',\n          Software: 'sharp'\n\n        }\n      })\n      .toBuffer();\n\n    const md2 = await sharp(data2).metadata();\n    const exif2 = exifReader(md2.exif);\n    assert.strictEqual(exif2.Image.Copyright, 'Test 2');\n    assert.strictEqual(exif2.Image.Software, 'sharp');\n  });\n\n  describe('XMP metadata tests', () => {\n    it('withMetadata preserves existing XMP metadata from input', async () => {\n      const data = await sharp(fixtures.inputJpgWithIptcAndXmp)\n        .resize(320, 240)\n        .withMetadata()\n        .toBuffer();\n\n      const metadata = await sharp(data).metadata();\n      assert.strictEqual('object', typeof metadata.xmp);\n      assert.strictEqual(true, metadata.xmp instanceof Buffer);\n      assert.strictEqual(true, metadata.xmp.length > 0);\n      // Check that XMP starts with the expected XML declaration\n      assert.strictEqual(metadata.xmp.indexOf(Buffer.from('<?xpacket begin=\"')), 0);\n    });\n\n    it('keepXmp preserves existing XMP metadata from input', async () => {\n      const data = await sharp(fixtures.inputJpgWithIptcAndXmp)\n        .resize(320, 240)\n        .keepXmp()\n        .toBuffer();\n\n      const metadata = await sharp(data).metadata();\n      assert.strictEqual('object', typeof metadata.xmp);\n      assert.strictEqual(true, metadata.xmp instanceof Buffer);\n      assert.strictEqual(true, metadata.xmp.length > 0);\n      // Check that XMP starts with the expected XML declaration\n      assert.strictEqual(metadata.xmp.indexOf(Buffer.from('<?xpacket begin=\"')), 0);\n    });\n\n    it('withXmp with custom XMP replaces existing XMP', async () => {\n      const customXmp = '<?xml version=\"1.0\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"><dc:creator><rdf:Seq><rdf:li>Test Creator</rdf:li></rdf:Seq></dc:creator><dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">Test Title</rdf:li></rdf:Alt></dc:title></rdf:Description></rdf:RDF></x:xmpmeta>';\n\n      const data = await sharp(fixtures.inputJpgWithIptcAndXmp)\n        .resize(320, 240)\n        .withXmp(customXmp)\n        .toBuffer();\n\n      const metadata = await sharp(data).metadata();\n      assert.strictEqual('object', typeof metadata.xmp);\n      assert.strictEqual(true, metadata.xmp instanceof Buffer);\n\n      // Check that the XMP contains our custom content\n      const xmpString = metadata.xmp.toString();\n      assert.strictEqual(true, xmpString.includes('Test Creator'));\n      assert.strictEqual(true, xmpString.includes('Test Title'));\n    });\n\n    it('withXmp with custom XMP buffer on image without existing XMP', async () => {\n      const customXmp = '<?xml version=\"1.0\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"><dc:description><rdf:Alt><rdf:li xml:lang=\"x-default\">Added via Sharp</rdf:li></rdf:Alt></dc:description></rdf:Description></rdf:RDF></x:xmpmeta>';\n\n      const data = await sharp(fixtures.inputJpg)\n        .resize(320, 240)\n        .withXmp(customXmp)\n        .toBuffer();\n\n      const metadata = await sharp(data).metadata();\n      assert.strictEqual('object', typeof metadata.xmp);\n      assert.strictEqual(true, metadata.xmp instanceof Buffer);\n\n      // Check that the XMP contains our custom content\n      const xmpString = metadata.xmp.toString();\n      assert.strictEqual(true, xmpString.includes('Added via Sharp'));\n    });\n\n    it('withXmp with valid XMP metadata for different image formats', async () => {\n      const customXmp = '<?xml version=\"1.0\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"><dc:subject><rdf:Bag><rdf:li>test</rdf:li><rdf:li>metadata</rdf:li></rdf:Bag></dc:subject></rdf:Description></rdf:RDF></x:xmpmeta>';\n\n      // Test with JPEG output\n      const jpegData = await sharp(fixtures.inputJpg)\n        .resize(100, 100)\n        .jpeg()\n        .withXmp(customXmp)\n        .toBuffer();\n\n      const jpegMetadata = await sharp(jpegData).metadata();\n      assert.strictEqual('object', typeof jpegMetadata.xmp);\n      assert.strictEqual(true, jpegMetadata.xmp instanceof Buffer);\n      assert.strictEqual(true, jpegMetadata.xmp.toString().includes('test'));\n\n      // Test with PNG output (PNG should also support XMP metadata)\n      const pngData = await sharp(fixtures.inputJpg)\n        .resize(100, 100)\n        .png()\n        .withXmp(customXmp)\n        .toBuffer();\n\n      const pngMetadata = await sharp(pngData).metadata();\n      // PNG format should preserve XMP metadata when using withXmp\n      assert.strictEqual('object', typeof pngMetadata.xmp);\n      assert.strictEqual(true, pngMetadata.xmp instanceof Buffer);\n      assert.strictEqual(true, pngMetadata.xmp.toString().includes('test'));\n\n      // Test with WebP output (WebP should also support XMP metadata)\n      const webpData = await sharp(fixtures.inputJpg)\n        .resize(100, 100)\n        .webp()\n        .withXmp(customXmp)\n        .toBuffer();\n\n      const webpMetadata = await sharp(webpData).metadata();\n      // WebP format should preserve XMP metadata when using withXmp\n      assert.strictEqual('object', typeof webpMetadata.xmp);\n      assert.strictEqual(true, webpMetadata.xmp instanceof Buffer);\n      assert.strictEqual(true, webpMetadata.xmp.toString().includes('test'));\n    });\n\n    it('XMP metadata persists through multiple operations', async () => {\n      const customXmp = '<?xml version=\"1.0\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"><dc:identifier>persistent-test</dc:identifier></rdf:Description></rdf:RDF></x:xmpmeta>';\n\n      const data = await sharp(fixtures.inputJpg)\n        .resize(320, 240)\n        .withXmp(customXmp)\n        .rotate(90)\n        .blur(1)\n        .sharpen()\n        .toBuffer();\n\n      const metadata = await sharp(data).metadata();\n      assert.strictEqual('object', typeof metadata.xmp);\n      assert.strictEqual(true, metadata.xmp instanceof Buffer);\n      assert.strictEqual(true, metadata.xmp.toString().includes('persistent-test'));\n    });\n\n    it('withXmp XMP works with WebP format specifically', async () => {\n      const webpXmp = '<?xml version=\"1.0\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"><dc:creator><rdf:Seq><rdf:li>WebP Creator</rdf:li></rdf:Seq></dc:creator><dc:format>image/webp</dc:format></rdf:Description></rdf:RDF></x:xmpmeta>';\n\n      const data = await sharp(fixtures.inputJpg)\n        .resize(120, 80)\n        .webp({ quality: 80 })\n        .withXmp(webpXmp)\n        .toBuffer();\n\n      const metadata = await sharp(data).metadata();\n      assert.strictEqual('webp', metadata.format);\n      assert.strictEqual('object', typeof metadata.xmp);\n      assert.strictEqual(true, metadata.xmp instanceof Buffer);\n\n      const xmpString = metadata.xmp.toString();\n      assert.strictEqual(true, xmpString.includes('WebP Creator'));\n      assert.strictEqual(true, xmpString.includes('image/webp'));\n    });\n\n    it('withXmp XMP validation - non-string input', () => {\n      assert.throws(\n        () => sharp().withXmp(123),\n        /Expected non-empty string for xmp but received 123 of type number/\n      );\n    });\n\n    it('withXmp XMP validation - null input', () => {\n      assert.throws(\n        () => sharp().withXmp(null),\n        /Expected non-empty string for xmp but received null of type object/\n      );\n    });\n\n    it('withXmp XMP validation - empty string', () => {\n      assert.throws(\n        () => sharp().withXmp(''),\n        /Expected non-empty string for xmp/\n      );\n    });\n  });\n\n  describe('Invalid parameters', () => {\n    it('String orientation', () => {\n      assert.throws(() => {\n        sharp().withMetadata({ orientation: 'zoinks' });\n      });\n    });\n    it('Negative orientation', () => {\n      assert.throws(() => {\n        sharp().withMetadata({ orientation: -1 });\n      });\n    });\n    it('Zero orientation', () => {\n      assert.throws(() => {\n        sharp().withMetadata({ orientation: 0 });\n      });\n    });\n    it('Too large orientation', () => {\n      assert.throws(() => {\n        sharp().withMetadata({ orientation: 9 });\n      });\n    });\n    it('Non-numeric density', () => {\n      assert.throws(() => {\n        sharp().withMetadata({ density: '1' });\n      });\n    });\n    it('Negative density', () => {\n      assert.throws(() => {\n        sharp().withMetadata({ density: -1 });\n      });\n    });\n    it('Non string icc', () => {\n      assert.throws(() => {\n        sharp().withMetadata({ icc: true });\n      });\n    });\n    it('Non object exif', () => {\n      assert.throws(() => {\n        sharp().withMetadata({ exif: false });\n      });\n    });\n    it('Non string value in object exif', () => {\n      assert.throws(() => {\n        sharp().withMetadata({ exif: { ifd0: false } });\n      });\n    });\n    it('Non string value in nested object exif', () => {\n      assert.throws(() => {\n        sharp().withMetadata({ exif: { ifd0: { fail: false } } });\n      });\n    });\n    it('withIccProfile invalid profile', () => {\n      assert.throws(\n        () => sharp().withIccProfile(false),\n        /Expected string for icc but received false of type boolean/\n      );\n    });\n    it('withIccProfile missing attach', () => {\n      assert.doesNotThrow(\n        () => sharp().withIccProfile('test', {})\n      );\n    });\n    it('withIccProfile invalid attach', () => {\n      assert.throws(\n        () => sharp().withIccProfile('test', { attach: 1 }),\n        /Expected boolean for attach but received 1 of type number/\n      );\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/modulate.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst sharp = require('../../');\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\nconst fixtures = require('../fixtures');\n\ndescribe('Modulate', () => {\n  describe('Invalid options', () => {\n    [\n      null,\n      undefined,\n      10,\n      { brightness: -1 },\n      { brightness: '50%' },\n      { brightness: null },\n      { saturation: -1 },\n      { saturation: '50%' },\n      { saturation: null },\n      { hue: '50deg' },\n      { hue: 1.5 },\n      { hue: null },\n      { lightness: '+50' },\n      { lightness: null }\n    ].forEach((options) => {\n      it('should throw', () => {\n        assert.throws(() => {\n          sharp(fixtures.inputJpg).modulate(options);\n        });\n      });\n    });\n  });\n\n  it('should be able to hue-rotate', async () => {\n    const [r, g, b] = await sharp({\n      create: {\n        width: 1,\n        height: 1,\n        channels: 3,\n        background: { r: 153, g: 68, b: 68 }\n      }\n    })\n      .modulate({ hue: 120 })\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual({ r: 41, g: 107, b: 57 }, { r, g, b });\n  });\n\n  it('should be able to brighten', async () => {\n    const [r, g, b] = await sharp({\n      create: {\n        width: 1,\n        height: 1,\n        channels: 3,\n        background: { r: 153, g: 68, b: 68 }\n      }\n    })\n      .modulate({ brightness: 2 })\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual({ r: 255, g: 173, b: 168 }, { r, g, b });\n  });\n\n  it('should be able to darken', async () => {\n    const [r, g, b] = await sharp({\n      create: {\n        width: 1,\n        height: 1,\n        channels: 3,\n        background: { r: 153, g: 68, b: 68 }\n      }\n    })\n      .modulate({ brightness: 0.5 })\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual({ r: 97, g: 17, b: 25 }, { r, g, b });\n  });\n\n  it('should be able to saturate', async () => {\n    const [r, g, b] = await sharp({\n      create: {\n        width: 1,\n        height: 1,\n        channels: 3,\n        background: { r: 153, g: 68, b: 68 }\n      }\n    })\n      .modulate({ saturation: 2 })\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual({ r: 198, g: 0, b: 43 }, { r, g, b });\n  });\n\n  it('should be able to desaturate', async () => {\n    const [r, g, b] = await sharp({\n      create: {\n        width: 1,\n        height: 1,\n        channels: 3,\n        background: { r: 153, g: 68, b: 68 }\n      }\n    })\n      .modulate({ saturation: 0.5 })\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual({ r: 127, g: 83, b: 81 }, { r, g, b });\n  });\n\n  it('should be able to lighten', async () => {\n    const [r, g, b] = await sharp({\n      create: {\n        width: 1,\n        height: 1,\n        channels: 3,\n        background: { r: 153, g: 68, b: 68 }\n      }\n    })\n      .modulate({ lightness: 10 })\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual({ r: 182, g: 93, b: 92 }, { r, g, b });\n  });\n\n  it('should be able to modulate all channels', async () => {\n    const [r, g, b] = await sharp({\n      create: {\n        width: 1,\n        height: 1,\n        channels: 3,\n        background: { r: 153, g: 68, b: 68 }\n      }\n    })\n      .modulate({ brightness: 2, saturation: 0.5, hue: 180 })\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual({ r: 149, g: 209, b: 214 }, { r, g, b });\n  });\n\n  it('should be able to use linear and modulate together', async () => {\n    const contrast = 1.5;\n    const brightness = 0.5;\n\n    const [r, g, b] = await sharp({\n      create: {\n        width: 1,\n        height: 1,\n        channels: 3,\n        background: { r: 153, g: 68, b: 68 }\n      }\n    })\n      .linear(contrast, -(128 * contrast) + 128)\n      .modulate({ brightness })\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual({ r: 81, g: 0, b: 0 }, { r, g, b });\n  });\n\n  describe('hue-rotate', () => {\n    [30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360].forEach(angle => {\n      it(`should hue rotate by ${angle} deg`, async () => {\n        const base = `modulate-hue-angle-${angle}.png`;\n        const actual = fixtures.path(`output.${base}`);\n        const expected = fixtures.expected(base);\n\n        await sharp(fixtures.testPattern)\n          .resize(320)\n          .modulate({ hue: angle })\n          .png({ compressionLevel: 0 })\n          .toFile(actual)\n          .then(() => {\n            fixtures.assertMaxColourDistance(actual, expected, 3);\n          });\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/negate.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Negate', () => {\n  it('negate (jpeg)', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .negate()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate.jpg'), data, done);\n      });\n  });\n\n  it('negate (png)', (_t, done) => {\n    sharp(fixtures.inputPng)\n      .resize(320, 240)\n      .negate()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate.png'), data, done);\n      });\n  });\n\n  it('negate (png, trans)', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency)\n      .resize(320, 240)\n      .negate()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate-trans.png'), data, done);\n      });\n  });\n\n  it('negate (png, alpha)', (_t, done) => {\n    sharp(fixtures.inputPngWithGreyAlpha)\n      .resize(320, 240)\n      .negate()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate-alpha.png'), data, done);\n      });\n  });\n\n  it('negate (webp)', (_t, done) => {\n    sharp(fixtures.inputWebP)\n      .resize(320, 240)\n      .negate()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('webp', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate.webp'), data, done);\n      });\n  });\n\n  it('negate (webp, trans)', (_t, done) => {\n    sharp(fixtures.inputWebPWithTransparency)\n      .resize(320, 240)\n      .negate()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('webp', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate-trans.webp'), data, done);\n      });\n  });\n\n  it('negate (true)', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .negate(true)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate.jpg'), data, done);\n      });\n  });\n\n  it('negate (false)', (_t, done) => {\n    const output = fixtures.path('output.unmodified-by-negate.png');\n    sharp(fixtures.inputJpgWithLowContrast)\n      .negate(false)\n      .toFile(output, (err) => {\n        if (err) throw err;\n        fixtures.assertMaxColourDistance(output, fixtures.inputJpgWithLowContrast, 0);\n        done();\n      });\n  });\n\n  it('negate ({alpha: true})', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .negate({ alpha: true })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate.jpg'), data, done);\n      });\n  });\n\n  it('negate non-alpha channels (png)', (_t, done) => {\n    sharp(fixtures.inputPng)\n      .resize(320, 240)\n      .negate({ alpha: false })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate-preserve-alpha.png'), data, done);\n      });\n  });\n\n  it('negate non-alpha channels (png, trans)', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency)\n      .resize(320, 240)\n      .negate({ alpha: false })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate-preserve-alpha-trans.png'), data, done);\n      });\n  });\n\n  it('negate non-alpha channels (png, alpha)', (_t, done) => {\n    sharp(fixtures.inputPngWithGreyAlpha)\n      .resize(320, 240)\n      .negate({ alpha: false })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate-preserve-alpha-grey.png'), data, done);\n      });\n  });\n\n  it('negate non-alpha channels (webp)', (_t, done) => {\n    sharp(fixtures.inputWebP)\n      .resize(320, 240)\n      .negate({ alpha: false })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('webp', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate-preserve-alpha.webp'), data, done);\n      });\n  });\n\n  it('negate non-alpha channels (webp, trans)', (_t, done) => {\n    sharp(fixtures.inputWebPWithTransparency)\n      .resize(320, 240)\n      .negate({ alpha: false })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('webp', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('negate-preserve-alpha-trans.webp'), data, done);\n      });\n  });\n\n  it('negate create', async () => {\n    const [r, g, b] = await sharp({\n      create: {\n        width: 1,\n        height: 1,\n        channels: 3,\n        background: { r: 10, g: 20, b: 30 }\n      }\n    })\n      .negate()\n      .raw()\n      .toBuffer();\n\n    assert.deepStrictEqual({ r, g, b }, { r: 245, g: 235, b: 225 });\n  });\n\n  it('invalid alpha value', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputWebPWithTransparency).negate({ alpha: 'non-bool' });\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/noise.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Gaussian noise', () => {\n  it('generate single-channel gaussian noise', (_t, done) => {\n    const output = fixtures.path('output.noise-1-channel.png');\n    const noise = sharp({\n      create: {\n        width: 1024,\n        height: 768,\n        channels: 1, // b-w\n        noise: {\n          type: 'gaussian',\n          mean: 128,\n          sigma: 30\n        }\n      }\n    }).toColourspace('b-w');\n    noise.toFile(output, (err, info) => {\n      if (err) throw err;\n      assert.strictEqual('png', info.format);\n      assert.strictEqual(1024, info.width);\n      assert.strictEqual(768, info.height);\n      assert.strictEqual(1, info.channels);\n      sharp(output).metadata((err, metadata) => {\n        if (err) throw err;\n        assert.strictEqual('b-w', metadata.space);\n        assert.strictEqual('uchar', metadata.depth);\n        done();\n      });\n    });\n  });\n\n  it('generate 3-channels gaussian noise', (_t, done) => {\n    const output = fixtures.path('output.noise-3-channels.png');\n    const noise = sharp({\n      create: {\n        width: 1024,\n        height: 768,\n        channels: 3, // sRGB\n        noise: {\n          type: 'gaussian',\n          mean: 128,\n          sigma: 30\n        }\n      }\n    });\n    noise.toFile(output, (err, info) => {\n      if (err) throw err;\n      assert.strictEqual('png', info.format);\n      assert.strictEqual(1024, info.width);\n      assert.strictEqual(768, info.height);\n      assert.strictEqual(3, info.channels);\n      sharp(output).metadata((err, metadata) => {\n        if (err) throw err;\n        assert.strictEqual('srgb', metadata.space);\n        assert.strictEqual('uchar', metadata.depth);\n        done();\n      });\n    });\n  });\n\n  it('overlay 3-channels gaussian noise over image', (_t, done) => {\n    const output = fixtures.path('output.noise-image.jpg');\n    const noise = sharp({\n      create: {\n        width: 320,\n        height: 240,\n        channels: 3,\n        noise: {\n          type: 'gaussian',\n          mean: 0,\n          sigma: 5\n        }\n      }\n    });\n    noise.toBuffer((err, data, info) => {\n      if (err) throw err;\n      assert.strictEqual(3, info.channels);\n      sharp(fixtures.inputJpg)\n        .resize(320, 240)\n        .composite([\n          {\n            input: data,\n            blend: 'exclusion',\n            raw: {\n              width: info.width,\n              height: info.height,\n              channels: info.channels\n            }\n          }\n        ])\n        .toFile(output, (err, info) => {\n          if (err) throw err;\n          assert.strictEqual('jpeg', info.format);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(240, info.height);\n          assert.strictEqual(3, info.channels);\n          // perceptual hashing detects that images are the same (difference is <=1%)\n          fixtures.assertSimilar(output, fixtures.inputJpg, (err) => {\n            if (err) throw err;\n            done();\n          });\n        });\n    });\n  });\n\n  it('overlay strong single-channel (sRGB) gaussian noise with 25% transparency over transparent png image', (_t, done) => {\n    const output = fixtures.path('output.noise-image-transparent.png');\n    const width = 320;\n    const height = 240;\n    const rawData = {\n      width,\n      height,\n      channels: 1\n    };\n    const noise = sharp({\n      create: {\n        width,\n        height,\n        channels: 1,\n        noise: {\n          type: 'gaussian',\n          mean: 200,\n          sigma: 30\n        }\n      }\n    });\n    noise\n      .toColourspace('b-w')\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(1, info.channels);\n        sharp(data, { raw: rawData })\n          .joinChannel(data, { raw: rawData }) // r channel\n          .joinChannel(data, { raw: rawData }) // b channel\n          .joinChannel(Buffer.alloc(width * height, 64), { raw: rawData }) // alpha channel\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            assert.strictEqual(4, info.channels);\n            sharp(fixtures.inputPngRGBWithAlpha)\n              .resize(width, height)\n              .composite([\n                {\n                  input: data,\n                  blend: 'exclusion',\n                  raw: {\n                    width: info.width,\n                    height: info.height,\n                    channels: info.channels\n                  }\n                }\n              ])\n              .toFile(output, (err, info) => {\n                if (err) throw err;\n                assert.strictEqual('png', info.format);\n                assert.strictEqual(width, info.width);\n                assert.strictEqual(height, info.height);\n                assert.strictEqual(4, info.channels);\n                fixtures.assertSimilar(output, fixtures.inputPngRGBWithAlpha, { threshold: 10 }, (err) => {\n                  if (err) throw err;\n                  done();\n                });\n              });\n          });\n      });\n  });\n\n  it('animated noise', async () => {\n    const gif = await sharp({\n      create: {\n        width: 16,\n        height: 64,\n        pageHeight: 16,\n        channels: 3,\n        noise: { type: 'gaussian' }\n      }\n    })\n      .gif()\n      .toBuffer();\n\n    const { width, height, pages, delay } = await sharp(gif).metadata();\n    assert.strictEqual(width, 16);\n    assert.strictEqual(height, 16);\n    assert.strictEqual(pages, 4);\n    assert.strictEqual(delay.length, 4);\n  });\n\n  it('no create object properties specified', () => {\n    assert.throws(() => {\n      sharp({\n        create: {}\n      });\n    });\n  });\n\n  it('invalid noise object', () => {\n    assert.throws(() => {\n      sharp({\n        create: {\n          width: 100,\n          height: 100,\n          channels: 3,\n          noise: 'gaussian'\n        }\n      });\n    });\n  });\n\n  it('unknown type of noise', () => {\n    assert.throws(() => {\n      sharp({\n        create: {\n          width: 100,\n          height: 100,\n          channels: 3,\n          noise: {\n            type: 'unknown'\n          }\n        }\n      });\n    });\n  });\n\n  it('gaussian noise, invalid amount of channels', () => {\n    assert.throws(() => {\n      sharp({\n        create: {\n          width: 100,\n          height: 100,\n          channels: 5,\n          noise: {\n            type: 'gaussian',\n            mean: 5,\n            sigma: 10\n          }\n        }\n      });\n    });\n  });\n\n  it('gaussian noise, invalid mean', () => {\n    assert.throws(() => {\n      sharp({\n        create: {\n          width: 100,\n          height: 100,\n          channels: 1,\n          noise: {\n            type: 'gaussian',\n            mean: -1.5,\n            sigma: 10\n          }\n        }\n      });\n    });\n  });\n\n  it('gaussian noise, invalid sigma', () => {\n    assert.throws(() => {\n      sharp({\n        create: {\n          width: 100,\n          height: 100,\n          channels: 1,\n          noise: {\n            type: 'gaussian',\n            mean: 0,\n            sigma: -1.5\n          }\n        }\n      });\n    });\n  });\n\n  it('Invalid pageHeight', () => {\n    const create = {\n      width: 8,\n      height: 8,\n      channels: 4,\n      noise: { type: 'gaussian' }\n    };\n    assert.throws(\n      () => sharp({ create: { ...create, pageHeight: 'zoinks' } }),\n      /Expected positive integer for create\\.pageHeight but received zoinks of type string/\n    );\n    assert.throws(\n      () => sharp({ create: { ...create, pageHeight: -1 } }),\n      /Expected positive integer for create\\.pageHeight but received -1 of type number/\n    );\n    assert.throws(\n      () => sharp({ create: { ...create, pageHeight: 9 } }),\n      /Expected positive integer for create\\.pageHeight but received 9 of type number/\n    );\n    assert.throws(\n      () => sharp({ create: { ...create, pageHeight: 3 } }),\n      /Expected create\\.height 8 to be a multiple of create\\.pageHeight 3/\n    );\n  });\n});\n"
  },
  {
    "path": "test/unit/normalize.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\nconst assertNormalized = (data) => {\n  let min = 255;\n  let max = 0;\n  for (let i = 0; i < data.length; i++) {\n    min = Math.min(min, data[i]);\n    max = Math.max(max, data[i]);\n  }\n  assert.strictEqual(0, min, 'min too high');\n  assert.ok(max > 248, 'max too low');\n};\n\ndescribe('Normalization', () => {\n  it('spreads rgb image values between 0 and 255', (_t, done) => {\n    sharp(fixtures.inputJpgWithLowContrast)\n      .normalise()\n      .raw()\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        assertNormalized(data);\n        done();\n      });\n  });\n\n  it('spreads grayscaled image values between 0 and 255', (_t, done) => {\n    sharp(fixtures.inputJpgWithLowContrast)\n      .greyscale()\n      .normalize()\n      .raw()\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        assertNormalized(data);\n        done();\n      });\n  });\n\n  it('stretches greyscale images with alpha channel', (_t, done) => {\n    sharp(fixtures.inputPngWithGreyAlpha)\n      .normalise()\n      .raw()\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        assertNormalized(data);\n        done();\n      });\n  });\n\n  it('keeps an existing alpha channel', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency)\n      .resize(8, 8)\n      .normalize()\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        sharp(data).metadata((err, metadata) => {\n          if (err) return done(err);\n          assert.strictEqual(4, metadata.channels);\n          assert.strictEqual(true, metadata.hasAlpha);\n          assert.strictEqual('srgb', metadata.space);\n          done();\n        });\n      });\n  });\n\n  it('keeps the alpha channel of greyscale images intact', (_t, done) => {\n    sharp(fixtures.inputPngWithGreyAlpha)\n      .resize(8, 8)\n      .normalise()\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        sharp(data).metadata((err, metadata) => {\n          if (err) return done(err);\n          assert.strictEqual(true, metadata.hasAlpha);\n          assert.strictEqual(4, metadata.channels);\n          assert.strictEqual('srgb', metadata.space);\n          done();\n        });\n      });\n  });\n\n  it('does not alter images with only one color', (_t, done) => {\n    const output = fixtures.path('output.unmodified-png-with-one-color.png');\n    sharp(fixtures.inputPngWithOneColor)\n      .normalize()\n      .toFile(output, (err) => {\n        if (err) done(err);\n        fixtures.assertMaxColourDistance(output, fixtures.inputPngWithOneColor, 0);\n        done();\n      });\n  });\n\n  it('works with 16-bit RGBA images', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency16bit)\n      .normalise()\n      .raw()\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        assertNormalized(data);\n        done();\n      });\n  });\n\n  it('should handle luminance range', (_t, done) => {\n    sharp(fixtures.inputJpgWithLowContrast)\n      .normalise({ lower: 10, upper: 70 })\n      .raw()\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        assertNormalized(data);\n        done();\n      });\n  });\n\n  it('should allow lower without upper', () => {\n    assert.doesNotThrow(() => sharp().normalize({ lower: 2 }));\n  });\n  it('should allow upper without lower', () => {\n    assert.doesNotThrow(() => sharp().normalize({ upper: 98 }));\n  });\n  it('should throw when lower is out of range', () => {\n    assert.throws(\n      () => sharp().normalise({ lower: -10 }),\n      /Expected number between 0 and 99 for lower but received -10 of type number/\n    );\n  });\n  it('should throw when upper is out of range', () => {\n    assert.throws(\n      () => sharp().normalise({ upper: 110 }),\n      /Expected number between 1 and 100 for upper but received 110 of type number/\n    );\n  });\n  it('should throw when lower is not a number', () => {\n    assert.throws(\n      () => sharp().normalise({ lower: 'fail' }),\n      /Expected number between 0 and 99 for lower but received fail of type string/\n    );\n  });\n  it('should throw when upper is not a number', () => {\n    assert.throws(\n      () => sharp().normalise({ upper: 'fail' }),\n      /Expected number between 1 and 100 for upper but received fail of type string/\n    );\n  });\n  it('should throw when the lower and upper are equal', () => {\n    assert.throws(\n      () => sharp().normalise({ lower: 2, upper: 2 }),\n      /Expected lower to be less than upper for range but received 2 >= 2/\n    );\n  });\n  it('should throw when the lower is greater than upper', () => {\n    assert.throws(\n      () => sharp().normalise({ lower: 3, upper: 2 }),\n      /Expected lower to be less than upper for range but received 3 >= 2/\n    );\n  });\n});\n"
  },
  {
    "path": "test/unit/png.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('PNG', () => {\n  it('compression level is valid', () => {\n    assert.doesNotThrow(() => {\n      sharp().png({ compressionLevel: 0 });\n    });\n  });\n\n  it('compression level is invalid', () => {\n    assert.throws(() => {\n      sharp().png({ compressionLevel: -1 });\n    });\n  });\n\n  it('default compressionLevel generates smaller file than compressionLevel=0', (_t, done) => {\n    // First generate with default compressionLevel\n    sharp(fixtures.inputPng)\n      .resize(320, 240)\n      .png()\n      .toBuffer((err, defaultData, defaultInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, defaultData.length > 0);\n        assert.strictEqual('png', defaultInfo.format);\n        // Then generate with compressionLevel=6\n        sharp(fixtures.inputPng)\n          .resize(320, 240)\n          .png({ compressionLevel: 0 })\n          .toBuffer((err, largerData, largerInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, largerData.length > 0);\n            assert.strictEqual('png', largerInfo.format);\n            assert.strictEqual(true, defaultData.length < largerData.length);\n            done();\n          });\n      });\n  });\n\n  it('without adaptiveFiltering generates smaller file', (_t, done) => {\n    // First generate with adaptive filtering\n    sharp(fixtures.inputPng)\n      .resize(320, 240)\n      .png({ adaptiveFiltering: true })\n      .toBuffer((err, adaptiveData, adaptiveInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, adaptiveData.length > 0);\n        assert.strictEqual(adaptiveData.length, adaptiveInfo.size);\n        assert.strictEqual('png', adaptiveInfo.format);\n        assert.strictEqual(320, adaptiveInfo.width);\n        assert.strictEqual(240, adaptiveInfo.height);\n        // Then generate without\n        sharp(fixtures.inputPng)\n          .resize(320, 240)\n          .png({ adaptiveFiltering: false })\n          .toBuffer((err, withoutAdaptiveData, withoutAdaptiveInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, withoutAdaptiveData.length > 0);\n            assert.strictEqual(withoutAdaptiveData.length, withoutAdaptiveInfo.size);\n            assert.strictEqual('png', withoutAdaptiveInfo.format);\n            assert.strictEqual(320, withoutAdaptiveInfo.width);\n            assert.strictEqual(240, withoutAdaptiveInfo.height);\n            assert.strictEqual(true, withoutAdaptiveData.length < adaptiveData.length);\n            done();\n          });\n      });\n  });\n\n  it('Invalid PNG adaptiveFiltering value throws error', () => {\n    assert.throws(() => {\n      sharp().png({ adaptiveFiltering: 1 });\n    });\n  });\n\n  it('Progressive PNG image', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .png({ progressive: false })\n      .toBuffer((err, nonProgressiveData, nonProgressiveInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, nonProgressiveData.length > 0);\n        assert.strictEqual(nonProgressiveData.length, nonProgressiveInfo.size);\n        assert.strictEqual('png', nonProgressiveInfo.format);\n        assert.strictEqual(320, nonProgressiveInfo.width);\n        assert.strictEqual(240, nonProgressiveInfo.height);\n        sharp(nonProgressiveData)\n          .png({ progressive: true })\n          .toBuffer((err, progressiveData, progressiveInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, progressiveData.length > 0);\n            assert.strictEqual(progressiveData.length, progressiveInfo.size);\n            assert.strictEqual(true, progressiveData.length > nonProgressiveData.length);\n            assert.strictEqual('png', progressiveInfo.format);\n            assert.strictEqual(320, progressiveInfo.width);\n            assert.strictEqual(240, progressiveInfo.height);\n            done();\n          });\n      });\n  });\n\n  it('16-bit grey+alpha PNG identity transform', () => {\n    const actual = fixtures.path('output.16-bit-grey-alpha-identity.png');\n    return sharp(fixtures.inputPng16BitGreyAlpha)\n      .toFile(actual)\n      .then(() => {\n        fixtures.assertMaxColourDistance(actual, fixtures.expected('16-bit-grey-alpha-identity.png'));\n      });\n  });\n\n  it('16-bit grey+alpha PNG roundtrip', async () => {\n    const after = await sharp(fixtures.inputPng16BitGreyAlpha)\n      .toColourspace('grey16')\n      .toBuffer();\n\n    const [alphaMeanBefore, alphaMeanAfter] = (\n      await Promise.all([\n        sharp(fixtures.inputPng16BitGreyAlpha).stats(),\n        sharp(after).stats()\n      ])\n    )\n      .map(stats => stats.channels[1].mean);\n\n    assert.strictEqual(alphaMeanAfter, alphaMeanBefore);\n  });\n\n  it('palette decode/encode roundtrip', async () => {\n    const data = await sharp(fixtures.inputPngPalette)\n      .png({ effort: 1, palette: true })\n      .toBuffer();\n\n    const { size, ...metadata } = await sharp(data).metadata();\n    void size;\n    assert.deepStrictEqual(metadata, {\n      autoOrient: {\n        height: 68,\n        width: 68\n      },\n      format: 'png',\n      width: 68,\n      height: 68,\n      space: 'srgb',\n      channels: 3,\n      density: 72,\n      depth: 'uchar',\n      isProgressive: false,\n      isPalette: true,\n      bitsPerSample: 8,\n      paletteBitDepth: 8,\n      hasProfile: false,\n      hasAlpha: false\n    });\n  });\n\n  it('Valid PNG libimagequant palette value does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().png({ palette: false });\n    });\n  });\n\n  it('Invalid PNG libimagequant palette value throws error', () => {\n    assert.throws(() => {\n      sharp().png({ palette: 'fail' });\n    });\n  });\n\n  it('Valid PNG libimagequant quality value produces image of same size or smaller', () => {\n    const inputPngBuffer = fs.readFileSync(fixtures.inputPng);\n    return Promise.all([\n      sharp(inputPngBuffer).resize(10).png({ effort: 1, quality: 80 }).toBuffer(),\n      sharp(inputPngBuffer).resize(10).png({ effort: 1, quality: 100 }).toBuffer()\n    ]).then((data) => {\n      assert.strictEqual(true, data[0].length <= data[1].length);\n    });\n  });\n\n  it('Invalid PNG libimagequant quality value throws error', () => {\n    assert.throws(() => {\n      sharp().png({ quality: 101 });\n    });\n  });\n\n  it('Invalid effort value throws error', () => {\n    assert.throws(() => {\n      sharp().png({ effort: 0.1 });\n    });\n  });\n\n  it('Valid PNG libimagequant colours value produces image of same size or smaller', () => {\n    const inputPngBuffer = fs.readFileSync(fixtures.inputPng);\n    return Promise.all([\n      sharp(inputPngBuffer).resize(10).png({ colours: 100 }).toBuffer(),\n      sharp(inputPngBuffer).resize(10).png({ colours: 200 }).toBuffer()\n    ]).then((data) => {\n      assert.strictEqual(true, data[0].length <= data[1].length);\n    });\n  });\n\n  it('Invalid PNG libimagequant colours value throws error', () => {\n    assert.throws(() => {\n      sharp().png({ colours: -1 });\n    });\n  });\n\n  it('Invalid PNG libimagequant colors value throws error', () => {\n    assert.throws(() => {\n      sharp().png({ colors: 0.1 });\n    });\n  });\n\n  it('Can set bitdepth of PNG without palette', async () => {\n    const data = await sharp({\n      create: {\n        width: 8, height: 8, channels: 3, background: 'red'\n      }\n    })\n      .toColourspace('b-w')\n      .png({ colours: 2, palette: false })\n      .toBuffer();\n\n    const { channels, isPalette, bitsPerSample, paletteBitDepth, size, space } = await sharp(data).metadata();\n    assert.strictEqual(channels, 1);\n    assert.strictEqual(isPalette, false);\n    assert.strictEqual(bitsPerSample, 1);\n    assert.strictEqual(paletteBitDepth, undefined);\n    assert.strictEqual(size, 89);\n    assert.strictEqual(space, 'b-w');\n  });\n\n  it('Valid PNG libimagequant dither value produces image of same size or smaller', () => {\n    const inputPngBuffer = fs.readFileSync(fixtures.inputPng);\n    return Promise.all([\n      sharp(inputPngBuffer).resize(10).png({ dither: 0.1 }).toBuffer(),\n      sharp(inputPngBuffer).resize(10).png({ dither: 0.9 }).toBuffer()\n    ]).then((data) => {\n      assert.strictEqual(true, data[0].length <= data[1].length);\n    });\n  });\n\n  it('Invalid PNG libimagequant dither value throws error', () => {\n    assert.throws(() => {\n      sharp().png({ dither: 'fail' });\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/raw.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Raw pixel data', () => {\n  describe('Raw pixel input', () => {\n    it('Empty data', () => {\n      assert.throws(() => {\n        sharp(Buffer.from(''));\n      }, /empty/);\n      assert.throws(() => {\n        sharp(new ArrayBuffer(0));\n      }, /empty/);\n      assert.throws(() => {\n        sharp(new Uint8Array(0));\n      }, /empty/);\n      assert.throws(() => {\n        sharp(new Uint8ClampedArray(0));\n      }, /empty/);\n    });\n\n    it('Missing options', () => {\n      assert.throws(() => {\n        sharp({ raw: {} });\n      });\n    });\n\n    it('Incomplete options', () => {\n      assert.throws(() => {\n        sharp({ raw: { width: 1, height: 1 } });\n      });\n    });\n\n    it('Invalid channels', () => {\n      assert.throws(() => {\n        sharp({ raw: { width: 1, height: 1, channels: 5 } });\n      });\n    });\n\n    it('Invalid height', () => {\n      assert.throws(() => {\n        sharp({ raw: { width: 1, height: 0, channels: 4 } });\n      });\n    });\n\n    it('Invalid width', () => {\n      assert.throws(() => {\n        sharp({ raw: { width: 'zoinks', height: 1, channels: 4 } });\n      });\n    });\n\n    it('Invalid premultiplied', () => {\n      assert.throws(\n        () => sharp({ raw: { width: 1, height: 1, channels: 4, premultiplied: 'zoinks' } }),\n        /Expected boolean for raw\\.premultiplied but received zoinks of type string/\n      );\n    });\n\n    it('Invalid pageHeight', () => {\n      const width = 8;\n      const height = 8;\n      const channels = 4;\n      assert.throws(\n        () => sharp({ raw: { width, height, channels, pageHeight: 'zoinks' } }),\n        /Expected positive integer for raw\\.pageHeight but received zoinks of type string/\n      );\n      assert.throws(\n        () => sharp({ raw: { width, height, channels, pageHeight: -1 } }),\n        /Expected positive integer for raw\\.pageHeight but received -1 of type number/\n      );\n      assert.throws(\n        () => sharp({ raw: { width, height, channels, pageHeight: 9 } }),\n        /Expected positive integer for raw\\.pageHeight but received 9 of type number/\n      );\n      assert.throws(\n        () => sharp({ raw: { width, height, channels, pageHeight: 3 } }),\n        /Expected raw\\.height 8 to be a multiple of raw\\.pageHeight 3/\n      );\n    });\n\n    it('RGB', (_t, done) => {\n      // Convert to raw pixel data\n      sharp(fixtures.inputJpg)\n        .resize(256)\n        .raw()\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(256, info.width);\n          assert.strictEqual(209, info.height);\n          assert.strictEqual(3, info.channels);\n          // Convert back to JPEG\n          sharp(data, {\n            raw: {\n              width: info.width,\n              height: info.height,\n              channels: info.channels\n            }\n          })\n            .jpeg()\n            .toBuffer((err, data, info) => {\n              if (err) throw err;\n              assert.strictEqual(256, info.width);\n              assert.strictEqual(209, info.height);\n              assert.strictEqual(3, info.channels);\n              fixtures.assertSimilar(fixtures.inputJpg, data, done);\n            });\n        });\n    });\n\n    it('RGBA', (_t, done) => {\n      // Convert to raw pixel data\n      sharp(fixtures.inputPngOverlayLayer1)\n        .resize(256)\n        .raw()\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(256, info.width);\n          assert.strictEqual(192, info.height);\n          assert.strictEqual(4, info.channels);\n          // Convert back to PNG\n          sharp(data, {\n            raw: {\n              width: info.width,\n              height: info.height,\n              channels: info.channels\n            }\n          })\n            .png()\n            .toBuffer((err, data, info) => {\n              if (err) throw err;\n              assert.strictEqual(256, info.width);\n              assert.strictEqual(192, info.height);\n              assert.strictEqual(4, info.channels);\n              fixtures.assertSimilar(fixtures.inputPngOverlayLayer1, data, { threshold: 7 }, done);\n            });\n        });\n    });\n\n    it('RGBA premultiplied', (_t, done) => {\n      // Convert to raw pixel data\n      sharp(fixtures.inputPngSolidAlpha)\n        .resize(256)\n        .raw()\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(256, info.width);\n          assert.strictEqual(192, info.height);\n          assert.strictEqual(4, info.channels);\n\n          const originalData = Buffer.from(data);\n\n          // Premultiply image data\n          for (let i = 0; i < data.length; i += 4) {\n            const alpha = data[i + 3];\n            const norm = alpha / 255;\n\n            if (alpha < 255) {\n              data[i] = Math.round(data[i] * norm);\n              data[i + 1] = Math.round(data[i + 1] * norm);\n              data[i + 2] = Math.round(data[i + 2] * norm);\n            }\n          }\n\n          // Convert back to PNG\n          sharp(data, {\n            raw: {\n              width: info.width,\n              height: info.height,\n              channels: info.channels,\n              premultiplied: true\n            }\n          })\n            .raw()\n            .toBuffer((err, data, info) => {\n              if (err) throw err;\n              assert.strictEqual(256, info.width);\n              assert.strictEqual(192, info.height);\n              assert.strictEqual(4, info.channels);\n              assert.equal(data.compare(originalData), 0, 'output buffer matches unpremultiplied input buffer');\n              done();\n            });\n        });\n    });\n\n    it('JPEG to raw Stream and back again', (_t, done) => {\n      const width = 32;\n      const height = 24;\n      const writable = sharp({\n        raw: {\n          width,\n          height,\n          channels: 3\n        }\n      });\n      writable\n        .jpeg()\n        .toBuffer((err, _data, info) => {\n          if (err) throw err;\n          assert.strictEqual('jpeg', info.format);\n          assert.strictEqual(32, info.width);\n          assert.strictEqual(24, info.height);\n          done();\n        });\n      sharp(fixtures.inputJpg)\n        .resize(width, height)\n        .raw()\n        .pipe(writable);\n    });\n  });\n\n  describe('Output raw, uncompressed image data', () => {\n    it('1 channel greyscale image', (_t, done) => {\n      sharp(fixtures.inputJpg)\n        .greyscale()\n        .resize(32, 24)\n        .raw()\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(32 * 24 * 1, info.size);\n          assert.strictEqual(data.length, info.size);\n          assert.strictEqual('raw', info.format);\n          assert.strictEqual(32, info.width);\n          assert.strictEqual(24, info.height);\n          assert.strictEqual(1, info.channels);\n          done();\n        });\n    });\n\n    it('3 channel colour image without transparency', (_t, done) => {\n      sharp(fixtures.inputJpg)\n        .resize(32, 24)\n        .toFormat('raw')\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(32 * 24 * 3, info.size);\n          assert.strictEqual(data.length, info.size);\n          assert.strictEqual('raw', info.format);\n          assert.strictEqual(32, info.width);\n          assert.strictEqual(24, info.height);\n          done();\n        });\n    });\n\n    it('4 channel colour image with transparency', (_t, done) => {\n      sharp(fixtures.inputPngWithTransparency)\n        .resize(32, 24)\n        .toFormat(sharp.format.raw)\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(32 * 24 * 4, info.size);\n          assert.strictEqual(data.length, info.size);\n          assert.strictEqual('raw', info.format);\n          assert.strictEqual(32, info.width);\n          assert.strictEqual(24, info.height);\n          done();\n        });\n    });\n\n    it('Extract A from RGBA', () =>\n      sharp(fixtures.inputPngWithTransparency)\n        .resize(32, 24)\n        .extractChannel(3)\n        .toColourspace('b-w')\n        .raw()\n        .toBuffer({ resolveWithObject: true })\n        .then(({ info }) => {\n          assert.strictEqual('raw', info.format);\n          assert.strictEqual(1, info.channels);\n          assert.strictEqual(32 * 24, info.size);\n        })\n    );\n  });\n\n  describe('Raw pixel depths', () => {\n    it('Invalid depth', () => {\n      assert.throws(() => {\n        sharp(Buffer.alloc(3), { raw: { width: 1, height: 1, channels: 3 } })\n          .raw({ depth: 'zoinks' });\n      });\n    });\n\n    for (const { type, depth, bits } of [\n      { type: Uint8Array, depth: undefined, bits: 8 },\n      { type: Uint8Array, depth: 'uchar', bits: 8 },\n      { type: Uint8ClampedArray, depth: 'uchar', bits: 8 },\n      { type: Int8Array, depth: 'char', bits: 8 },\n      { type: Uint16Array, depth: 'ushort', bits: 16 },\n      { type: Int16Array, depth: 'short', bits: 16 },\n      { type: Uint32Array, depth: 'uint', bits: 32 },\n      { type: Int32Array, depth: 'int', bits: 32 },\n      { type: Float32Array, depth: 'float', bits: 32 },\n      { type: Float64Array, depth: 'double', bits: 64 }\n    ]) {\n      it(type.name, () =>\n        sharp(new type(3), { raw: { width: 1, height: 1, channels: 3 } })\n          .raw({ depth })\n          .toBuffer({ resolveWithObject: true })\n          .then(({ data, info }) => {\n            assert.strictEqual(1, info.width);\n            assert.strictEqual(1, info.height);\n            assert.strictEqual(3, info.channels);\n            if (depth !== undefined) {\n              assert.strictEqual(depth, info.depth);\n            }\n            assert.strictEqual(data.length / 3, bits / 8);\n          })\n      );\n    }\n  });\n\n  it('Animated', async () => {\n    const gif = await sharp(\n      Buffer.alloc(8),\n      { raw: { width: 1, height: 2, channels: 4, pageHeight: 1 }, animated: true }\n    )\n      .gif({ keepDuplicateFrames: true })\n      .toBuffer();\n\n    const { width, height, pages, delay } = await sharp(gif).metadata();\n    assert.strictEqual(width, 1);\n    assert.strictEqual(height, 1);\n    assert.strictEqual(pages, 2);\n    assert.strictEqual(delay.length, 2);\n  });\n\n  describe('16-bit roundtrip', () => {\n    it('grey', async () => {\n      const grey = 42000;\n      const png = await sharp(\n        Uint16Array.from([grey]),\n        { raw: { width: 1, height: 1, channels: 1 } }\n      )\n        .toColourspace('grey16')\n        .png({ compressionLevel: 0 })\n        .toBuffer();\n      const raw = await sharp(png)\n        .toColourspace('grey16')\n        .raw({ depth: 'ushort' })\n        .toBuffer();\n\n      assert.strictEqual(raw.readUint16LE(0), grey);\n    });\n\n    it('RGB', async () => {\n      const rgb = [10946, 28657, 46368];\n      const png = await sharp(\n        Uint16Array.from(rgb),\n        { raw: { width: 1, height: 1, channels: 3 } }\n      )\n        .toColourspace('rgb16')\n        .png({ compressionLevel: 0 })\n        .toBuffer();\n      const raw = await sharp(png)\n        .toColourspace('rgb16')\n        .raw({ depth: 'ushort' })\n        .toBuffer();\n\n      assert.strictEqual(raw.readUint16LE(0), rgb[0]);\n      assert.strictEqual(raw.readUint16LE(2), rgb[1]);\n      assert.strictEqual(raw.readUint16LE(4), rgb[2]);\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/recomb.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\nconst sepia = [\n  [0.3588, 0.7044, 0.1368],\n  [0.299, 0.587, 0.114],\n  [0.2392, 0.4696, 0.0912]\n];\n\ndescribe('Recomb', () => {\n  it('applies a sepia filter using recomb', (_t, done) => {\n    const output = fixtures.path('output.recomb-sepia.jpg');\n    sharp(fixtures.inputJpgWithLandscapeExif1)\n      .recomb(sepia)\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(600, info.width);\n        assert.strictEqual(450, info.height);\n        fixtures.assertMaxColourDistance(\n          output,\n          fixtures.expected('Landscape_1-recomb-sepia.jpg'),\n          17\n        );\n        done();\n      });\n  });\n\n  it('applies a sepia filter using recomb to an PNG with Alpha', (_t, done) => {\n    const output = fixtures.path('output.recomb-sepia.png');\n    sharp(fixtures.inputPngAlphaPremultiplicationSmall)\n      .recomb(sepia)\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(1024, info.width);\n        assert.strictEqual(768, info.height);\n        fixtures.assertMaxColourDistance(\n          output,\n          fixtures.expected('alpha-recomb-sepia.png'),\n          17\n        );\n        done();\n      });\n  });\n\n  it('recomb with a single channel input', async () => {\n    const { info } = await sharp(Buffer.alloc(64), {\n      raw: {\n        width: 8,\n        height: 8,\n        channels: 1\n      }\n    })\n      .recomb(sepia)\n      .toBuffer({ resolveWithObject: true });\n\n    assert.strictEqual(3, info.channels);\n  });\n\n  it('applies a different sepia filter using recomb', (_t, done) => {\n    const output = fixtures.path('output.recomb-sepia2.jpg');\n    sharp(fixtures.inputJpgWithLandscapeExif1)\n      .recomb([\n        [0.393, 0.769, 0.189],\n        [0.349, 0.686, 0.168],\n        [0.272, 0.534, 0.131]\n      ])\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(600, info.width);\n        assert.strictEqual(450, info.height);\n        fixtures.assertMaxColourDistance(\n          output,\n          fixtures.expected('Landscape_1-recomb-sepia2.jpg'),\n          17\n        );\n        done();\n      });\n  });\n  it('increases the saturation of the image', (_t, done) => {\n    const saturationLevel = 1;\n    const output = fixtures.path('output.recomb-saturation.jpg');\n    sharp(fixtures.inputJpgWithLandscapeExif1)\n      .recomb([\n        [\n          saturationLevel + 1 - 0.2989,\n          -0.587 * saturationLevel,\n          -0.114 * saturationLevel\n        ],\n        [\n          -0.2989 * saturationLevel,\n          saturationLevel + 1 - 0.587,\n          -0.114 * saturationLevel\n        ],\n        [\n          -0.2989 * saturationLevel,\n          -0.587 * saturationLevel,\n          saturationLevel + 1 - 0.114\n        ]\n      ])\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(600, info.width);\n        assert.strictEqual(450, info.height);\n        fixtures.assertMaxColourDistance(\n          output,\n          fixtures.expected('Landscape_1-recomb-saturation.jpg'),\n          37\n        );\n        done();\n      });\n  });\n\n  it('applies opacity 30% to the image', (_t, done) => {\n    const output = fixtures.path('output.recomb-opacity.png');\n    sharp(fixtures.inputPngWithTransparent)\n      .recomb([\n        [1, 0, 0, 0],\n        [0, 1, 0, 0],\n        [0, 0, 1, 0],\n        [0, 0, 0, 0.3]\n      ])\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(48, info.width);\n        assert.strictEqual(48, info.height);\n        fixtures.assertMaxColourDistance(\n          output,\n          fixtures.expected('d-opacity-30.png'),\n          17\n        );\n        done();\n      });\n  });\n\n  describe('invalid matrix specification', () => {\n    it('missing', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg).recomb();\n      });\n    });\n    it('incorrect flat data', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg).recomb([1, 2, 3, 4, 5, 6, 7, 8, 9]);\n      });\n    });\n    it('incorrect sub size', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg).recomb([\n          [1, 2, 3, 4],\n          [5, 6, 7, 8],\n          [1, 2, 9, 6]\n        ]);\n      });\n    });\n    it('incorrect top size', () => {\n      assert.throws(() => {\n        sharp(fixtures.inputJpg).recomb([[1, 2, 3, 4], [5, 6, 7, 8]]);\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/resize-contain.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Resize fit=contain', () => {\n  it('Allows specifying the position as a string', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240, {\n        fit: 'contain',\n        position: 'center'\n      })\n      .png()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('embed-3-into-3.png'), data, done);\n      });\n  });\n\n  it('JPEG within PNG, no alpha channel', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240, { fit: 'contain' })\n      .png()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        assert.strictEqual(3, info.channels);\n        fixtures.assertSimilar(fixtures.expected('embed-3-into-3.png'), data, done);\n      });\n  });\n\n  it('JPEG within WebP, to include alpha channel', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240, {\n        fit: 'contain',\n        background: { r: 0, g: 0, b: 0, alpha: 0 }\n      })\n      .webp()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('webp', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('embed-3-into-4.webp'), data, done);\n      });\n  });\n\n  it('PNG with alpha channel', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency)\n      .resize(50, 50, { fit: 'contain' })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(50, info.width);\n        assert.strictEqual(50, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('embed-4-into-4.png'), data, done);\n      });\n  });\n\n  it('16-bit PNG with alpha channel', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency16bit)\n      .resize(32, 16, { fit: 'contain' })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(32, info.width);\n        assert.strictEqual(16, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('embed-16bit.png'), data, done);\n      });\n  });\n\n  it('16-bit PNG with alpha channel onto RGBA', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency16bit)\n      .resize(32, 16, {\n        fit: 'contain',\n        background: { r: 0, g: 0, b: 0, alpha: 0 }\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(32, info.width);\n        assert.strictEqual(16, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('embed-16bit-rgba.png'), data, done);\n      });\n  });\n\n  it('PNG with 2 channels', (_t, done) => {\n    sharp(fixtures.inputPngWithGreyAlpha)\n      .resize(32, 16, {\n        fit: 'contain',\n        background: { r: 0, g: 0, b: 0, alpha: 0 }\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(32, info.width);\n        assert.strictEqual(16, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('embed-2channel.png'), data, done);\n      });\n  });\n\n  it('TIFF in LAB colourspace onto RGBA background', (_t, done) => {\n    sharp(fixtures.inputTiffCielab)\n      .resize(64, 128, {\n        fit: 'contain',\n        background: { r: 255, g: 102, b: 0, alpha: 0.5 }\n      })\n      .png()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(64, info.width);\n        assert.strictEqual(128, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('embed-lab-into-rgba.png'), data, done);\n      });\n  });\n\n  it('Enlarge', (_t, done) => {\n    sharp(fixtures.inputPngWithOneColor)\n      .resize(320, 240, { fit: 'contain' })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        assert.strictEqual(3, info.channels);\n        fixtures.assertSimilar(fixtures.expected('embed-enlarge.png'), data, done);\n      });\n  });\n\n  describe('Animated WebP', () => {\n    it('Width only', (_t, done) => {\n      sharp(fixtures.inputWebPAnimated, { pages: -1 })\n        .resize(320, 240, {\n          fit: 'contain',\n          background: { r: 255, g: 0, b: 0 }\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(true, data.length > 0);\n          assert.strictEqual('webp', info.format);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(240 * 9, info.height);\n          assert.strictEqual(4, info.channels);\n          fixtures.assertSimilar(fixtures.expected('embed-animated-width.webp'), data, done);\n        });\n    });\n\n    it('Height only', (_t, done) => {\n      sharp(fixtures.inputWebPAnimated, { pages: -1 })\n        .resize(240, 320, {\n          fit: 'contain',\n          background: { r: 255, g: 0, b: 0 }\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(true, data.length > 0);\n          assert.strictEqual('webp', info.format);\n          assert.strictEqual(240, info.width);\n          assert.strictEqual(320 * 9, info.height);\n          assert.strictEqual(4, info.channels);\n          fixtures.assertSimilar(fixtures.expected('embed-animated-height.webp'), data, done);\n        });\n    });\n  });\n\n  it('Invalid position values should fail', () => {\n    [-1, 8.1, 9, 1000000, false, 'vallejo'].forEach((position) => {\n      assert.throws(() => {\n        sharp().resize(null, null, { fit: 'contain', position });\n      });\n    });\n  });\n\n  it('Position horizontal top', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'top'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a2-n.png'), data, done);\n      });\n  });\n\n  it('Position horizontal right top', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'right top'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a3-ne.png'), data, done);\n      });\n  });\n\n  it('Position horizontal right', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'right'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a4-e.png'), data, done);\n      });\n  });\n\n  it('Position horizontal right bottom', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'right bottom'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a5-se.png'), data, done);\n      });\n  });\n\n  it('Position horizontal bottom', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'bottom'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a6-s.png'), data, done);\n      });\n  });\n\n  it('Position horizontal left bottom', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'left bottom'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a7-sw.png'), data, done);\n      });\n  });\n\n  it('Position horizontal left', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'left'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a8-w.png'), data, done);\n      });\n  });\n\n  it('Position horizontal left top', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'left top'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a1-nw.png'), data, done);\n      });\n  });\n\n  it('Position horizontal north', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.north\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a2-n.png'), data, done);\n      });\n  });\n\n  it('Position horizontal northeast', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.northeast\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a3-ne.png'), data, done);\n      });\n  });\n\n  it('Position horizontal east', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.east\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a4-e.png'), data, done);\n      });\n  });\n\n  it('Position horizontal southeast', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.southeast\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a5-se.png'), data, done);\n      });\n  });\n\n  it('Position horizontal south', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.south\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a6-s.png'), data, done);\n      });\n  });\n\n  it('Position horizontal southwest', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.southwest\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a7-sw.png'), data, done);\n      });\n  });\n\n  it('Position horizontal west', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.west\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a8-w.png'), data, done);\n      });\n  });\n\n  it('Position horizontal northwest', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.northwest\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a1-nw.png'), data, done);\n      });\n  });\n\n  it('Position horizontal center', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 100, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.center\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(100, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/a9-c.png'), data, done);\n      });\n  });\n\n  it('Position vertical top', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'top'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/2-n.png'), data, done);\n      });\n  });\n\n  it('Position vertical right top', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'right top'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/3-ne.png'), data, done);\n      });\n  });\n\n  it('Position vertical right', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'right'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/4-e.png'), data, done);\n      });\n  });\n\n  it('Position vertical right bottom', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'right bottom'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/5-se.png'), data, done);\n      });\n  });\n\n  it('Position vertical bottom', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'bottom'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/6-s.png'), data, done);\n      });\n  });\n\n  it('Position vertical left bottom', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'left bottom'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/7-sw.png'), data, done);\n      });\n  });\n\n  it('Position vertical left', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'left'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/8-w.png'), data, done);\n      });\n  });\n\n  it('Position vertical left top', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: 'left top'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/1-nw.png'), data, done);\n      });\n  });\n\n  it('Position vertical north', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.north\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/2-n.png'), data, done);\n      });\n  });\n\n  it('Position vertical northeast', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.northeast\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/3-ne.png'), data, done);\n      });\n  });\n\n  it('Position vertical east', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.east\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/4-e.png'), data, done);\n      });\n  });\n\n  it('Position vertical southeast', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.southeast\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/5-se.png'), data, done);\n      });\n  });\n\n  it('Position vertical south', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.south\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/6-s.png'), data, done);\n      });\n  });\n\n  it('Position vertical southwest', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.southwest\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/7-sw.png'), data, done);\n      });\n  });\n\n  it('Position vertical west', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.west\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/8-w.png'), data, done);\n      });\n  });\n\n  it('Position vertical northwest', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.northwest\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/1-nw.png'), data, done);\n      });\n  });\n\n  it('Position vertical center', (_t, done) => {\n    sharp(fixtures.inputPngEmbed)\n      .resize(200, 200, {\n        fit: sharp.fit.contain,\n        background: { r: 0, g: 0, b: 0, alpha: 0 },\n        position: sharp.gravity.center\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(200, info.width);\n        assert.strictEqual(200, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('./embedgravitybird/9-c.png'), data, done);\n      });\n  });\n\n  it('multiple alpha channels', async () => {\n    const create = {\n      width: 20,\n      height: 12,\n      channels: 4,\n      background: 'green'\n    };\n    const multipleAlphaChannels = await sharp({ create })\n      .joinChannel({ create })\n      .tiff({ compression: 'deflate' })\n      .toBuffer();\n\n    const data = await sharp(multipleAlphaChannels)\n      .resize({\n        width: 8,\n        height: 8,\n        fit: 'contain',\n        background: 'blue'\n      })\n      .tiff({ compression: 'deflate' })\n      .toBuffer();\n    const { format, width, height, space, channels } = await sharp(data).metadata();\n    assert.deepStrictEqual(format, 'tiff');\n    assert.deepStrictEqual(width, 8);\n    assert.deepStrictEqual(height, 8);\n    assert.deepStrictEqual(space, 'srgb');\n    assert.deepStrictEqual(channels, 8);\n  });\n});\n"
  },
  {
    "path": "test/unit/resize-cover.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Resize fit=cover', () => {\n  [\n    // Position\n    {\n      name: 'Position: top',\n      width: 320,\n      height: 80,\n      gravity: sharp.position.top,\n      fixture: 'gravity-north.jpg'\n    },\n    {\n      name: 'Position: right',\n      width: 80,\n      height: 320,\n      gravity: sharp.position.right,\n      fixture: 'gravity-east.jpg'\n    },\n    {\n      name: 'Position: bottom',\n      width: 320,\n      height: 80,\n      gravity: sharp.position.bottom,\n      fixture: 'gravity-south.jpg'\n    },\n    {\n      name: 'Position: left',\n      width: 80,\n      height: 320,\n      gravity: sharp.position.left,\n      fixture: 'gravity-west.jpg'\n    },\n    {\n      name: 'Position: right top (top)',\n      width: 320,\n      height: 80,\n      gravity: sharp.position['right top'],\n      fixture: 'gravity-north.jpg'\n    },\n    {\n      name: 'Position: right top (right)',\n      width: 80,\n      height: 320,\n      gravity: sharp.position['right top'],\n      fixture: 'gravity-east.jpg'\n    },\n    {\n      name: 'Position: right bottom (bottom)',\n      width: 320,\n      height: 80,\n      gravity: sharp.position['right bottom'],\n      fixture: 'gravity-south.jpg'\n    },\n    {\n      name: 'Position: right bottom (right)',\n      width: 80,\n      height: 320,\n      gravity: sharp.position['right bottom'],\n      fixture: 'gravity-east.jpg'\n    },\n    {\n      name: 'Position: left bottom (bottom)',\n      width: 320,\n      height: 80,\n      gravity: sharp.position['left bottom'],\n      fixture: 'gravity-south.jpg'\n    },\n    {\n      name: 'Position: left bottom (left)',\n      width: 80,\n      height: 320,\n      gravity: sharp.position['left bottom'],\n      fixture: 'gravity-west.jpg'\n    },\n    {\n      name: 'Position: left top (top)',\n      width: 320,\n      height: 80,\n      gravity: sharp.position['left top'],\n      fixture: 'gravity-north.jpg'\n    },\n    {\n      name: 'Position: left top (left)',\n      width: 80,\n      height: 320,\n      gravity: sharp.position['left top'],\n      fixture: 'gravity-west.jpg'\n    },\n    // Gravity\n    {\n      name: 'Gravity: north',\n      width: 320,\n      height: 80,\n      gravity: sharp.gravity.north,\n      fixture: 'gravity-north.jpg'\n    },\n    {\n      name: 'Gravity: east',\n      width: 80,\n      height: 320,\n      gravity: sharp.gravity.east,\n      fixture: 'gravity-east.jpg'\n    },\n    {\n      name: 'Gravity: south',\n      width: 320,\n      height: 80,\n      gravity: sharp.gravity.south,\n      fixture: 'gravity-south.jpg'\n    },\n    {\n      name: 'Gravity: west',\n      width: 80,\n      height: 320,\n      gravity: sharp.gravity.west,\n      fixture: 'gravity-west.jpg'\n    },\n    {\n      name: 'Gravity: center',\n      width: 320,\n      height: 80,\n      gravity: sharp.gravity.center,\n      fixture: 'gravity-center.jpg'\n    },\n    {\n      name: 'Gravity: centre',\n      width: 80,\n      height: 320,\n      gravity: sharp.gravity.centre,\n      fixture: 'gravity-centre.jpg'\n    },\n    {\n      name: 'Default (centre)',\n      width: 80,\n      height: 320,\n      gravity: undefined,\n      fixture: 'gravity-centre.jpg'\n    },\n    {\n      name: 'Gravity: northeast (north)',\n      width: 320,\n      height: 80,\n      gravity: sharp.gravity.northeast,\n      fixture: 'gravity-north.jpg'\n    },\n    {\n      name: 'Gravity: northeast (east)',\n      width: 80,\n      height: 320,\n      gravity: sharp.gravity.northeast,\n      fixture: 'gravity-east.jpg'\n    },\n    {\n      name: 'Gravity: southeast (south)',\n      width: 320,\n      height: 80,\n      gravity: sharp.gravity.southeast,\n      fixture: 'gravity-south.jpg'\n    },\n    {\n      name: 'Gravity: southeast (east)',\n      width: 80,\n      height: 320,\n      gravity: sharp.gravity.southeast,\n      fixture: 'gravity-east.jpg'\n    },\n    {\n      name: 'Gravity: southwest (south)',\n      width: 320,\n      height: 80,\n      gravity: sharp.gravity.southwest,\n      fixture: 'gravity-south.jpg'\n    },\n    {\n      name: 'Gravity: southwest (west)',\n      width: 80,\n      height: 320,\n      gravity: sharp.gravity.southwest,\n      fixture: 'gravity-west.jpg'\n    },\n    {\n      name: 'Gravity: northwest (north)',\n      width: 320,\n      height: 80,\n      gravity: sharp.gravity.northwest,\n      fixture: 'gravity-north.jpg'\n    },\n    {\n      name: 'Gravity: northwest (west)',\n      width: 80,\n      height: 320,\n      gravity: sharp.gravity.northwest,\n      fixture: 'gravity-west.jpg'\n    }\n  ].forEach((settings) => {\n    it(settings.name, (_t, done) => {\n      sharp(fixtures.inputJpg)\n        .resize(settings.width, settings.height, {\n          fit: sharp.fit.cover,\n          position: settings.gravity\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(settings.width, info.width);\n          assert.strictEqual(settings.height, info.height);\n          fixtures.assertSimilar(fixtures.expected(settings.fixture), data, done);\n        });\n    });\n  });\n\n  it('Allows specifying the gravity as a string', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(80, 320, {\n        fit: sharp.fit.cover,\n        position: 'east'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(80, info.width);\n        assert.strictEqual(320, info.height);\n        fixtures.assertSimilar(fixtures.expected('gravity-east.jpg'), data, done);\n      });\n  });\n\n  it('Invalid position values fail', () => {\n    assert.throws(() => {\n      sharp().resize(null, null, { fit: 'cover', position: 9 });\n    }, /Expected valid position\\/gravity\\/strategy for position but received 9 of type number/);\n    assert.throws(() => {\n      sharp().resize(null, null, { fit: 'cover', position: 1.1 });\n    }, /Expected valid position\\/gravity\\/strategy for position but received 1.1 of type number/);\n    assert.throws(() => {\n      sharp().resize(null, null, { fit: 'cover', position: -1 });\n    }, /Expected valid position\\/gravity\\/strategy for position but received -1 of type number/);\n    assert.throws(() => {\n      sharp().resize(null, null, { fit: 'cover', position: 'zoinks' }).crop();\n    }, /Expected valid position\\/gravity\\/strategy for position but received zoinks of type string/);\n  });\n\n  it('Uses default value when none specified', () => {\n    assert.doesNotThrow(() => {\n      sharp().resize(null, null, { fit: 'cover' });\n    });\n  });\n\n  it('Skip crop when post-resize dimensions are at target', () => sharp(fixtures.inputJpg)\n      .resize(1600, 1200)\n      .toBuffer()\n      .then((input) => sharp(input)\n          .resize(1110, null, {\n            fit: sharp.fit.cover,\n            position: sharp.strategy.attention\n          })\n          .toBuffer({ resolveWithObject: true })\n          .then((result) => {\n            assert.strictEqual(1110, result.info.width);\n            assert.strictEqual(832, result.info.height);\n            assert.strictEqual(undefined, result.info.cropOffsetLeft);\n            assert.strictEqual(undefined, result.info.cropOffsetTop);\n          })));\n\n  describe('Animated WebP', () => {\n    it('Width only', (_t, done) => {\n      sharp(fixtures.inputWebPAnimated, { pages: -1 })\n        .resize(80, 320, { fit: sharp.fit.cover })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(80, info.width);\n          assert.strictEqual(320 * 9, info.height);\n          fixtures.assertSimilar(fixtures.expected('gravity-center-width.webp'), data, done);\n        });\n    });\n\n    it('Height only', (_t, done) => {\n      sharp(fixtures.inputWebPAnimated, { pages: -1 })\n        .resize(320, 80, { fit: sharp.fit.cover })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80 * 9, info.height);\n          fixtures.assertSimilar(fixtures.expected('gravity-center-height.webp'), data, done);\n        });\n    });\n  });\n\n  describe('Entropy-based strategy', () => {\n    it('JPEG', (_t, done) => {\n      sharp(fixtures.inputJpg)\n        .resize(80, 320, {\n          fit: 'cover',\n          position: sharp.strategy.entropy\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual('jpeg', info.format);\n          assert.strictEqual(3, info.channels);\n          assert.strictEqual(80, info.width);\n          assert.strictEqual(320, info.height);\n          assert.strictEqual(-117, info.cropOffsetLeft);\n          assert.strictEqual(0, info.cropOffsetTop);\n          fixtures.assertSimilar(fixtures.expected('crop-strategy-entropy.jpg'), data, done);\n        });\n    });\n\n    it('PNG', (_t, done) => {\n      sharp(fixtures.inputPngWithTransparency)\n        .resize(320, 80, {\n          fit: 'cover',\n          position: sharp.strategy.entropy\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual('png', info.format);\n          assert.strictEqual(4, info.channels);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80, info.height);\n          assert.strictEqual(0, info.cropOffsetLeft);\n          assert.strictEqual(-80, info.cropOffsetTop);\n          fixtures.assertSimilar(fixtures.expected('crop-strategy.png'), data, done);\n        });\n    });\n\n    it('supports the strategy passed as a string', (_t, done) => {\n      sharp(fixtures.inputPngWithTransparency)\n        .resize(320, 80, {\n          fit: 'cover',\n          position: 'entropy'\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual('png', info.format);\n          assert.strictEqual(4, info.channels);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80, info.height);\n          assert.strictEqual(0, info.cropOffsetLeft);\n          assert.strictEqual(-80, info.cropOffsetTop);\n          fixtures.assertSimilar(fixtures.expected('crop-strategy.png'), data, done);\n        });\n    });\n\n    it('Animated image rejects', () =>\n      assert.rejects(() => sharp(fixtures.inputGifAnimated, { animated: true })\n        .resize({\n          width: 100,\n          height: 8,\n          position: sharp.strategy.entropy\n        })\n        .toBuffer(),\n      /Resize strategy is not supported for multi-page images/\n      )\n    );\n  });\n\n  describe('Attention strategy', () => {\n    it('JPEG', (_t, done) => {\n      sharp(fixtures.inputJpg)\n        .resize(80, 320, {\n          fit: 'cover',\n          position: sharp.strategy.attention\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual('jpeg', info.format);\n          assert.strictEqual(3, info.channels);\n          assert.strictEqual(80, info.width);\n          assert.strictEqual(320, info.height);\n          assert.strictEqual(-107, info.cropOffsetLeft);\n          assert.strictEqual(0, info.cropOffsetTop);\n          assert.strictEqual(588, info.attentionX);\n          assert.strictEqual(640, info.attentionY);\n          fixtures.assertSimilar(fixtures.expected('crop-strategy-attention.jpg'), data, done);\n        });\n    });\n\n    it('PNG', (_t, done) => {\n      sharp(fixtures.inputPngWithTransparency)\n        .resize(320, 80, {\n          fit: 'cover',\n          position: sharp.strategy.attention\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual('png', info.format);\n          assert.strictEqual(4, info.channels);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80, info.height);\n          assert.strictEqual(0, info.cropOffsetLeft);\n          assert.strictEqual(0, info.cropOffsetTop);\n          assert.strictEqual(0, info.attentionX);\n          assert.strictEqual(0, info.attentionY);\n          fixtures.assertSimilar(fixtures.expected('crop-strategy.png'), data, done);\n        });\n    });\n\n    it('WebP', (_t, done) => {\n      sharp(fixtures.inputWebP)\n        .resize(320, 80, {\n          fit: 'cover',\n          position: sharp.strategy.attention\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual('webp', info.format);\n          assert.strictEqual(3, info.channels);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80, info.height);\n          assert.strictEqual(0, info.cropOffsetLeft);\n          assert.strictEqual(-161, info.cropOffsetTop);\n          assert.strictEqual(288, info.attentionX);\n          assert.strictEqual(745, info.attentionY);\n          fixtures.assertSimilar(fixtures.expected('crop-strategy.webp'), data, done);\n        });\n    });\n\n    it('supports the strategy passed as a string', (_t, done) => {\n      sharp(fixtures.inputPngWithTransparency)\n        .resize(320, 80, {\n          fit: 'cover',\n          position: 'attention'\n        })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual('png', info.format);\n          assert.strictEqual(4, info.channels);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(80, info.height);\n          assert.strictEqual(0, info.cropOffsetLeft);\n          assert.strictEqual(0, info.cropOffsetTop);\n          fixtures.assertSimilar(fixtures.expected('crop-strategy.png'), data, done);\n        });\n    });\n\n    it('Animated image rejects', () =>\n      assert.rejects(() => sharp(fixtures.inputGifAnimated, { animated: true })\n        .resize({\n          width: 100,\n          height: 8,\n          position: sharp.strategy.attention\n        })\n        .toBuffer(),\n      /Resize strategy is not supported for multi-page images/\n      )\n    );\n  });\n});\n"
  },
  {
    "path": "test/unit/resize.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Resize dimensions', () => {\n  it('Exact crop', (_t, done) => {\n    sharp(fixtures.inputJpg).resize(320, 240).toBuffer((err, data, info) => {\n      if (err) throw err;\n      assert.strictEqual(true, data.length > 0);\n      assert.strictEqual('jpeg', info.format);\n      assert.strictEqual(320, info.width);\n      assert.strictEqual(240, info.height);\n      done();\n    });\n  });\n\n  it('Fixed width', (_t, done) => {\n    sharp(fixtures.inputJpg).resize(320).toBuffer((err, data, info) => {\n      if (err) throw err;\n      assert.strictEqual(true, data.length > 0);\n      assert.strictEqual('jpeg', info.format);\n      assert.strictEqual(320, info.width);\n      assert.strictEqual(261, info.height);\n      done();\n    });\n  });\n\n  it('Fixed height', (_t, done) => {\n    sharp(fixtures.inputJpg).resize(null, 320).toBuffer((err, data, info) => {\n      if (err) throw err;\n      assert.strictEqual(true, data.length > 0);\n      assert.strictEqual('jpeg', info.format);\n      assert.strictEqual(392, info.width);\n      assert.strictEqual(320, info.height);\n      done();\n    });\n  });\n\n  it('Identity transform', (_t, done) => {\n    sharp(fixtures.inputJpg).toBuffer((err, data, info) => {\n      if (err) throw err;\n      assert.strictEqual(true, data.length > 0);\n      assert.strictEqual('jpeg', info.format);\n      assert.strictEqual(2725, info.width);\n      assert.strictEqual(2225, info.height);\n      done();\n    });\n  });\n\n  it('Upscale', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(3000)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(3000, info.width);\n        assert.strictEqual(2450, info.height);\n        done();\n      });\n  });\n\n  it('Invalid width - NaN', () => {\n    assert.throws(() => {\n      sharp().resize('spoons', 240);\n    }, /Expected positive integer for width but received spoons of type string/);\n  });\n\n  it('Invalid height - NaN', () => {\n    assert.throws(() => {\n      sharp().resize(320, 'spoons');\n    }, /Expected positive integer for height but received spoons of type string/);\n  });\n\n  it('Invalid width - float', () => {\n    assert.throws(() => {\n      sharp().resize(1.5, 240);\n    }, /Expected positive integer for width but received 1.5 of type number/);\n  });\n\n  it('Invalid height - float', () => {\n    assert.throws(() => {\n      sharp().resize(320, 1.5);\n    }, /Expected positive integer for height but received 1.5 of type number/);\n  });\n\n  it('Invalid width - via options', () => {\n    assert.throws(() => {\n      sharp().resize({ width: 1.5, height: 240 });\n    }, /Expected positive integer for width but received 1.5 of type number/);\n  });\n\n  it('Invalid height - via options', () => {\n    assert.throws(() => {\n      sharp().resize({ width: 320, height: 1.5 });\n    }, /Expected positive integer for height but received 1.5 of type number/);\n  });\n\n  it('Invalid width - too large', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(0x4000, 1)\n      .webp()\n      .toBuffer((err) => {\n        assert.strictEqual(true, err instanceof Error);\n        assert.strictEqual('Processed image is too large for the WebP format', err.message);\n        done();\n      });\n  });\n\n  it('Invalid height - too large', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(1, 0x4000)\n      .webp()\n      .toBuffer((err) => {\n        assert.strictEqual(true, err instanceof Error);\n        assert.strictEqual('Processed image is too large for the WebP format', err.message);\n        done();\n      });\n  });\n\n  it('Webp resize then extract large image', (_t, done) => {\n    sharp(fixtures.inputWebP)\n      .resize(0x4000, 0x4000)\n      .extract({ top: 0x2000, left: 0x2000, width: 256, height: 256 })\n      .webp()\n      .toBuffer((err, _data, info) => {\n        if (err) throw err;\n        assert.strictEqual('webp', info.format);\n        assert.strictEqual(256, info.width);\n        assert.strictEqual(256, info.height);\n        done();\n      });\n  });\n\n  it('WebP shrink-on-load rounds to zero, ensure recalculation is correct', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(1080, 607)\n      .webp()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('webp', info.format);\n        assert.strictEqual(1080, info.width);\n        assert.strictEqual(607, info.height);\n        sharp(data)\n          .resize(233, 131)\n          .toBuffer((err, _data, info) => {\n            if (err) throw err;\n            assert.strictEqual('webp', info.format);\n            assert.strictEqual(233, info.width);\n            assert.strictEqual(131, info.height);\n            done();\n          });\n      });\n  });\n\n  it('JPEG shrink-on-load with 90 degree rotation, ensure recalculation is correct', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(1920, 1280)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(1920, info.width);\n        assert.strictEqual(1280, info.height);\n        sharp(data)\n          .rotate(90)\n          .resize(533, 800)\n          .toBuffer((err, _data, info) => {\n            if (err) throw err;\n            assert.strictEqual(533, info.width);\n            assert.strictEqual(800, info.height);\n            done();\n          });\n      });\n  });\n\n  it('TIFF embed known to cause rounding errors', (_t, done) => {\n    sharp(fixtures.inputTiff)\n      .resize(240, 320, { fit: sharp.fit.contain })\n      .jpeg()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(240, info.width);\n        assert.strictEqual(320, info.height);\n        done();\n      });\n  });\n\n  it('TIFF known to cause rounding errors', (_t, done) => {\n    sharp(fixtures.inputTiff)\n      .resize(240, 320)\n      .jpeg()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(240, info.width);\n        assert.strictEqual(320, info.height);\n        done();\n      });\n  });\n\n  it('fit=inside, portrait', (_t, done) => {\n    sharp(fixtures.inputTiff)\n      .resize(320, 320, { fit: sharp.fit.inside })\n      .jpeg()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(243, info.width);\n        assert.strictEqual(320, info.height);\n        done();\n      });\n  });\n\n  it('fit=outside, portrait', (_t, done) => {\n    sharp(fixtures.inputTiff)\n      .resize(320, 320, { fit: sharp.fit.outside })\n      .jpeg()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(422, info.height);\n        done();\n      });\n  });\n\n  it('fit=inside, landscape', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 320, { fit: sharp.fit.inside })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(261, info.height);\n        done();\n      });\n  });\n\n  it('fit=outside, landscape', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 320, { fit: sharp.fit.outside })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(392, info.width);\n        assert.strictEqual(320, info.height);\n        done();\n      });\n  });\n\n  it('fit=inside, provide only one dimension', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize({\n        width: 320,\n        fit: sharp.fit.inside\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(261, info.height);\n        done();\n      });\n  });\n\n  it('fit=outside, provide only one dimension', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize({\n        width: 320,\n        fit: sharp.fit.outside\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(261, info.height);\n        done();\n      });\n  });\n\n  it('Do not enlarge when input width is already less than output width', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize({\n        width: 2800,\n        withoutEnlargement: true\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(2725, info.width);\n        assert.strictEqual(2225, info.height);\n        done();\n      });\n  });\n\n  it('Do not enlarge when input height is already less than output height', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize({\n        height: 2300,\n        withoutEnlargement: true\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(2725, info.width);\n        assert.strictEqual(2225, info.height);\n        done();\n      });\n  });\n\n  it('Do crop when fit = cover and withoutEnlargement = true and width >= outputWidth, and height < outputHeight', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize({\n        width: 3000,\n        height: 1000,\n        withoutEnlargement: true\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(2725, info.width);\n        assert.strictEqual(1000, info.height);\n        done();\n      });\n  });\n\n  it('Do crop when fit = cover and withoutEnlargement = true and width < outputWidth, and height >= outputHeight', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize({\n        width: 1500,\n        height: 2226,\n        withoutEnlargement: true\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(1500, info.width);\n        assert.strictEqual(2225, info.height);\n        done();\n      });\n  });\n\n  it('Do enlarge when input width is less than output width', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize({\n        width: 2800,\n        withoutEnlargement: false\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(2800, info.width);\n        assert.strictEqual(2286, info.height);\n        done();\n      });\n  });\n\n  it('Do enlarge when input width is less than output width', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize({\n        width: 2800,\n        withoutReduction: true\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(2800, info.width);\n        assert.strictEqual(2286, info.height);\n        done();\n      });\n  });\n\n  it('Do enlarge when input height is less than output height', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize({\n        height: 2300,\n        withoutReduction: true\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(2817, info.width);\n        assert.strictEqual(2300, info.height);\n        done();\n      });\n  });\n\n  it('Do enlarge when input width is less than output width', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize({\n        width: 2800,\n        withoutReduction: false\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(2800, info.width);\n        assert.strictEqual(2286, info.height);\n        done();\n      });\n  });\n\n  it('Do not resize when both withoutEnlargement and withoutReduction are true', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 320, { fit: 'fill', withoutEnlargement: true, withoutReduction: true })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(2725, info.width);\n        assert.strictEqual(2225, info.height);\n        done();\n      });\n  });\n\n  it('Do not reduce size when fit = outside and withoutReduction are true and height > outputHeight and width > outputWidth', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 320, { fit: 'outside', withoutReduction: true })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(2725, info.width);\n        assert.strictEqual(2225, info.height);\n        done();\n      });\n  });\n\n  it('Do resize when fit = outside and withoutReduction are true and input height > height and input width > width ', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(3000, 3000, { fit: 'outside', withoutReduction: true })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(3674, info.width);\n        assert.strictEqual(3000, info.height);\n        done();\n      });\n  });\n\n  it('fit=fill, downscale width and height', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 320, { fit: 'fill' })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(320, info.height);\n        done();\n      });\n  });\n\n  it('fit=fill, downscale width', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize({\n        width: 320,\n        fit: 'fill'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(2225, info.height);\n        done();\n      });\n  });\n\n  it('fit=fill, downscale height', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize({\n        height: 320,\n        fit: 'fill'\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(2725, info.width);\n        assert.strictEqual(320, info.height);\n        done();\n      });\n  });\n\n  it('fit=fill, upscale width and height', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(3000, 3000, { fit: 'fill' })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(3000, info.width);\n        assert.strictEqual(3000, info.height);\n        done();\n      });\n  });\n\n  it('fit=fill, upscale width', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(3000, null, { fit: 'fill' })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(3000, info.width);\n        assert.strictEqual(2225, info.height);\n        done();\n      });\n  });\n\n  it('fit=fill, upscale height', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(null, 3000, { fit: 'fill' })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(2725, info.width);\n        assert.strictEqual(3000, info.height);\n        done();\n      });\n  });\n\n  it('fit=fill, downscale width, upscale height', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 3000, { fit: 'fill' })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(3000, info.height);\n        done();\n      });\n  });\n\n  it('fit=fill, upscale width, downscale height', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(3000, 320, { fit: 'fill' })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(3000, info.width);\n        assert.strictEqual(320, info.height);\n        done();\n      });\n  });\n\n  it('fit=fill, identity transform', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(null, null, { fit: 'fill' })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(2725, info.width);\n        assert.strictEqual(2225, info.height);\n        done();\n      });\n  });\n\n  it('Dimensions that result in differing even shrinks on each axis', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(645, 399)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(645, info.width);\n        assert.strictEqual(399, info.height);\n        sharp(data)\n          .resize(150, 100)\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            assert.strictEqual(150, info.width);\n            assert.strictEqual(100, info.height);\n            fixtures.assertSimilar(fixtures.expected('resize-diff-shrink-even.jpg'), data, done);\n          });\n      });\n  });\n\n  it('Dimensions that result in differing odd shrinks on each axis', (_t, done) => sharp(fixtures.inputJpg)\n      .resize(600, 399)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(600, info.width);\n        assert.strictEqual(399, info.height);\n        sharp(data)\n          .resize(200)\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            assert.strictEqual(200, info.width);\n            assert.strictEqual(133, info.height);\n            fixtures.assertSimilar(fixtures.expected('resize-diff-shrink-odd.jpg'), data, done);\n          });\n      }));\n\n  [\n    true,\n    false\n  ].forEach((value) => {\n    it(`fastShrinkOnLoad: ${value} does not causes image shifts`, (_t, done) => {\n      sharp(fixtures.inputJpgCenteredImage)\n        .resize(9, 8, { fastShrinkOnLoad: value })\n        .png()\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual(9, info.width);\n          assert.strictEqual(8, info.height);\n          fixtures.assertSimilar(fixtures.expected('fast-shrink-on-load.png'), data, done);\n        });\n    });\n  });\n\n  [\n    sharp.kernel.nearest,\n    sharp.kernel.cubic,\n    sharp.kernel.mitchell,\n    sharp.kernel.lanczos2,\n    sharp.kernel.lanczos3\n  ].forEach((kernel) => {\n    it(`kernel ${kernel}`, (_t, done) => {\n      sharp(fixtures.inputJpg)\n        .resize(320, null, { kernel })\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual('jpeg', info.format);\n          assert.strictEqual(320, info.width);\n          fixtures.assertSimilar(fixtures.inputJpg, data, done);\n        });\n    });\n  });\n\n  it('nearest upsampling with integral factor', (_t, done) => {\n    sharp(fixtures.inputTiff8BitDepth)\n      .resize(210, 210, { kernel: 'nearest' })\n      .png()\n      .toBuffer((err, _data, info) => {\n        if (err) throw err;\n        assert.strictEqual(210, info.width);\n        assert.strictEqual(210, info.height);\n        done();\n      });\n  });\n\n  it('Ensure shortest edge (height) is at least 1 pixel', () => sharp({\n      create: {\n        width: 10,\n        height: 2,\n        channels: 3,\n        background: 'red'\n      }\n    })\n      .resize(2)\n      .toBuffer({ resolveWithObject: true })\n      .then((output) => {\n        assert.strictEqual(2, output.info.width);\n        assert.strictEqual(1, output.info.height);\n      }));\n\n  it('Ensure shortest edge (width) is at least 1 pixel', () => sharp({\n      create: {\n        width: 2,\n        height: 10,\n        channels: 3,\n        background: 'red'\n      }\n    })\n      .resize(null, 2)\n      .toBuffer({ resolveWithObject: true })\n      .then((output) => {\n        assert.strictEqual(1, output.info.width);\n        assert.strictEqual(2, output.info.height);\n      }));\n\n  it('Ensure embedded shortest edge (height) is at least 1 pixel', () => sharp({\n      create: {\n        width: 200,\n        height: 1,\n        channels: 3,\n        background: 'red'\n      }\n    })\n      .resize({ width: 50, height: 50, fit: sharp.fit.contain })\n      .toBuffer({ resolveWithObject: true })\n      .then((output) => {\n        assert.strictEqual(50, output.info.width);\n        assert.strictEqual(50, output.info.height);\n      }));\n\n  it('Ensure embedded shortest edge (width) is at least 1 pixel', () => sharp({\n      create: {\n        width: 1,\n        height: 200,\n        channels: 3,\n        background: 'red'\n      }\n    })\n      .resize({ width: 50, height: 50, fit: sharp.fit.contain })\n      .toBuffer({ resolveWithObject: true })\n      .then((output) => {\n        assert.strictEqual(50, output.info.width);\n        assert.strictEqual(50, output.info.height);\n      }));\n\n  it('Skip shrink-on-load where one dimension <4px', async () => {\n    const jpeg = await sharp({\n      create: {\n        width: 100,\n        height: 3,\n        channels: 3,\n        background: 'red'\n      }\n    })\n      .jpeg()\n      .toBuffer();\n\n    const { info } = await sharp(jpeg)\n      .resize(8)\n      .toBuffer({ resolveWithObject: true });\n\n    assert.strictEqual(info.width, 8);\n    assert.strictEqual(info.height, 1);\n  });\n\n  it('Skip JPEG shrink-on-load for known libjpeg rounding errors', async () => {\n    const input = await sharp({\n      create: {\n        width: 1000,\n        height: 667,\n        channels: 3,\n        background: 'red'\n      }\n    })\n      .jpeg()\n      .toBuffer();\n\n    const output = await sharp(input)\n      .resize({ width: 500 })\n      .toBuffer();\n\n    const { width, height } = await sharp(output).metadata();\n    assert.strictEqual(width, 500);\n    assert.strictEqual(height, 334);\n  });\n\n  it('unknown kernel throws', () => {\n    assert.throws(() => {\n      sharp().resize(null, null, { kernel: 'unknown' });\n    });\n  });\n\n  it('unknown fit throws', () => {\n    assert.throws(() => {\n      sharp().resize(null, null, { fit: 'unknown' });\n    });\n  });\n\n  it('unknown position throws', () => {\n    assert.throws(() => {\n      sharp().resize(null, null, { position: 'unknown' });\n    });\n  });\n\n  it('Multiple resize emits warning', () => {\n    let warningMessage = '';\n    const s = sharp();\n    s.on('warning', (msg) => { warningMessage = msg; });\n    s.resize(1);\n    assert.strictEqual(warningMessage, '');\n    s.resize(2);\n    assert.strictEqual(warningMessage, 'ignoring previous resize options');\n  });\n});\n"
  },
  {
    "path": "test/unit/rotate.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Rotation', () => {\n  ['autoOrient', 'constructor'].forEach((rotateMethod) => {\n    describe(`Auto orientation via ${rotateMethod}:`, () => {\n      const options = rotateMethod === 'constructor' ? { autoOrient: true } : {};\n\n      ['Landscape', 'Portrait'].forEach((orientation) => {\n        [1, 2, 3, 4, 5, 6, 7, 8].forEach((exifTag) => {\n          const input = fixtures[`inputJpgWith${orientation}Exif${exifTag}`];\n          const expectedOutput = fixtures.expected(`${orientation}_${exifTag}-out.jpg`);\n          it(`${orientation} image with EXIF Orientation ${exifTag}: Auto-rotate`, (_t, done) => {\n            const [expectedWidth, expectedHeight] = orientation === 'Landscape' ? [600, 450] : [450, 600];\n\n            const img = sharp(input, options);\n            rotateMethod === 'autoOrient' && img.autoOrient();\n\n            img.toBuffer((err, data, info) => {\n              if (err) throw err;\n              assert.strictEqual(info.width, expectedWidth);\n              assert.strictEqual(info.height, expectedHeight);\n              fixtures.assertSimilar(expectedOutput, data, done);\n            });\n          });\n\n          it(`${orientation} image with EXIF Orientation ${exifTag}: Auto-rotate then resize`, (_t, done) => {\n            const [expectedWidth, expectedHeight] = orientation === 'Landscape' ? [320, 240] : [320, 427];\n\n            const img = sharp(input, options);\n            rotateMethod === 'autoOrient' && img.autoOrient();\n\n            img.resize({ width: 320 })\n              .toBuffer((err, data, info) => {\n                if (err) throw err;\n                assert.strictEqual(info.width, expectedWidth);\n                assert.strictEqual(info.height, expectedHeight);\n                fixtures.assertSimilar(expectedOutput, data, done);\n              });\n          });\n\n          if (rotateMethod !== 'constructor') {\n            it(`${orientation} image with EXIF Orientation ${exifTag}: Resize then auto-rotate`, (_t, done) => {\n              const [expectedWidth, expectedHeight] = orientation === 'Landscape'\n                ? (exifTag < 5) ? [320, 240] : [320, 240]\n                : [320, 427];\n\n              const img = sharp(input, options)\n                .resize({ width: 320 });\n\n              rotateMethod === 'autoOrient' && img.autoOrient();\n              img.toBuffer((err, data, info) => {\n                if (err) throw err;\n                assert.strictEqual(info.width, expectedWidth);\n                assert.strictEqual(info.height, expectedHeight);\n                fixtures.assertSimilar(expectedOutput, data, done);\n              });\n            });\n          }\n\n          [true, false].forEach((doResize) => {\n            [90, 180, 270, 45].forEach((angle) => {\n              const [inputWidth, inputHeight] = orientation === 'Landscape' ? [600, 450] : [450, 600];\n              const expectedOutput = fixtures.expected(`${orientation}_${exifTag}_rotate${angle}-out.jpg`);\n              it(`${orientation} image with EXIF Orientation ${exifTag}: Auto-rotate then rotate ${angle} ${doResize ? 'and resize' : ''}`, (_t, done) => {\n                const [width, height] = (angle === 45 ? [742, 742] : [inputWidth, inputHeight]).map((x) => doResize ? Math.floor(x / 1.875) : x);\n                const [expectedWidth, expectedHeight] = angle % 180 === 0 ? [width, height] : [height, width];\n\n                const img = sharp(input, options);\n                rotateMethod === 'autoOrient' && img.autoOrient();\n\n                img.rotate(angle);\n                doResize && img.resize(expectedWidth);\n\n                img.toBuffer((err, data, info) => {\n                  if (err) throw err;\n                  assert.strictEqual(info.width, expectedWidth);\n                  assert.strictEqual(info.height, expectedHeight);\n                  fixtures.assertSimilar(expectedOutput, data, done);\n                });\n              });\n            });\n\n            [[true, true], [true, false], [false, true]].forEach(([flip, flop]) => {\n              const [inputWidth, inputHeight] = orientation === 'Landscape' ? [600, 450] : [450, 600];\n              const flipFlopFileName = [flip && 'flip', flop && 'flop'].filter(Boolean).join('_');\n              const flipFlopTestName = [flip && 'flip', flop && 'flop'].filter(Boolean).join(' & ');\n              it(`${orientation} image with EXIF Orientation ${exifTag}: Auto-rotate then ${flipFlopTestName} ${doResize ? 'and resize' : ''}`, (_t, done) => {\n                const expectedOutput = fixtures.expected(`${orientation}_${exifTag}_${flipFlopFileName}-out.jpg`);\n\n                const img = sharp(input, options);\n\n                rotateMethod === 'autoOrient' && img.autoOrient();\n\n                flip && img.flip();\n                flop && img.flop();\n                doResize && img.resize(orientation === 'Landscape' ? 320 : 240);\n\n                img.toBuffer((err, data, info) => {\n                  if (err) throw err;\n                  assert.strictEqual(info.width, inputWidth / (doResize ? 1.875 : 1));\n                  assert.strictEqual(info.height, inputHeight / (doResize ? 1.875 : 1));\n                  fixtures.assertSimilar(expectedOutput, data, done);\n                });\n              });\n            });\n          });\n        });\n      });\n    });\n  });\n\n  it('Rotate by 30 degrees with semi-transparent background', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320)\n      .rotate(30, { background: { r: 255, g: 0, b: 0, alpha: 0.5 } })\n      .png()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(408, info.width);\n        assert.strictEqual(386, info.height);\n        fixtures.assertSimilar(fixtures.expected('rotate-transparent-bg.png'), data, done);\n      });\n  });\n\n  it('Rotate by 30 degrees with solid background', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320)\n      .rotate(30, { background: { r: 255, g: 0, b: 0 } })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(408, info.width);\n        assert.strictEqual(386, info.height);\n        fixtures.assertSimilar(fixtures.expected('rotate-solid-bg.jpg'), data, done);\n      });\n  });\n\n  it('Rotate by 90 degrees, respecting output input size', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .rotate(90)\n      .resize(320, 240)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        done();\n      });\n  });\n\n  it('Resize then rotate by 30 degrees, respecting output input size', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .rotate(30)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(397, info.width);\n        assert.strictEqual(368, info.height);\n        done();\n      });\n  });\n\n  [-3690, -450, -90, 90, 450, 3690].forEach((angle) => {\n    it(`Rotate by any 90-multiple angle (${angle}deg)`, (_t, done) => {\n      sharp(fixtures.inputJpg320x240).rotate(angle).toBuffer((err, _data, info) => {\n        if (err) throw err;\n        assert.strictEqual(240, info.width);\n        assert.strictEqual(320, info.height);\n        done();\n      });\n    });\n  });\n\n  [-3750, -510, -150, 30, 390, 3630].forEach((angle) => {\n    it(`Rotate by any 30-multiple angle (${angle}deg)`, (_t, done) => {\n      sharp(fixtures.inputJpg320x240).rotate(angle).toBuffer((err, _data, info) => {\n        if (err) throw err;\n        assert.strictEqual(397, info.width);\n        assert.strictEqual(368, info.height);\n        done();\n      });\n    });\n  });\n\n  [-3780, -540, 0, 180, 540, 3780].forEach((angle) => {\n    it(`Rotate by any 180-multiple angle (${angle}deg)`, (_t, done) => {\n      sharp(fixtures.inputJpg320x240).rotate(angle).toBuffer((err, _data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        done();\n      });\n    });\n  });\n\n  it('Rotate by 270 degrees, square output ignoring aspect ratio', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(240, 240, { fit: sharp.fit.fill })\n      .rotate(270)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(240, info.width);\n        assert.strictEqual(240, info.height);\n        sharp(data).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(240, metadata.width);\n          assert.strictEqual(240, metadata.height);\n          done();\n        });\n      });\n  });\n\n  it('Rotate by 315 degrees, square output ignoring aspect ratio', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(240, 240, { fit: sharp.fit.fill })\n      .rotate(315)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(339, info.width);\n        assert.strictEqual(339, info.height);\n        sharp(data).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(339, metadata.width);\n          assert.strictEqual(339, metadata.height);\n          done();\n        });\n      });\n  });\n\n  it('Rotate by 270 degrees, rectangular output ignoring aspect ratio', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .rotate(270)\n      .resize(320, 240, { fit: sharp.fit.fill })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        sharp(data).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(320, metadata.width);\n          assert.strictEqual(240, metadata.height);\n          done();\n        });\n      });\n  });\n\n  it('Auto-rotate by 270 degrees, rectangular output ignoring aspect ratio', (_t, done) => {\n    sharp(fixtures.inputJpgWithLandscapeExif8)\n      .resize(320, 240, { fit: sharp.fit.fill })\n      .rotate()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        sharp(data).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(320, metadata.width);\n          assert.strictEqual(240, metadata.height);\n          done();\n        });\n      });\n  });\n\n  it('Rotate by 30 degrees, rectangular output ignoring aspect ratio', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240, { fit: sharp.fit.fill })\n      .rotate(30)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(397, info.width);\n        assert.strictEqual(368, info.height);\n        sharp(data).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(397, metadata.width);\n          assert.strictEqual(368, metadata.height);\n          done();\n        });\n      });\n  });\n\n  it('Input image has Orientation EXIF tag but do not rotate output', (_t, done) => {\n    sharp(fixtures.inputJpgWithExif)\n      .resize(320)\n      .withMetadata()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(427, info.height);\n        sharp(data).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(8, metadata.orientation);\n          done();\n        });\n      });\n  });\n\n  it('Input image has Orientation EXIF tag value of 8 (270 degrees), auto-rotate', (_t, done) => {\n    sharp(fixtures.inputJpgWithExif)\n      .rotate()\n      .resize(320)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('exif-8.jpg'), data, done);\n      });\n  });\n\n  it('Override EXIF Orientation tag metadata after auto-rotate', (_t, done) => {\n    sharp(fixtures.inputJpgWithExif)\n      .rotate()\n      .resize(320)\n      .withMetadata({ orientation: 3 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        sharp(data).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(3, metadata.orientation);\n          fixtures.assertSimilar(fixtures.expected('exif-8.jpg'), data, done);\n        });\n      });\n  });\n\n  it('Input image has Orientation EXIF tag value of 5 (270 degrees + flip), auto-rotate', (_t, done) => {\n    sharp(fixtures.inputJpgWithExifMirroring)\n      .rotate()\n      .resize(320)\n      .withMetadata()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        sharp(data).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(1, metadata.orientation);\n          fixtures.assertSimilar(fixtures.expected('exif-5.jpg'), data, done);\n        });\n      });\n  });\n\n  it('Attempt to auto-rotate using image that has no EXIF', (_t, done) => {\n    sharp(fixtures.inputJpg).rotate().resize(320).toBuffer((err, data, info) => {\n      if (err) throw err;\n      assert.strictEqual(true, data.length > 0);\n      assert.strictEqual('jpeg', info.format);\n      assert.strictEqual(320, info.width);\n      assert.strictEqual(261, info.height);\n      done();\n    });\n  });\n\n  it('Attempt to auto-rotate image format without EXIF support', (_t, done) => {\n    sharp(fixtures.inputPng)\n      .rotate()\n      .resize(320)\n      .jpeg()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(236, info.height);\n        done();\n      });\n  });\n\n  it('Rotate with a string argument, should fail', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).rotate('not-a-number');\n    });\n  });\n\n  it('Animated image rotate-then-extract rejects', () =>\n    assert.rejects(() => sharp(fixtures.inputGifAnimated, { animated: true })\n      .rotate(1)\n      .extract({\n        top: 1,\n        left: 1,\n        width: 10,\n        height: 10\n      })\n      .toBuffer(),\n    /Rotate is not supported for multi-page images/\n    )\n  );\n\n  it('Animated image extract-then-rotate rejects', () =>\n    assert.rejects(() => sharp(fixtures.inputGifAnimated, { animated: true })\n      .extract({\n        top: 1,\n        left: 1,\n        width: 10,\n        height: 10\n      })\n      .rotate(1)\n      .toBuffer(),\n    /Rotate is not supported for multi-page images/\n    )\n  );\n\n  it('Animated image rotate 180', () =>\n    assert.doesNotReject(() => sharp(fixtures.inputGifAnimated, { animated: true })\n      .rotate(180)\n      .toBuffer()\n    )\n  );\n\n  it('Animated image rotate non-180 rejects', () =>\n    assert.rejects(() => sharp(fixtures.inputGifAnimated, { animated: true })\n      .rotate(90)\n      .toBuffer(),\n    /Rotate is not supported for multi-page images/\n    )\n  );\n\n  it('Multiple rotate emits warning', () => {\n    let warningMessage = '';\n    const s = sharp();\n    s.on('warning', (msg) => { warningMessage = msg; });\n    s.rotate(90);\n    assert.strictEqual(warningMessage, '');\n    s.rotate(180);\n    assert.strictEqual(warningMessage, 'ignoring previous rotate options');\n  });\n\n  it('Multiple rotate: last one wins (cardinal)', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .rotate(45)\n      .rotate(90)\n      .toBuffer((err, _data, info) => {\n        if (err) throw err;\n        assert.strictEqual(2225, info.width);\n        assert.strictEqual(2725, info.height);\n        done();\n      });\n  });\n\n  it('Multiple rotate: last one wins (non cardinal)', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .rotate(90)\n      .rotate(45)\n      .toBuffer((err, _data, info) => {\n        if (err) throw err;\n        assert.strictEqual(3500, info.width);\n        assert.strictEqual(3500, info.height);\n        done();\n      });\n  });\n\n  it('Flip - vertical', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320)\n      .flip()\n      .withMetadata()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(261, info.height);\n        sharp(data).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(1, metadata.orientation);\n          fixtures.assertSimilar(fixtures.expected('flip.jpg'), data, done);\n        });\n      });\n  });\n\n  it('Flop - horizontal', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320)\n      .flop()\n      .withMetadata()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(261, info.height);\n        sharp(data).metadata((err, metadata) => {\n          if (err) throw err;\n          assert.strictEqual(1, metadata.orientation);\n          fixtures.assertSimilar(fixtures.expected('flop.jpg'), data, done);\n        });\n      });\n  });\n\n  it('Flip and flop', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320)\n      .flip()\n      .flop()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(261, info.height);\n        fixtures.assertSimilar(fixtures.expected('flip-and-flop.jpg'), data, done);\n      });\n  });\n\n  it('Neither flip nor flop', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320)\n      .flip(false)\n      .flop(false)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(261, info.height);\n        fixtures.assertSimilar(fixtures.inputJpg, data, done);\n      });\n  });\n\n  it('Auto-rotate and flip', (_t, done) => {\n    sharp(fixtures.inputJpgWithExif)\n      .rotate()\n      .flip()\n      .resize(320)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('rotate-and-flip.jpg'), data, done);\n      });\n  });\n\n  it('Auto-rotate and flop', (_t, done) => {\n    sharp(fixtures.inputJpgWithExif)\n      .rotate()\n      .flop()\n      .resize(320)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('rotate-and-flop.jpg'), data, done);\n      });\n  });\n\n  it('Auto-rotate and shrink-on-load', async () => {\n    const [r, g, b] = await sharp(fixtures.inputJpgWithLandscapeExif3)\n      .rotate()\n      .resize(8)\n      .raw()\n      .toBuffer();\n\n    assert.strictEqual(r, 61);\n    assert.strictEqual(g, 74);\n    assert.strictEqual(b, 51);\n  });\n\n  it('Flip and rotate ordering', async () => {\n    const [r, g, b] = await sharp(fixtures.inputJpgWithPortraitExif5)\n      .flip()\n      .rotate(90)\n      .raw()\n      .toBuffer();\n\n    assert.strictEqual(r, 55);\n    assert.strictEqual(g, 65);\n    assert.strictEqual(b, 31);\n  });\n\n  it('Flip, rotate and resize ordering', async () => {\n    const [r, g, b] = await sharp(fixtures.inputJpgWithPortraitExif5)\n      .flip()\n      .rotate(90)\n      .resize(449)\n      .raw()\n      .toBuffer();\n\n    assert.strictEqual(r, 54);\n    assert.strictEqual(g, 64);\n    assert.strictEqual(b, 30);\n  });\n\n  it('Resize after affine-based rotation does not overcompute', async () =>\n    sharp({\n      create: {\n        width: 4640,\n        height: 2610,\n        channels: 3,\n        background: 'black'\n      }\n    })\n      .rotate(28)\n      .resize({ width: 640, height: 360 })\n      .raw()\n      .timeout({ seconds: 5 })\n      .toBuffer()\n  );\n\n  it('Rotate 90 then resize with inside fit', async () => {\n    const data = await sharp({ create: { width: 16, height: 8, channels: 3, background: 'red' } })\n      .rotate(90)\n      .resize({ width: 6, fit: 'inside' })\n      .png({ compressionLevel: 0 })\n      .toBuffer();\n\n    const { width, height } = await sharp(data).metadata();\n    assert.strictEqual(width, 6);\n    assert.strictEqual(height, 12);\n  });\n\n  it('Resize with inside fit then rotate 90', async () => {\n    const data = await sharp({ create: { width: 16, height: 8, channels: 3, background: 'red' } })\n      .resize({ width: 6, fit: 'inside' })\n      .rotate(90)\n      .png({ compressionLevel: 0 })\n      .toBuffer();\n\n    const { width, height } = await sharp(data).metadata();\n    assert.strictEqual(width, 3);\n    assert.strictEqual(height, 6);\n  });\n\n  it('Shrink-on-load with autoOrient', async () => {\n    const data = await sharp(fixtures.inputJpgWithLandscapeExif6)\n      .resize(8)\n      .autoOrient()\n      .avif({ effort: 0 })\n      .toBuffer();\n\n    const { width, height, orientation } = await sharp(data).metadata();\n    assert.strictEqual(width, 8);\n    assert.strictEqual(height, 6);\n    assert.strictEqual(orientation, undefined);\n  });\n\n  it('Auto-orient and rotate 45', async () => {\n    const data = await sharp(fixtures.inputJpgWithLandscapeExif2, { autoOrient: true })\n      .rotate(45)\n      .toBuffer();\n\n    const { width, height } = await sharp(data).metadata();\n    assert.strictEqual(width, 742);\n    assert.strictEqual(height, 742);\n  });\n\n  it('Auto-orient, extract and rotate 45', async () => {\n    const data = await sharp(fixtures.inputJpgWithLandscapeExif2, { autoOrient: true })\n      .extract({ left: 20, top: 20, width: 200, height: 100 })\n      .rotate(45)\n      .toBuffer();\n\n    const { width, height } = await sharp(data).metadata();\n    assert.strictEqual(width, 212);\n    assert.strictEqual(height, 212);\n  });\n\n  it('Invalid autoOrient throws', () =>\n    assert.throws(\n      () => sharp({ autoOrient: 'fail' }),\n      /Expected boolean for autoOrient but received fail of type string/\n    )\n  );\n});\n"
  },
  {
    "path": "test/unit/sharpen.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Sharpen', () => {\n  it('specific radius 10 (sigma 6)', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .sharpen(6)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('sharpen-10.jpg'), data, done);\n      });\n  });\n\n  it('specific radius 3 (sigma 1.5) and levels 0.5, 2.5', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .sharpen(1.5, 0.5, 2.5)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('sharpen-3-0.5-2.5.jpg'), data, done);\n      });\n  });\n\n  it('specific radius 5 (sigma 3.5) and levels 2, 4', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .sharpen(3.5, 2, 4)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('sharpen-5-2-4.jpg'), data, done);\n      });\n  });\n\n  it('sigma=3.5, m1=2, m2=4', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .sharpen({ sigma: 3.5, m1: 2, m2: 4 })\n      .toBuffer()\n      .then(data => fixtures.assertSimilar(fixtures.expected('sharpen-5-2-4.jpg'), data, done));\n  });\n\n  it('sigma=3.5, m1=2, m2=4, x1=2, y2=5, y3=25', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .sharpen({ sigma: 3.5, m1: 2, m2: 4, x1: 2, y2: 5, y3: 25 })\n      .toBuffer()\n      .then(data => fixtures.assertSimilar(fixtures.expected('sharpen-5-2-4.jpg'), data, done));\n  });\n\n  if (!process.env.SHARP_TEST_WITHOUT_CACHE) {\n    it('specific radius/levels with alpha channel', (_t, done) => {\n      sharp(fixtures.inputPngWithTransparency)\n        .resize(320, 240)\n        .sharpen(5, 4, 8)\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual('png', info.format);\n          assert.strictEqual(4, info.channels);\n          assert.strictEqual(320, info.width);\n          assert.strictEqual(240, info.height);\n          fixtures.assertSimilar(fixtures.expected('sharpen-rgba.png'), data, done);\n        });\n    });\n  }\n\n  it('mild sharpen', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .sharpen()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('sharpen-mild.jpg'), data, done);\n      });\n  });\n\n  it('invalid sigma', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).sharpen(-1.5);\n    });\n  });\n\n  it('invalid flat', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).sharpen(1, -1);\n    });\n  });\n\n  it('invalid jagged', () => {\n    assert.throws(() => {\n      sharp(fixtures.inputJpg).sharpen(1, 1, -1);\n    });\n  });\n\n  it('invalid options.sigma', () => assert.throws(\n    () => sharp().sharpen({ sigma: -1 }),\n    /Expected number between 0\\.000001 and 10 for options\\.sigma but received -1 of type number/\n  ));\n\n  it('invalid options.m1', () => assert.throws(\n    () => sharp().sharpen({ sigma: 1, m1: -1 }),\n    /Expected number between 0 and 1000000 for options\\.m1 but received -1 of type number/\n  ));\n\n  it('invalid options.m2', () => assert.throws(\n    () => sharp().sharpen({ sigma: 1, m2: -1 }),\n    /Expected number between 0 and 1000000 for options\\.m2 but received -1 of type number/\n  ));\n\n  it('invalid options.x1', () => assert.throws(\n    () => sharp().sharpen({ sigma: 1, x1: -1 }),\n    /Expected number between 0 and 1000000 for options\\.x1 but received -1 of type number/\n  ));\n\n  it('invalid options.y2', () => assert.throws(\n    () => sharp().sharpen({ sigma: 1, y2: -1 }),\n    /Expected number between 0 and 1000000 for options\\.y2 but received -1 of type number/\n  ));\n\n  it('invalid options.y3', () => assert.throws(\n    () => sharp().sharpen({ sigma: 1, y3: -1 }),\n    /Expected number between 0 and 1000000 for options\\.y3 but received -1 of type number/\n  ));\n\n  it('sharpened image is larger than non-sharpened', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .sharpen(false)\n      .toBuffer((err, notSharpened, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, notSharpened.length > 0);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .sharpen(true)\n          .toBuffer((err, sharpened, info) => {\n            if (err) throw err;\n            assert.strictEqual(true, sharpened.length > 0);\n            assert.strictEqual(true, sharpened.length > notSharpened.length);\n            assert.strictEqual('jpeg', info.format);\n            assert.strictEqual(320, info.width);\n            assert.strictEqual(240, info.height);\n            done();\n          });\n      });\n  });\n});\n"
  },
  {
    "path": "test/unit/stats.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\n// Test Helpers\nconst threshold = 0.001;\nfunction isInAcceptableRange (actual, expected) {\n  return actual >= ((1 - threshold) * expected) && actual <= ((1 + threshold) * expected);\n}\nfunction isInRange (actual, min, max) {\n  return actual >= min && actual <= max;\n}\nfunction isInteger (val) {\n  return Number.isInteger(val);\n}\n\ndescribe('Image Stats', () => {\n  it('JPEG', (_t, done) => {\n    sharp(fixtures.inputJpg).stats((err, stats) => {\n      if (err) throw err;\n\n      assert.strictEqual(true, stats.isOpaque);\n      assert.strictEqual(true, isInAcceptableRange(stats.entropy, 7.332915340666659));\n      assert.strictEqual(true, isInAcceptableRange(stats.sharpness, 0.7883011147075762));\n\n      const { r, g, b } = stats.dominant;\n      assert.strictEqual(40, r);\n      assert.strictEqual(40, g);\n      assert.strictEqual(40, b);\n\n      // red channel\n      assert.strictEqual(0, stats.channels[0].min);\n      assert.strictEqual(255, stats.channels[0].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].sum, 615101275));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].squaresSum, 83061892917));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].mean, 101.44954540768993));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].stdev, 58.373870588815414));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 2725));\n\n      // green channel\n      assert.strictEqual(0, stats.channels[1].min);\n      assert.strictEqual(255, stats.channels[1].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].sum, 462824115));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].squaresSum, 47083677255));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].mean, 76.33425255128337));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].stdev, 44.03023262954866));\n      assert.strictEqual(true, isInteger(stats.channels[1].minX));\n      assert.strictEqual(true, isInRange(stats.channels[1].minX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[1].minY));\n      assert.strictEqual(true, isInRange(stats.channels[1].minY, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[1].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[1].maxX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[1].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[1].maxY, 0, 2725));\n\n      // blue channel\n      assert.strictEqual(0, stats.channels[2].min);\n      assert.strictEqual(255, stats.channels[2].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].sum, 372986756));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].squaresSum, 32151543524));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].mean, 61.51724663436759));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].stdev, 38.96702865090125));\n      assert.strictEqual(true, isInteger(stats.channels[2].minX));\n      assert.strictEqual(true, isInRange(stats.channels[2].minX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[2].minY));\n      assert.strictEqual(true, isInRange(stats.channels[2].minY, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[2].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[2].maxX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[2].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[2].maxY, 0, 2725));\n\n      done();\n    });\n  });\n\n  it('PNG without transparency', (_t, done) => {\n    sharp(fixtures.inputPng).stats((err, stats) => {\n      if (err) throw err;\n\n      assert.strictEqual(true, stats.isOpaque);\n      assert.strictEqual(true, isInAcceptableRange(stats.entropy, 0.3409031108021736));\n      assert.strictEqual(true, isInAcceptableRange(stats.sharpness, 9.111356137722868));\n\n      const { r, g, b } = stats.dominant;\n      assert.strictEqual(248, r);\n      assert.strictEqual(248, g);\n      assert.strictEqual(248, b);\n\n      // red channel\n      assert.strictEqual(0, stats.channels[0].min);\n      assert.strictEqual(255, stats.channels[0].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].sum, 1391368230));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].squaresSum, 354798898650));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].mean, 238.8259925648822));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].stdev, 62.15121915523771));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 2809));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 2074));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 2809));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 2074));\n      done();\n    });\n  });\n\n  it('PNG with transparency', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency).stats((err, stats) => {\n      if (err) throw err;\n\n      assert.strictEqual(false, stats.isOpaque);\n      assert.strictEqual(true, isInAcceptableRange(stats.entropy, 0.06778064835816622));\n      assert.strictEqual(true, isInAcceptableRange(stats.sharpness, 2.522916068931278));\n\n      const { r, g, b } = stats.dominant;\n      assert.strictEqual(248, r);\n      assert.strictEqual(248, g);\n      assert.strictEqual(248, b);\n\n      // red channel\n      assert.strictEqual(0, stats.channels[0].min);\n      assert.strictEqual(255, stats.channels[0].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].sum, 795678795));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].squaresSum, 202898092725));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].mean, 252.9394769668579));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].stdev, 22.829537532816));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 2048));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 1536));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 2048));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 1536));\n\n      // green channel\n      assert.strictEqual(0, stats.channels[1].min);\n      assert.strictEqual(255, stats.channels[1].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].sum, 795678795));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].squaresSum, 202898092725));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].mean, 252.9394769668579));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].stdev, 22.829537532816));\n      assert.strictEqual(true, isInteger(stats.channels[1].minX));\n      assert.strictEqual(true, isInRange(stats.channels[1].minX, 0, 2048));\n      assert.strictEqual(true, isInteger(stats.channels[1].minY));\n      assert.strictEqual(true, isInRange(stats.channels[1].minY, 0, 1536));\n      assert.strictEqual(true, isInteger(stats.channels[1].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[1].maxX, 0, 2048));\n      assert.strictEqual(true, isInteger(stats.channels[1].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[1].maxY, 0, 1536));\n\n      // blue channel\n      assert.strictEqual(0, stats.channels[2].min);\n      assert.strictEqual(255, stats.channels[2].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].sum, 795678795));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].squaresSum, 202898092725));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].mean, 252.9394769668579));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].stdev, 22.829537532816));\n      assert.strictEqual(true, isInteger(stats.channels[2].minX));\n      assert.strictEqual(true, isInRange(stats.channels[2].minX, 0, 2048));\n      assert.strictEqual(true, isInteger(stats.channels[2].minY));\n      assert.strictEqual(true, isInRange(stats.channels[2].minY, 0, 1536));\n      assert.strictEqual(true, isInteger(stats.channels[2].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[2].maxX, 0, 2048));\n      assert.strictEqual(true, isInteger(stats.channels[2].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[2].maxY, 0, 1536));\n\n      // alpha channel\n      assert.strictEqual(0, stats.channels[3].min);\n      assert.strictEqual(255, stats.channels[3].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[3].sum, 5549142));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[3].squaresSum, 1333571132));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[3].mean, 1.7640247344970703));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[3].stdev, 20.51387814157297));\n      assert.strictEqual(true, isInteger(stats.channels[3].minX));\n      assert.strictEqual(true, isInRange(stats.channels[3].minX, 0, 2048));\n      assert.strictEqual(true, isInteger(stats.channels[3].minY));\n      assert.strictEqual(true, isInRange(stats.channels[3].minY, 0, 1536));\n      assert.strictEqual(true, isInteger(stats.channels[3].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[3].maxX, 0, 2048));\n      assert.strictEqual(true, isInteger(stats.channels[3].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[3].maxY, 0, 1536));\n\n      done();\n    });\n  });\n\n  it('PNG fully transparent', (_t, done) => {\n    sharp(fixtures.inputPngCompleteTransparency).stats((err, stats) => {\n      if (err) throw err;\n\n      assert.strictEqual(false, stats.isOpaque);\n      assert.strictEqual(true, isInAcceptableRange(stats.entropy, 0));\n      assert.strictEqual(true, isInAcceptableRange(stats.sharpness, 0));\n\n      const { r, g, b } = stats.dominant;\n      assert.strictEqual(72, r);\n      assert.strictEqual(104, g);\n      assert.strictEqual(72, b);\n\n      // alpha channel\n      assert.strictEqual(0, stats.channels[3].min);\n      assert.strictEqual(0, stats.channels[3].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[3].sum, 0));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[3].squaresSum, 0));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[3].mean, 0));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[3].stdev, 0));\n      assert.strictEqual(true, isInteger(stats.channels[3].minX));\n      assert.strictEqual(true, isInRange(stats.channels[3].minX, 0, 300));\n      assert.strictEqual(true, isInteger(stats.channels[3].minY));\n      assert.strictEqual(true, isInRange(stats.channels[3].minY, 0, 300));\n      assert.strictEqual(true, isInteger(stats.channels[3].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[3].maxX, 0, 300));\n      assert.strictEqual(true, isInteger(stats.channels[3].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[3].maxY, 0, 300));\n\n      done();\n    });\n  });\n\n  it('Tiff', (_t, done) => {\n    sharp(fixtures.inputTiff).stats((err, stats) => {\n      if (err) throw err;\n\n      assert.strictEqual(true, stats.isOpaque);\n      assert.strictEqual(true, isInAcceptableRange(stats.entropy, 0.3851250782608986));\n      assert.strictEqual(true, isInAcceptableRange(stats.sharpness, 10.312521863719589));\n\n      const { r, g, b } = stats.dominant;\n      assert.strictEqual(248, r);\n      assert.strictEqual(248, g);\n      assert.strictEqual(248, b);\n\n      // red channel\n      assert.strictEqual(0, stats.channels[0].min);\n      assert.strictEqual(255, stats.channels[0].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].sum, 1887266220));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].squaresSum, 481252886100));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].mean, 235.81772349417824));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].stdev, 67.25712856093298));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 2464));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 3248));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 2464));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 3248));\n\n      done();\n    });\n  });\n\n  it('WebP', (_t, done) => {\n    sharp(fixtures.inputWebP).stats((err, stats) => {\n      if (err) throw err;\n\n      assert.strictEqual(true, stats.isOpaque);\n      assert.strictEqual(true, isInAcceptableRange(stats.entropy, 7.51758075132966));\n      assert.strictEqual(true, isInAcceptableRange(stats.sharpness, 9.971384105278734));\n\n      const { r, g, b } = stats.dominant;\n      assert.strictEqual(40, r);\n      assert.strictEqual(136, g);\n      assert.strictEqual(200, b);\n\n      // red channel\n      assert.strictEqual(0, stats.channels[0].min);\n      assert.strictEqual(true, isInRange(stats.channels[0].max, 254, 255));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].sum, 83291370));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].squaresSum, 11379783198));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].mean, 105.36169496842616));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].stdev, 57.39412151419967));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 1024));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 772));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 1024));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 772));\n\n      // green channel\n      assert.strictEqual(0, stats.channels[1].min);\n      assert.strictEqual(true, isInRange(stats.channels[1].max, 254, 255));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].sum, 120877425));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].squaresSum, 20774687595));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].mean, 152.9072025279307));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].stdev, 53.84143349689916));\n      assert.strictEqual(true, isInteger(stats.channels[1].minX));\n      assert.strictEqual(true, isInRange(stats.channels[1].minX, 0, 1024));\n      assert.strictEqual(true, isInteger(stats.channels[1].minY));\n      assert.strictEqual(true, isInRange(stats.channels[1].minY, 0, 772));\n      assert.strictEqual(true, isInteger(stats.channels[1].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[1].maxX, 0, 1024));\n      assert.strictEqual(true, isInteger(stats.channels[1].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[1].maxY, 0, 772));\n\n      // blue channel\n      assert.strictEqual(0, stats.channels[2].min);\n      assert.strictEqual(true, isInRange(stats.channels[2].max, 254, 255));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].sum, 138938859));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].squaresSum, 28449125593));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].mean, 175.75450711423252));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].stdev, 71.39929031070358));\n      assert.strictEqual(true, isInteger(stats.channels[2].minX));\n      assert.strictEqual(true, isInRange(stats.channels[2].minX, 0, 1024));\n      assert.strictEqual(true, isInteger(stats.channels[2].minY));\n      assert.strictEqual(true, isInRange(stats.channels[2].minY, 0, 772));\n      assert.strictEqual(true, isInteger(stats.channels[2].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[2].maxX, 0, 1024));\n      assert.strictEqual(true, isInteger(stats.channels[2].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[2].maxY, 0, 772));\n\n      done();\n    });\n  });\n\n  it('GIF', (_t, done) => {\n    sharp(fixtures.inputGif).stats((err, stats) => {\n      if (err) throw err;\n\n      assert.strictEqual(true, stats.isOpaque);\n      assert.strictEqual(true, isInAcceptableRange(stats.entropy, 6.08118048729375));\n      assert.strictEqual(true, isInAcceptableRange(stats.sharpness, 2.936767879098001));\n\n      const { r, g, b } = stats.dominant;\n      assert.strictEqual(120, r);\n      assert.strictEqual(136, g);\n      assert.strictEqual(88, b);\n\n      // red channel\n      assert.strictEqual(35, stats.channels[0].min);\n      assert.strictEqual(254, stats.channels[0].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].sum, 56088385));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].squaresSum, 8002132113));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].mean, 131.53936444652908));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].stdev, 38.26389131415863));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 800));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 533));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 800));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 533));\n\n      // green channel\n      assert.strictEqual(43, stats.channels[1].min);\n      assert.strictEqual(255, stats.channels[1].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].sum, 58612156));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].squaresSum, 8548344254));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].mean, 137.45815196998123));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].stdev, 33.955424103758205));\n      assert.strictEqual(true, isInteger(stats.channels[1].minX));\n      assert.strictEqual(true, isInRange(stats.channels[1].minX, 0, 800));\n      assert.strictEqual(true, isInteger(stats.channels[1].minY));\n      assert.strictEqual(true, isInRange(stats.channels[1].minY, 0, 533));\n      assert.strictEqual(true, isInteger(stats.channels[1].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[1].maxX, 0, 800));\n      assert.strictEqual(true, isInteger(stats.channels[1].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[1].maxY, 0, 533));\n\n      // blue channel\n      assert.strictEqual(51, stats.channels[2].min);\n      assert.strictEqual(254, stats.channels[2].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].sum, 49628525));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].squaresSum, 6450556071));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].mean, 116.38959896810506));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].stdev, 39.7669551046809));\n      assert.strictEqual(true, isInteger(stats.channels[2].minX));\n      assert.strictEqual(true, isInRange(stats.channels[2].minX, 0, 800));\n      assert.strictEqual(true, isInteger(stats.channels[2].minY));\n      assert.strictEqual(true, isInRange(stats.channels[2].minY, 0, 533));\n      assert.strictEqual(true, isInteger(stats.channels[2].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[2].maxX, 0, 800));\n      assert.strictEqual(true, isInteger(stats.channels[2].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[2].maxY, 0, 533));\n\n      done();\n    });\n  });\n\n  it('Grayscale GIF with alpha', (_t, done) => {\n    sharp(fixtures.inputGifGreyPlusAlpha).stats((err, stats) => {\n      if (err) throw err;\n\n      assert.strictEqual(false, stats.isOpaque);\n      assert.strictEqual(true, isInAcceptableRange(stats.entropy, 1));\n      assert.strictEqual(true, isInAcceptableRange(stats.sharpness, 15.870619016486861));\n\n      const { r, g, b } = stats.dominant;\n      assert.strictEqual(8, r);\n      assert.strictEqual(8, g);\n      assert.strictEqual(8, b);\n\n      // gray channel\n      assert.strictEqual(0, stats.channels[0].min);\n      assert.strictEqual(101, stats.channels[0].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].sum, 101));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].squaresSum, 10201));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].mean, 50.5));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].stdev, 71.4177848998413));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 2));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 1));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 2));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 1));\n\n      // alpha channel\n      assert.strictEqual(0, stats.channels[3].min);\n      assert.strictEqual(255, stats.channels[3].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[3].sum, 255));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[3].squaresSum, 65025));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[3].mean, 127.5));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[3].stdev, 180.31222920256963));\n      assert.strictEqual(true, isInteger(stats.channels[3].minX));\n      assert.strictEqual(true, isInRange(stats.channels[3].minX, 0, 2));\n      assert.strictEqual(true, isInteger(stats.channels[3].minY));\n      assert.strictEqual(true, isInRange(stats.channels[3].minY, 0, 1));\n      assert.strictEqual(true, isInteger(stats.channels[3].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[3].maxX, 0, 2));\n      assert.strictEqual(true, isInteger(stats.channels[3].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[3].maxY, 0, 1));\n\n      done();\n    });\n  });\n\n  it('CMYK input without profile', () =>\n    sharp(fixtures.inputJpgWithCmykNoProfile)\n      .stats()\n      .then(stats => {\n        assert.strictEqual(4, stats.channels.length);\n        assert.strictEqual(true, stats.isOpaque);\n      })\n  );\n\n  it('Dominant colour', () =>\n    sharp(fixtures.inputJpgBooleanTest)\n      .stats()\n      .then(({ dominant }) => {\n        const { r, g, b } = dominant;\n        assert.strictEqual(r, 8);\n        assert.strictEqual(g, 136);\n        assert.strictEqual(b, 248);\n      })\n  );\n\n  it('Entropy and sharpness of 1x1 input are zero', async () => {\n    const { entropy, sharpness } = await sharp({\n      create: {\n        width: 1,\n        height: 1,\n        channels: 3,\n        background: 'red'\n      }\n    }).stats();\n    assert.strictEqual(entropy, 0);\n    assert.strictEqual(sharpness, 0);\n  });\n\n  it('Stream in, Callback out', (_t, done) => {\n    const readable = fs.createReadStream(fixtures.inputJpg);\n    const pipeline = sharp().stats((err, stats) => {\n      if (err) throw err;\n\n      assert.strictEqual(true, stats.isOpaque);\n      assert.strictEqual(true, isInAcceptableRange(stats.entropy, 7.332915340666659));\n      assert.strictEqual(true, isInAcceptableRange(stats.sharpness, 0.788301114707569));\n\n      const { r, g, b } = stats.dominant;\n      assert.strictEqual(40, r);\n      assert.strictEqual(40, g);\n      assert.strictEqual(40, b);\n\n      // red channel\n      assert.strictEqual(0, stats.channels[0].min);\n      assert.strictEqual(255, stats.channels[0].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].sum, 615101275));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].squaresSum, 83061892917));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].mean, 101.44954540768993));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].stdev, 58.373870588815414));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 2725));\n\n      // green channel\n      assert.strictEqual(0, stats.channels[1].min);\n      assert.strictEqual(255, stats.channels[1].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].sum, 462824115));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].squaresSum, 47083677255));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].mean, 76.33425255128337));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].stdev, 44.03023262954866));\n      assert.strictEqual(true, isInteger(stats.channels[1].minX));\n      assert.strictEqual(true, isInRange(stats.channels[1].minX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[1].minY));\n      assert.strictEqual(true, isInRange(stats.channels[1].minY, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[1].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[1].maxX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[1].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[1].maxY, 0, 2725));\n\n      // blue channel\n      assert.strictEqual(0, stats.channels[2].min);\n      assert.strictEqual(255, stats.channels[2].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].sum, 372986756));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].squaresSum, 32151543524));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].mean, 61.51724663436759));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].stdev, 38.96702865090125));\n      assert.strictEqual(true, isInteger(stats.channels[2].minX));\n      assert.strictEqual(true, isInRange(stats.channels[2].minX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[2].minY));\n      assert.strictEqual(true, isInRange(stats.channels[2].minY, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[2].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[2].maxX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[2].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[2].maxY, 0, 2725));\n\n      done();\n    });\n    readable.pipe(pipeline);\n  });\n\n  it('Stream in, Promise out', () => {\n    const pipeline = sharp();\n\n    fs.createReadStream(fixtures.inputJpg).pipe(pipeline);\n\n    return pipeline.stats().then((stats) => {\n      assert.strictEqual(true, stats.isOpaque);\n      assert.strictEqual(true, isInAcceptableRange(stats.entropy, 7.332915340666659));\n      assert.strictEqual(true, isInAcceptableRange(stats.sharpness, 0.788301114707569));\n\n      const { r, g, b } = stats.dominant;\n      assert.strictEqual(40, r);\n      assert.strictEqual(40, g);\n      assert.strictEqual(40, b);\n\n      // red channel\n      assert.strictEqual(0, stats.channels[0].min);\n      assert.strictEqual(255, stats.channels[0].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].sum, 615101275));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].squaresSum, 83061892917));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].mean, 101.44954540768993));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].stdev, 58.373870588815414));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 2725));\n\n      // green channel\n      assert.strictEqual(0, stats.channels[1].min);\n      assert.strictEqual(255, stats.channels[1].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].sum, 462824115));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].squaresSum, 47083677255));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].mean, 76.33425255128337));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].stdev, 44.03023262954866));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 2725));\n\n      // blue channel\n      assert.strictEqual(0, stats.channels[2].min);\n      assert.strictEqual(255, stats.channels[2].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].sum, 372986756));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].squaresSum, 32151543524));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].mean, 61.51724663436759));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].stdev, 38.96702865090125));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 2725));\n    }).catch((err) => {\n      throw err;\n    });\n  });\n\n  it('File in, Promise out', () => sharp(fixtures.inputJpg).stats().then((stats) => {\n      assert.strictEqual(true, stats.isOpaque);\n      assert.strictEqual(true, isInAcceptableRange(stats.entropy, 7.332915340666659));\n      assert.strictEqual(true, isInAcceptableRange(stats.sharpness, 0.788301114707569));\n\n      const { r, g, b } = stats.dominant;\n      assert.strictEqual(40, r);\n      assert.strictEqual(40, g);\n      assert.strictEqual(40, b);\n\n      // red channel\n      assert.strictEqual(0, stats.channels[0].min);\n      assert.strictEqual(255, stats.channels[0].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].sum, 615101275));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].squaresSum, 83061892917));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].mean, 101.44954540768993));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[0].stdev, 58.373870588815414));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 2725));\n\n      // green channel\n      assert.strictEqual(0, stats.channels[1].min);\n      assert.strictEqual(255, stats.channels[1].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].sum, 462824115));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].squaresSum, 47083677255));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].mean, 76.33425255128337));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[1].stdev, 44.03023262954866));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 2725));\n\n      // blue channel\n      assert.strictEqual(0, stats.channels[2].min);\n      assert.strictEqual(255, stats.channels[2].max);\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].sum, 372986756));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].squaresSum, 32151543524));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].mean, 61.51724663436759));\n      assert.strictEqual(true, isInAcceptableRange(stats.channels[2].stdev, 38.96702865090125));\n      assert.strictEqual(true, isInteger(stats.channels[0].minX));\n      assert.strictEqual(true, isInRange(stats.channels[0].minX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].minY));\n      assert.strictEqual(true, isInRange(stats.channels[0].minY, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxX));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxX, 0, 2725));\n      assert.strictEqual(true, isInteger(stats.channels[0].maxY));\n      assert.strictEqual(true, isInRange(stats.channels[0].maxY, 0, 2725));\n    }).catch((err) => {\n      throw err;\n    }));\n\n  it('Blurred image has lower sharpness than original', () => {\n    const original = sharp(fixtures.inputJpg).stats();\n    const blurred = sharp(fixtures.inputJpg).blur().toBuffer().then(blur => sharp(blur).stats());\n\n    return Promise\n      .all([original, blurred])\n      .then(([original, blurred]) => {\n        assert.strictEqual(true, isInAcceptableRange(original.sharpness, 0.789046400439488));\n        assert.strictEqual(true, isInAcceptableRange(blurred.sharpness, 0.47985138441709047));\n      });\n  });\n\n  it('File input with corrupt header fails gracefully', (_t, done) => {\n    sharp(fixtures.inputJpgWithCorruptHeader)\n      .stats((err) => {\n        assert(err.message.includes('Input file has corrupt header'));\n        assert(err.stack.includes('at Sharp.stats'));\n        assert(err.stack.includes(__filename));\n        done();\n      });\n  });\n\n  it('Stream input with corrupt header fails gracefully', (_t, done) => {\n    fs.createReadStream(fixtures.inputJpgWithCorruptHeader).pipe(\n      sharp()\n        .stats((err) => {\n          assert(err.message.includes('Input buffer has corrupt header'));\n          assert(err.stack.includes('at Sharp.stats'));\n          assert(err.stack.includes(__filename));\n          done();\n        })\n    );\n  });\n\n  it('File input with corrupt header fails gracefully, Promise out', () => sharp(fixtures.inputJpgWithCorruptHeader)\n      .stats().then(() => {\n        throw new Error('Corrupt Header file');\n      }).catch((err) => {\n        assert.ok(!!err);\n      }));\n\n  it('File input with corrupt header fails gracefully, Stream In, Promise Out', () => {\n    const pipeline = sharp();\n\n    fs.createReadStream(fixtures.inputJpgWithCorruptHeader).pipe(pipeline);\n\n    return pipeline\n      .stats().then(() => {\n        throw new Error('Corrupt Header file');\n      }).catch((err) => {\n        assert.ok(!!err);\n      });\n  });\n\n  it('Buffer input with corrupt header fails gracefully', (_t, done) => {\n    sharp(fs.readFileSync(fixtures.inputJpgWithCorruptHeader))\n      .stats((err) => {\n        assert.strictEqual(true, !!err);\n        done();\n      });\n  });\n\n  it('Non-existent file in, Promise out', (_t, done) => {\n    sharp('fail').stats().then(() => {\n      throw new Error('Non-existent file');\n    }, (err) => {\n      assert.ok(!!err);\n      done();\n    });\n  });\n\n  it('Sequential read option is ignored', async () => {\n    const { isOpaque } = await sharp(fixtures.inputJpg, { sequentialRead: true }).stats();\n    assert.strictEqual(isOpaque, true);\n  });\n});\n"
  },
  {
    "path": "test/unit/svg.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('SVG input', () => {\n  it('Convert SVG to PNG at default 72DPI', (_t, done) => {\n    sharp(fixtures.inputSvg)\n      .resize(1024)\n      .extract({ left: 290, top: 760, width: 40, height: 40 })\n      .toFormat('png')\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(40, info.width);\n        assert.strictEqual(40, info.height);\n        fixtures.assertSimilar(fixtures.expected('svg72.png'), data, (err) => {\n          if (err) throw err;\n          sharp(data).metadata((err, info) => {\n            if (err) throw err;\n            assert.strictEqual(72, info.density);\n            done();\n          });\n        });\n      });\n  });\n\n  it('Convert SVG to PNG at 1200DPI', (_t, done) => {\n    sharp(fixtures.inputSvg, { density: 1200 })\n      .resize(1024)\n      .extract({ left: 290, top: 760, width: 40, height: 40 })\n      .toFormat('png')\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(40, info.width);\n        assert.strictEqual(40, info.height);\n        fixtures.assertSimilar(fixtures.expected('svg1200.png'), data, (err) => {\n          if (err) throw err;\n          sharp(data).metadata((err, info) => {\n            if (err) throw err;\n            assert.strictEqual(1200, info.density);\n            done();\n          });\n        });\n      });\n  });\n\n  it('Convert SVG to PNG at DPI larger than 2400', (_t, done) => {\n    const size = 1024;\n    sharp(fixtures.inputSvgSmallViewBox).metadata((err, metadata) => {\n      if (err) throw err;\n      const density = (size / Math.max(metadata.width, metadata.height)) * metadata.density;\n      sharp(fixtures.inputSvgSmallViewBox, { density })\n        .resize(size)\n        .toFormat('png')\n        .toBuffer((err, data, info) => {\n          if (err) throw err;\n          assert.strictEqual('png', info.format);\n          assert.strictEqual(size, info.width);\n          assert.strictEqual(size, info.height);\n          fixtures.assertSimilar(fixtures.expected('circle.png'), data, (err) => {\n            if (err) throw err;\n            sharp(data).metadata((err, info) => {\n              if (err) throw err;\n              assert.strictEqual(9216, info.density);\n              done();\n            });\n          });\n        });\n    });\n  });\n\n  it('Convert SVG to PNG utilizing scale-on-load', (_t, done) => {\n    const size = 1024;\n    sharp(fixtures.inputSvgSmallViewBox)\n      .resize(size)\n      .toFormat('png')\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(size, info.width);\n        assert.strictEqual(size, info.height);\n        fixtures.assertSimilar(fixtures.expected('circle.png'), data, (err) => {\n          if (err) throw err;\n          sharp(data).metadata((err, info) => {\n            if (err) throw err;\n            assert.strictEqual(72, info.density);\n            done();\n          });\n        });\n      });\n  });\n\n  it('Convert SVG to PNG at 14.4DPI', (_t, done) => {\n    sharp(fixtures.inputSvg, { density: 14.4 })\n      .toFormat('png')\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(20, info.width);\n        assert.strictEqual(20, info.height);\n        fixtures.assertSimilar(fixtures.expected('svg14.4.png'), data, (err) => {\n          if (err) throw err;\n          done();\n        });\n      });\n  });\n\n  it('Convert SVG with embedded images to PNG, respecting dimensions, autoconvert to PNG', (_t, done) => {\n    sharp(fixtures.inputSvgWithEmbeddedImages)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(480, info.width);\n        assert.strictEqual(360, info.height);\n        assert.strictEqual(4, info.channels);\n        fixtures.assertSimilar(fixtures.expected('svg-embedded.png'), data, done);\n      });\n  });\n\n  it('Converts SVG with truncated embedded PNG', async () => {\n    const truncatedPng = fs.readFileSync(fixtures.inputPngTruncated).toString('base64');\n    const svg = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n      <svg width=\"294\" height=\"240\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n        <image width=\"294\" height=\"240\" xlink:href=\"data:image/png;base64,${truncatedPng}\"/>\n      </svg>`;\n\n    const { info } = await sharp(Buffer.from(svg)).toBuffer({ resolveWithObject: true });\n    assert.strictEqual(info.format, 'png');\n    assert.strictEqual(info.width, 294);\n    assert.strictEqual(info.height, 240);\n    assert.strictEqual(info.channels, 4);\n  });\n\n  it('Can apply custom CSS', async () => {\n    const svg = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n      <svg  width=\"10\" height=\"10\" xmlns=\"http://www.w3.org/2000/svg\">\n        <circle cx=\"5\" cy=\"5\" r=\"4\" fill=\"green\" />\n      </svg>`;\n    const stylesheet = 'circle { fill: red }';\n\n    const [r, g, b, a] = await sharp(Buffer.from(svg), { svg: { stylesheet } })\n      .extract({ left: 5, top: 5, width: 1, height: 1 })\n      .raw()\n      .toBuffer();\n\n    assert.deepEqual([r, g, b, a], [255, 0, 0, 255]);\n  });\n\n  it('Invalid stylesheet input option throws', () =>\n    assert.throws(\n      () => sharp({ svg: { stylesheet: 123 } }),\n      /Expected string for svg\\.stylesheet but received 123 of type number/\n    )\n  );\n\n  it('Valid highBitdepth input option does not throw', () =>\n    assert.doesNotThrow(\n      () => sharp({ svg: { highBitdepth: true } })\n    )\n  );\n\n  it('Invalid highBitdepth input option throws', () =>\n    assert.throws(\n      () => sharp({ svg: { highBitdepth: 123 } }),\n      /Expected boolean for svg\\.highBitdepth but received 123 of type number/\n    )\n  );\n\n  it('Fails to render SVG larger than 32767x32767', () =>\n    assert.rejects(\n      () => sharp(Buffer.from('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32768\" height=\"1\" />')).toBuffer(),\n      /Input SVG image exceeds 32767x32767 pixel limit/\n    )\n  );\n\n  it('Fails to render scaled SVG larger than 32767x32767', () =>\n    assert.rejects(\n      () => sharp(Buffer.from('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32767\" height=\"1\" />')).resize(32768).toBuffer(),\n      /Input SVG image will exceed 32767x32767 pixel limit when scaled/\n    )\n  );\n\n  it('Detects SVG passed as a string', () =>\n    assert.rejects(\n      () => sharp('<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>').toBuffer(),\n      /Input file is missing, did you mean/\n    )\n  );\n});\n"
  },
  {
    "path": "test/unit/text.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\nconst { inRange } = require('../../lib/is');\n\ndescribe('Text to image', () => {\n  it('text with default values', async (t) => {\n    const output = fixtures.path('output.text-default.png');\n    const text = sharp({\n      text: {\n        text: 'Hello, world !'\n      }\n    });\n    if (!sharp.versions.pango) {\n      return t.skip();\n    }\n    const info = await text.png().toFile(output);\n    assert.strictEqual('png', info.format);\n    assert.strictEqual(3, info.channels);\n    assert.strictEqual(false, info.premultiplied);\n    assert.ok(info.width > 10);\n    assert.ok(info.height > 8);\n    const metadata = await sharp(output).metadata();\n    assert.strictEqual('uchar', metadata.depth);\n    assert.strictEqual('srgb', metadata.space);\n    assert.strictEqual(72, metadata.density);\n    const stats = await sharp(output).stats();\n    assert.strictEqual(0, stats.channels[0].min);\n    assert.strictEqual(255, stats.channels[0].max);\n    assert.strictEqual(0, stats.channels[1].min);\n    assert.strictEqual(255, stats.channels[1].max);\n    assert.strictEqual(0, stats.channels[2].min);\n    assert.strictEqual(255, stats.channels[2].max);\n    assert.ok(info.textAutofitDpi > 0);\n  });\n\n  it('text with width and height', async (t) => {\n    const output = fixtures.path('output.text-width-height.png');\n    const text = sharp({\n      text: {\n        text: 'Hello, world!',\n        width: 500,\n        height: 400\n      }\n    });\n    if (!sharp.versions.pango) {\n      return t.skip();\n    }\n    const info = await text.toFile(output);\n    assert.strictEqual('png', info.format);\n    assert.strictEqual(3, info.channels);\n    assert.ok(inRange(info.width, 400, 600), `Actual width ${info.width}`);\n    assert.ok(inRange(info.height, 290, 500), `Actual height ${info.height}`);\n    assert.ok(inRange(info.textAutofitDpi, 900, 1300), `Actual textAutofitDpi ${info.textAutofitDpi}`);\n  });\n\n  it('text with dpi', async (t) => {\n    const output = fixtures.path('output.text-dpi.png');\n    const dpi = 300;\n    const text = sharp({\n      text: {\n        text: 'Hello, world!',\n        dpi\n      }\n    });\n    if (!sharp.versions.pango) {\n      return t.skip();\n    }\n    const info = await text.toFile(output);\n    assert.strictEqual('png', info.format);\n    const metadata = await sharp(output).metadata();\n    assert.strictEqual(dpi, metadata.density);\n  });\n\n  it('text with color and pango markup', async (t) => {\n    const output = fixtures.path('output.text-color-pango.png');\n    const dpi = 300;\n    const text = sharp({\n      text: {\n        text: '<span foreground=\"red\" font=\"100\">red</span><span font=\"50\" background=\"cyan\">blue</span>',\n        rgba: true,\n        dpi\n      }\n    });\n    if (!sharp.versions.pango) {\n      return t.skip();\n    }\n    const info = await text.toFile(output);\n    assert.strictEqual('png', info.format);\n    assert.strictEqual(4, info.channels);\n    const metadata = await sharp(output).metadata();\n    assert.strictEqual(dpi, metadata.density);\n    assert.strictEqual('uchar', metadata.depth);\n    assert.strictEqual(true, metadata.hasAlpha);\n  });\n\n  it('text with font', async (t) => {\n    const output = fixtures.path('output.text-with-font.png');\n    const text = sharp({\n      text: {\n        text: 'Hello, world!',\n        font: 'sans 100'\n      }\n    });\n    if (!sharp.versions.pango) {\n      return t.skip();\n    }\n    const info = await text.toFile(output);\n    assert.strictEqual('png', info.format);\n    assert.strictEqual(3, info.channels);\n    assert.ok(info.width > 30);\n    assert.ok(info.height > 10);\n  });\n\n  it('text with justify and composite', async (t) => {\n    const output = fixtures.path('output.text-composite.png');\n    const width = 500;\n    const dpi = 300;\n    const text = sharp(fixtures.inputJpg)\n      .resize(width)\n      .composite([{\n        input: {\n          text: {\n            text: '<span foreground=\"#ffff00\">Watermark</span> <span foreground=\"white\"><i>is cool</i></span>',\n            width: 300,\n            height: 300,\n            justify: true,\n            align: 'right',\n            spacing: 50,\n            rgba: true\n          }\n        },\n        gravity: 'northeast'\n      }, {\n        input: {\n          text: {\n            text: '<span background=\"cyan\">cool</span>',\n            font: 'sans 30',\n            dpi,\n            rgba: true\n          }\n        },\n        left: 30,\n        top: 250\n      }]);\n    if (!sharp.versions.pango) {\n      return t.skip();\n    }\n    const info = await text.toFile(output);\n    assert.strictEqual('png', info.format);\n    assert.strictEqual(4, info.channels);\n    assert.strictEqual(width, info.width);\n    assert.strictEqual(true, info.premultiplied);\n    const metadata = await sharp(output).metadata();\n    assert.strictEqual('srgb', metadata.space);\n    assert.strictEqual('uchar', metadata.depth);\n    assert.strictEqual(true, metadata.hasAlpha);\n  });\n\n  it('bad text input', () => {\n    assert.throws(() => {\n      sharp({\n        text: {\n        }\n      });\n    });\n  });\n\n  it('fontfile input', () => {\n    assert.doesNotThrow(() => {\n      sharp({\n        text: {\n          text: 'text',\n          fontfile: 'UnknownFont.ttf'\n        }\n      });\n    });\n  });\n\n  it('bad font input', () => {\n    assert.throws(() => {\n      sharp({\n        text: {\n          text: 'text',\n          font: 12\n        }\n      });\n    });\n  });\n\n  it('bad fontfile input', () => {\n    assert.throws(() => {\n      sharp({\n        text: {\n          text: 'text',\n          fontfile: true\n        }\n      });\n    });\n  });\n\n  it('invalid width', () => {\n    assert.throws(\n      () => sharp({ text: { text: 'text', width: 'bad' } }),\n      /Expected positive integer for text\\.width but received bad of type string/\n    );\n    assert.throws(\n      () => sharp({ text: { text: 'text', width: 0.1 } }),\n      /Expected positive integer for text\\.width but received 0.1 of type number/\n    );\n    assert.throws(\n      () => sharp({ text: { text: 'text', width: -1 } }),\n      /Expected positive integer for text\\.width but received -1 of type number/\n    );\n  });\n\n  it('invalid height', () => {\n    assert.throws(\n      () => sharp({ text: { text: 'text', height: 'bad' } }),\n      /Expected positive integer for text\\.height but received bad of type string/\n    );\n    assert.throws(\n      () => sharp({ text: { text: 'text', height: 0.1 } }),\n      /Expected positive integer for text\\.height but received 0.1 of type number/\n    );\n    assert.throws(\n      () => sharp({ text: { text: 'text', height: -1 } }),\n      /Expected positive integer for text\\.height but received -1 of type number/\n    );\n  });\n\n  it('bad align input', () => {\n    assert.throws(() => {\n      sharp({\n        text: {\n          text: 'text',\n          align: 'unknown'\n        }\n      });\n    });\n  });\n\n  it('bad justify input', () => {\n    assert.throws(() => {\n      sharp({\n        text: {\n          text: 'text',\n          justify: 'unknown'\n        }\n      });\n    });\n  });\n\n  it('invalid dpi', () => {\n    assert.throws(\n      () => sharp({ text: { text: 'text', dpi: 'bad' } }),\n      /Expected integer between 1 and 1000000 for text\\.dpi but received bad of type string/\n    );\n    assert.throws(\n      () => sharp({ text: { text: 'text', dpi: 0.1 } }),\n      /Expected integer between 1 and 1000000 for text\\.dpi but received 0.1 of type number/\n    );\n    assert.throws(\n      () => sharp({ text: { text: 'text', dpi: -1 } }),\n      /Expected integer between 1 and 1000000 for text\\.dpi but received -1 of type number/\n    );\n  });\n\n  it('bad rgba input', () => {\n    assert.throws(() => {\n      sharp({\n        text: {\n          text: 'text',\n          rgba: -10\n        }\n      });\n    });\n  });\n\n  it('invalid spacing', () => {\n    assert.throws(\n      () => sharp({ text: { text: 'text', spacing: 'bad' } }),\n      /Expected integer between -1000000 and 1000000 for text\\.spacing but received bad of type string/\n    );\n    assert.throws(\n      () => sharp({ text: { text: 'text', spacing: 0.1 } }),\n      /Expected integer between -1000000 and 1000000 for text\\.spacing but received 0.1 of type number/\n    );\n    assert.throws(\n      () => sharp({ text: { text: 'text', spacing: -1000001 } }),\n      /Expected integer between -1000000 and 1000000 for text\\.spacing but received -1000001 of type number/\n    );\n  });\n\n  it('only height or dpi not both', () => {\n    assert.throws(() => {\n      sharp({\n        text: {\n          text: 'text',\n          height: 400,\n          dpi: 100\n        }\n      });\n    });\n  });\n\n  it('valid wrap throws', () => {\n    assert.doesNotThrow(() => sharp({ text: { text: 'text', wrap: 'none' } }));\n    assert.doesNotThrow(() => sharp({ text: { text: 'text', wrap: 'word-char' } }));\n  });\n\n  it('invalid wrap throws', () => {\n    assert.throws(\n      () => sharp({ text: { text: 'text', wrap: 1 } }),\n      /Expected one of: word, char, word-char, none for text\\.wrap but received 1 of type number/\n    );\n    assert.throws(\n      () => sharp({ text: { text: 'text', wrap: false } }),\n      /Expected one of: word, char, word-char, none for text\\.wrap but received false of type boolean/\n    );\n    assert.throws(\n      () => sharp({ text: { text: 'text', wrap: 'invalid' } }),\n      /Expected one of: word, char, word-char, none for text\\.wrap but received invalid of type string/\n    );\n  });\n});\n"
  },
  {
    "path": "test/unit/threshold.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Threshold', () => {\n  it('threshold 1 jpeg', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .threshold(1)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('threshold-1.jpg'), data, done);\n      });\n  });\n\n  it('threshold 40 jpeg', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .threshold(40)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('threshold-40.jpg'), data, done);\n      });\n  });\n\n  it('threshold 128', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .threshold(128)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('threshold-128.jpg'), data, done);\n      });\n  });\n\n  it('threshold true (=128)', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .threshold(true)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('threshold-128.jpg'), data, done);\n      });\n  });\n\n  it('threshold false (=0)', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .threshold(false)\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.inputJpg, data, done);\n      });\n  });\n\n  it('threshold grayscale: true (=128)', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .threshold(128, { grayscale: true })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('threshold-128.jpg'), data, done);\n      });\n  });\n\n  it('threshold default jpeg', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .threshold()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('threshold-128.jpg'), data, done);\n      });\n  });\n\n  it('threshold default png transparency', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency)\n      .resize(320, 240)\n      .threshold()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('threshold-128-transparency.png'), data, done);\n      });\n  });\n\n  it('threshold default png alpha', (_t, done) => {\n    sharp(fixtures.inputPngWithGreyAlpha)\n      .resize(320, 240)\n      .threshold()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('threshold-128-alpha.png'), data, done);\n      });\n  });\n\n  it('threshold default webp transparency', (_t, done) => {\n    sharp(fixtures.inputWebPWithTransparency)\n      .threshold()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('webp', info.format);\n        fixtures.assertSimilar(fixtures.expected('threshold-128-transparency.webp'), data, done);\n      });\n  });\n\n  it('color threshold', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .threshold(128, { grayscale: false })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertSimilar(fixtures.expected('threshold-color-128.jpg'), data, done);\n      });\n  });\n\n  it('invalid threshold -1', () => {\n    assert.throws(() => {\n      sharp().threshold(-1);\n    });\n  });\n\n  it('invalid threshold 256', () => {\n    assert.throws(() => {\n      sharp().threshold(256);\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/tiff.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\nconst outputTiff = fixtures.path('output.tiff');\n\ndescribe('TIFF', () => {\n  it('Load TIFF from Buffer', (_t, done) => {\n    const inputTiffBuffer = fs.readFileSync(fixtures.inputTiff);\n    sharp(inputTiffBuffer)\n      .resize(320, 240)\n      .jpeg()\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        done();\n      });\n  });\n\n  it('Load multi-page TIFF from file', (_t, done) => {\n    sharp(fixtures.inputTiffMultipage) // defaults to page 0\n      .jpeg()\n      .toBuffer((err, defaultData, defaultInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, defaultData.length > 0);\n        assert.strictEqual(defaultData.length, defaultInfo.size);\n        assert.strictEqual('jpeg', defaultInfo.format);\n\n        sharp(fixtures.inputTiffMultipage, { page: 1 }) // 50%-scale copy of page 0\n          .jpeg()\n          .toBuffer((err, scaledData, scaledInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, scaledData.length > 0);\n            assert.strictEqual(scaledData.length, scaledInfo.size);\n            assert.strictEqual('jpeg', scaledInfo.format);\n            assert.strictEqual(defaultInfo.width, scaledInfo.width * 2);\n            assert.strictEqual(defaultInfo.height, scaledInfo.height * 2);\n            done();\n          });\n      });\n  });\n\n  it('Load multi-page TIFF from Buffer', (_t, done) => {\n    const inputTiffBuffer = fs.readFileSync(fixtures.inputTiffMultipage);\n    sharp(inputTiffBuffer) // defaults to page 0\n      .jpeg()\n      .toBuffer((err, defaultData, defaultInfo) => {\n        if (err) throw err;\n        assert.strictEqual(true, defaultData.length > 0);\n        assert.strictEqual(defaultData.length, defaultInfo.size);\n        assert.strictEqual('jpeg', defaultInfo.format);\n\n        sharp(inputTiffBuffer, { page: 1 }) // 50%-scale copy of page 0\n          .jpeg()\n          .toBuffer((err, scaledData, scaledInfo) => {\n            if (err) throw err;\n            assert.strictEqual(true, scaledData.length > 0);\n            assert.strictEqual(scaledData.length, scaledInfo.size);\n            assert.strictEqual('jpeg', scaledInfo.format);\n            assert.strictEqual(defaultInfo.width, scaledInfo.width * 2);\n            assert.strictEqual(defaultInfo.height, scaledInfo.height * 2);\n            done();\n          });\n      });\n  });\n\n  it('Save TIFF to Buffer', (_t, done) => {\n    sharp(fixtures.inputTiff)\n      .resize(320, 240)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual(data.length, info.size);\n        assert.strictEqual('tiff', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        done();\n      });\n  });\n\n  it('Increasing TIFF quality increases file size', () =>\n    sharp(fixtures.inputJpgWithLandscapeExif1)\n      .resize(320, 240)\n      .tiff({ quality: 40 })\n      .toBuffer()\n      .then(tiff40 => sharp(fixtures.inputJpgWithLandscapeExif1)\n        .resize(320, 240)\n        .tiff({ quality: 90 })\n        .toBuffer()\n        .then(tiff90 =>\n          assert.strictEqual(true, tiff40.length < tiff90.length)\n        )\n      )\n  );\n\n  it('Invalid TIFF quality throws error', () => {\n    assert.throws(() => {\n      sharp().tiff({ quality: 101 });\n    });\n  });\n\n  it('Missing TIFF quality does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff();\n    });\n  });\n\n  it('Not squashing TIFF to a bit depth of 1 should not change the file size', (_t, done) => {\n    const startSize = fs.statSync(fixtures.inputTiff8BitDepth).size;\n    sharp(fixtures.inputTiff8BitDepth)\n      .toColourspace('b-w') // can only squash 1 band uchar images\n      .tiff({\n        bitdepth: 8,\n        compression: 'none',\n        predictor: 'none'\n      })\n      .toFile(outputTiff, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('tiff', info.format);\n        assert.strictEqual(startSize, info.size);\n        fs.rm(outputTiff, done);\n      });\n  });\n\n  it('Squashing TIFF to a bit depth of 1 should significantly reduce file size', (_t, done) => {\n    const startSize = fs.statSync(fixtures.inputTiff8BitDepth).size;\n    sharp(fixtures.inputTiff8BitDepth)\n      .toColourspace('b-w') // can only squash 1 band uchar images\n      .tiff({\n        bitdepth: 1,\n        compression: 'none',\n        predictor: 'none'\n      })\n      .toFile(outputTiff, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('tiff', info.format);\n        assert(info.size < (startSize / 2));\n        fs.rm(outputTiff, done);\n      });\n  });\n\n  it('Invalid TIFF bitdepth value throws error', () => {\n    assert.throws(() => {\n      sharp().tiff({ bitdepth: 3 });\n    }, /Error: Expected 1, 2, 4 or 8 for bitdepth but received 3 of type number/);\n  });\n\n  it('TIFF setting xres and yres on file', () =>\n    sharp(fixtures.inputTiff)\n      .resize(8, 8)\n      .tiff({\n        xres: 1000,\n        yres: 1000\n      })\n      .toFile(outputTiff)\n      .then(() => sharp(outputTiff)\n        .metadata()\n        .then(({ density }) => {\n          assert.strictEqual(25400, density);\n          return fs.promises.rm(outputTiff);\n        })\n      )\n  );\n\n  it('TIFF setting xres and yres on buffer', () =>\n    sharp(fixtures.inputTiff)\n      .resize(8, 8)\n      .tiff({\n        xres: 1000,\n        yres: 1000\n      })\n      .toBuffer()\n      .then(data => sharp(data)\n        .metadata()\n        .then(({ density }) => {\n          assert.strictEqual(25400, density);\n        })\n      )\n  );\n\n  it('TIFF imputes xres and yres from withMetadataDensity if not explicitly provided', async () => {\n    const data = await sharp(fixtures.inputTiff)\n      .resize(8, 8)\n      .tiff()\n      .withMetadata({ density: 600 })\n      .toBuffer();\n    const { density } = await sharp(data).metadata();\n    assert.strictEqual(600, density);\n  });\n\n  it('TIFF uses xres and yres over withMetadataDensity if explicitly provided', async () => {\n    const data = await sharp(fixtures.inputTiff)\n      .resize(8, 8)\n      .tiff({ xres: 1000, yres: 1000 })\n      .withMetadata({ density: 600 })\n      .toBuffer();\n    const { density } = await sharp(data).metadata();\n    assert.strictEqual(25400, density);\n  });\n\n  it('TIFF invalid xres value should throw an error', () => {\n    assert.throws(() => {\n      sharp().tiff({ xres: '1000.0' });\n    });\n  });\n\n  it('TIFF invalid yres value should throw an error', () => {\n    assert.throws(() => {\n      sharp().tiff({ yres: '1000.0' });\n    });\n  });\n\n  it('TIFF lzw compression with horizontal predictor shrinks test file', (_t, done) => {\n    const startSize = fs.statSync(fixtures.inputTiffUncompressed).size;\n    sharp(fixtures.inputTiffUncompressed)\n      .tiff({\n        compression: 'lzw',\n        predictor: 'horizontal'\n      })\n      .toFile(outputTiff, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('tiff', info.format);\n        assert.strictEqual(3, info.channels);\n        assert(info.size < startSize);\n        fs.rm(outputTiff, done);\n      });\n  });\n\n  it('TIFF LZW RGBA toFile', () =>\n    sharp({\n      create: {\n        width: 1,\n        height: 1,\n        channels: 4,\n        background: 'red'\n      }\n    })\n      .tiff({\n        compression: 'lzw'\n      })\n      .toFile(outputTiff)\n      .then(info => {\n        assert.strictEqual(4, info.channels);\n      })\n  );\n\n  it('TIFF LZW RGBA toBuffer', () =>\n    sharp({\n      create: {\n        width: 1,\n        height: 1,\n        channels: 4,\n        background: 'red'\n      }\n    })\n      .tiff({\n        compression: 'lzw'\n      })\n      .toBuffer({ resolveWithObject: true })\n      .then(({ info }) => {\n        assert.strictEqual(4, info.channels);\n      })\n  );\n\n  it('TIFF ccittfax4 compression shrinks b-w test file', (_t, done) => {\n    const startSize = fs.statSync(fixtures.inputTiff).size;\n    sharp(fixtures.inputTiff)\n      .toColourspace('b-w')\n      .tiff({\n        bitdepth: 1,\n        compression: 'ccittfax4'\n      })\n      .toFile(outputTiff, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('tiff', info.format);\n        assert(info.size < startSize);\n        fs.rm(outputTiff, done);\n      });\n  });\n\n  it('TIFF resolutionUnit of inch (default)', async () => {\n    const data = await sharp({ create: { width: 8, height: 8, channels: 3, background: 'red' } })\n      .tiff()\n      .toBuffer();\n    const { resolutionUnit } = await sharp(data).metadata();\n    assert.strictEqual(resolutionUnit, 'inch');\n  });\n\n  it('TIFF resolutionUnit of inch', async () => {\n    const data = await sharp({ create: { width: 8, height: 8, channels: 3, background: 'red' } })\n      .tiff({ resolutionUnit: 'inch' })\n      .toBuffer();\n    const { resolutionUnit } = await sharp(data).metadata();\n    assert.strictEqual(resolutionUnit, 'inch');\n  });\n\n  it('TIFF resolutionUnit of cm', async () => {\n    const data = await sharp({ create: { width: 8, height: 8, channels: 3, background: 'red' } })\n      .tiff({ resolutionUnit: 'cm' })\n      .toBuffer();\n    const { resolutionUnit } = await sharp(data).metadata();\n    assert.strictEqual(resolutionUnit, 'cm');\n  });\n\n  it('TIFF deflate compression with horizontal predictor shrinks test file', (_t, done) => {\n    const startSize = fs.statSync(fixtures.inputTiffUncompressed).size;\n    sharp(fixtures.inputTiffUncompressed)\n      .tiff({\n        compression: 'deflate',\n        predictor: 'horizontal'\n      })\n      .toFile(outputTiff, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('tiff', info.format);\n        assert(info.size < startSize);\n        fs.rm(outputTiff, done);\n      });\n  });\n\n  it('TIFF deflate compression with float predictor shrinks test file', (_t, done) => {\n    const startSize = fs.statSync(fixtures.inputTiffUncompressed).size;\n    sharp(fixtures.inputTiffUncompressed)\n      .tiff({\n        compression: 'deflate',\n        predictor: 'float'\n      })\n      .toFile(outputTiff, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('tiff', info.format);\n        assert(startSize > info.size);\n        fs.rm(outputTiff, done);\n      });\n  });\n\n  it('TIFF deflate compression without predictor shrinks test file', (_t, done) => {\n    const startSize = fs.statSync(fixtures.inputTiffUncompressed).size;\n    sharp(fixtures.inputTiffUncompressed)\n      .tiff({\n        compression: 'deflate',\n        predictor: 'none'\n      })\n      .toFile(outputTiff, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('tiff', info.format);\n        assert(info.size < startSize);\n        fs.rm(outputTiff, done);\n      });\n  });\n\n  it('TIFF jpeg compression shrinks test file', (_t, done) => {\n    const startSize = fs.statSync(fixtures.inputTiffUncompressed).size;\n    sharp(fixtures.inputTiffUncompressed)\n      .tiff({\n        compression: 'jpeg'\n      })\n      .toFile(outputTiff, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('tiff', info.format);\n        assert(info.size < startSize);\n        fs.rm(outputTiff, done);\n      });\n  });\n\n  it('TIFF none compression does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff({ compression: 'none' });\n    });\n  });\n\n  it('TIFF lzw compression does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff({ compression: 'lzw' });\n    });\n  });\n\n  it('TIFF deflate compression does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff({ compression: 'deflate' });\n    });\n  });\n\n  it('TIFF invalid compression option throws', () => {\n    assert.throws(() => {\n      sharp().tiff({ compression: 0 });\n    });\n  });\n\n  it('TIFF invalid compression option throws', () => {\n    assert.throws(() => {\n      sharp().tiff({ compression: 'a' });\n    });\n  });\n\n  it('TIFF bigtiff true value does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff({ bigtiff: true });\n    });\n  });\n\n  it('Invalid TIFF bigtiff value throws error', () => {\n    assert.throws(() => {\n      sharp().tiff({ bigtiff: 'true' });\n    });\n  });\n\n  it('TIFF invalid predictor option throws', () => {\n    assert.throws(() => {\n      sharp().tiff({ predictor: 'a' });\n    });\n  });\n\n  it('TIFF invalid resolutionUnit option throws', () => {\n    assert.throws(() => {\n      sharp().tiff({ resolutionUnit: 'none' });\n    });\n  });\n\n  it('TIFF horizontal predictor does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff({ predictor: 'horizontal' });\n    });\n  });\n\n  it('TIFF float predictor does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff({ predictor: 'float' });\n    });\n  });\n\n  it('TIFF none predictor does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff({ predictor: 'none' });\n    });\n  });\n\n  it('TIFF tiled pyramid image without compression enlarges test file', (_t, done) => {\n    const startSize = fs.statSync(fixtures.inputTiffUncompressed).size;\n    sharp(fixtures.inputTiffUncompressed)\n      .tiff({\n        compression: 'none',\n        pyramid: true,\n        tile: true,\n        tileHeight: 256,\n        tileWidth: 256\n      })\n      .toFile(outputTiff, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual('tiff', info.format);\n        assert(info.size > startSize);\n        fs.rm(outputTiff, done);\n      });\n  });\n\n  it('TIFF pyramid true value does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff({ pyramid: true });\n    });\n  });\n\n  it('Invalid TIFF pyramid value throws error', () => {\n    assert.throws(() => {\n      sharp().tiff({ pyramid: 'true' });\n    });\n  });\n\n  it('TIFF miniswhite true value does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff({ miniswhite: true });\n    });\n  });\n\n  it('Invalid TIFF miniswhite value throws error', () => {\n    assert.throws(() => {\n      sharp().tiff({ miniswhite: 'true' });\n    });\n  });\n\n  it('Invalid TIFF tile value throws error', () => {\n    assert.throws(() => {\n      sharp().tiff({ tile: 'true' });\n    });\n  });\n\n  it('TIFF tile true value does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff({ tile: true });\n    });\n  });\n\n  it('Valid TIFF tileHeight value does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff({ tileHeight: 512 });\n    });\n  });\n\n  it('Valid TIFF tileWidth value does not throw error', () => {\n    assert.doesNotThrow(() => {\n      sharp().tiff({ tileWidth: 512 });\n    });\n  });\n\n  it('Invalid TIFF tileHeight value throws error', () => {\n    assert.throws(() => {\n      sharp().tiff({ tileHeight: '256' });\n    });\n  });\n\n  it('Invalid TIFF tileWidth value throws error', () => {\n    assert.throws(() => {\n      sharp().tiff({ tileWidth: '256' });\n    });\n  });\n\n  it('Invalid TIFF tileHeight value throws error', () => {\n    assert.throws(() => {\n      sharp().tiff({ tileHeight: 0 });\n    });\n  });\n\n  it('Invalid TIFF tileWidth value throws error', () => {\n    assert.throws(() => {\n      sharp().tiff({ tileWidth: 0 });\n    });\n  });\n\n  it('TIFF file input with invalid page fails gracefully', (_t, done) => {\n    sharp(fixtures.inputTiffMultipage, { page: 2 })\n      .toBuffer((err) => {\n        assert.strictEqual(true, !!err);\n        done();\n      });\n  });\n\n  it('TIFF buffer input with invalid page fails gracefully', (_t, done) => {\n    sharp(fs.readFileSync(fixtures.inputTiffMultipage), { page: 2 })\n      .toBuffer((err) => {\n        assert.strictEqual(true, !!err);\n        done();\n      });\n  });\n});\n"
  },
  {
    "path": "test/unit/tile.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst path = require('node:path');\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst extractZip = require('extract-zip');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\n// Verifies all tiles in a given dz output directory are <= size\nconst assertDeepZoomTiles = (directory, expectedSize, expectedLevels, done) => {\n  // Get levels\n  const dirents = fs.readdirSync(directory, { withFileTypes: true });\n  const levels = dirents.filter(dirent => dirent.isDirectory()).map(dirent => dirent.name);\n  assert.strictEqual(expectedLevels, levels.length);\n  // Get tiles\n  const tiles = [];\n  levels.forEach((level) => {\n    // Verify level directory name\n    assert.strictEqual(true, /^[0-9]+$/.test(level));\n    fs.readdirSync(path.join(directory, level)).forEach((tile) => {\n      // Verify tile file name\n      assert.strictEqual(true, /^[0-9]+_[0-9]+\\.jpeg$/.test(tile));\n      tiles.push(path.join(directory, level, tile));\n    });\n  });\n  // Verify each tile is <= expectedSize\n  Promise.all(tiles.map((tile) => sharp(tile)\n      .metadata()\n      .then((metadata) => {\n        assert.strictEqual('jpeg', metadata.format);\n        assert.strictEqual('srgb', metadata.space);\n        assert.strictEqual(3, metadata.channels);\n        assert.strictEqual(false, metadata.hasProfile);\n        assert.strictEqual(false, metadata.hasAlpha);\n        assert.strictEqual(true, metadata.width <= expectedSize);\n        assert.strictEqual(true, metadata.height <= expectedSize);\n      })))\n    .then(() => done())\n    .catch(done);\n};\n\nconst assertZoomifyTiles = (directory, expectedLevels, done) => {\n  fs.stat(path.join(directory, 'ImageProperties.xml'), (err, stat) => {\n    if (err) throw err;\n    assert.ok(stat.isFile());\n    assert.ok(stat.size > 0);\n\n    let maxTileLevel = -1;\n    fs.readdirSync(path.join(directory, 'TileGroup0')).forEach((tile) => {\n      // Verify tile file name\n      assert.ok(/^[0-9]+-[0-9]+-[0-9]+\\.jpg$/.test(tile));\n      const level = Number(tile.split('-')[0]);\n      maxTileLevel = Math.max(maxTileLevel, level);\n    });\n\n    assert.strictEqual(maxTileLevel + 1, expectedLevels); // add one to account for zero level tile\n\n    done();\n  });\n};\n\nconst assertGoogleTiles = (directory, expectedLevels, done) => {\n  // Get levels\n  const dirents = fs.readdirSync(directory, { withFileTypes: true });\n  const levels = dirents.filter(dirent => dirent.isDirectory()).map(dirent => dirent.name);\n  assert.strictEqual(expectedLevels, levels.length);\n\n  fs.stat(path.join(directory, 'blank.png'), (err, stat) => {\n    if (err) throw err;\n    assert.ok(stat.isFile());\n    assert.ok(stat.size > 0);\n\n    // Basic check to confirm lowest and highest level tiles exist\n    fs.stat(path.join(directory, '0', '0', '0.jpg'), (err, stat) => {\n      if (err) throw err;\n      assert.strictEqual(true, stat.isFile());\n      assert.strictEqual(true, stat.size > 0);\n\n      fs.stat(path.join(directory, (expectedLevels - 1).toString(), '0', '0.jpg'), (err, stat) => {\n        if (err) throw err;\n        assert.strictEqual(true, stat.isFile());\n        assert.strictEqual(true, stat.size > 0);\n        done();\n      });\n    });\n  });\n};\n\n// Verifies tiles at specified level in a given output directory are > size+overlap\nconst assertTileOverlap = (directory, tileSize, done) => {\n  // Get sorted levels\n  const dirents = fs.readdirSync(directory, { withFileTypes: true });\n  const levels = dirents.filter(dirent => dirent.isDirectory()).map(dirent => dirent.name).sort((a, b) => a - b);\n  // Select the highest tile level\n  const highestLevel = levels[levels.length - 1];\n  // Get sorted tiles from greatest level\n  const tiles = fs.readdirSync(path.join(directory, highestLevel)).sort();\n  // Select a tile from the approximate center of the image\n  const squareTile = path.join(directory, highestLevel, tiles[Math.floor(tiles.length / 2)]);\n\n  sharp(squareTile).metadata((err, metadata) => {\n    if (err) {\n      throw err;\n    } else {\n      // Tile with an overlap should be larger than original size\n      assert.strictEqual(true, metadata.width > tileSize);\n      assert.strictEqual(true, metadata.height > tileSize);\n      done();\n    }\n  });\n};\n\ndescribe('Tile', () => {\n  it('Valid size values pass', () => {\n    [1, 8192].forEach((size) => {\n      assert.doesNotThrow(() => {\n        sharp().tile({\n          size\n        });\n      });\n    });\n  });\n\n  it('Invalid size values fail', () => {\n    ['zoinks', 1.1, -1, 0, 8193].forEach((size) => {\n      assert.throws(() => {\n        sharp().tile({\n          size\n        });\n      });\n    });\n  });\n\n  it('Valid overlap values pass', () => {\n    [0, 8192].forEach((overlap) => {\n      assert.doesNotThrow(() => {\n        sharp().tile({\n          size: 8192,\n          overlap\n        });\n      });\n    });\n  });\n\n  it('Invalid overlap values fail', () => {\n    ['zoinks', 1.1, -1, 8193].forEach((overlap) => {\n      assert.throws(() => {\n        sharp().tile({\n          overlap\n        });\n      });\n    });\n  });\n\n  it('Valid container values pass', () => {\n    ['fs', 'zip'].forEach((container) => {\n      assert.doesNotThrow(() => {\n        sharp().tile({\n          container\n        });\n      });\n    });\n  });\n\n  it('Invalid container values fail', () => {\n    ['zoinks', 1].forEach((container) => {\n      assert.throws(() => {\n        sharp().tile({\n          container\n        });\n      });\n    });\n  });\n\n  it('Valid layout values pass', () => {\n    ['dz', 'google', 'zoomify'].forEach((layout) => {\n      assert.doesNotThrow(() => {\n        sharp().tile({\n          layout\n        });\n      });\n    });\n  });\n\n  it('Invalid layout values fail', () => {\n    ['zoinks', 1].forEach((layout) => {\n      assert.throws(() => {\n        sharp().tile({\n          layout\n        });\n      });\n    });\n  });\n\n  it('Valid formats pass', () => {\n    ['jpeg', 'png', 'webp'].forEach((format) => {\n      assert.doesNotThrow(() => {\n        sharp().toFormat(format).tile();\n      });\n    });\n  });\n\n  it('Invalid formats fail', () => {\n    ['tiff', 'raw'].forEach((format) => {\n      assert.throws(() => {\n        sharp().toFormat(format).tile();\n      });\n    });\n  });\n\n  it('Valid depths pass', () => {\n    ['onepixel', 'onetile', 'one'].forEach((depth) => {\n      assert.doesNotThrow(() => sharp().tile({ depth }));\n    });\n  });\n\n  it('Invalid depths fail', () => {\n    ['depth', 1].forEach((depth) => {\n      assert.throws(\n        () => sharp().tile({ depth }),\n        /Expected one of: onepixel, onetile, one for depth but received/\n      );\n    });\n  });\n\n  it('Prevent larger overlap than default size', () => {\n    assert.throws(() => {\n      sharp().tile({\n        overlap: 257\n      });\n    });\n  });\n\n  it('Prevent larger overlap than provided size', () => {\n    assert.throws(() => {\n      sharp().tile({\n        size: 512,\n        overlap: 513\n      });\n    });\n  });\n\n  it('Valid rotation angle values pass', () => {\n    [90, 270, -90].forEach((angle) => {\n      assert.doesNotThrow(() => {\n        sharp().tile({\n          angle\n        });\n      });\n    });\n  });\n\n  it('Invalid rotation angle values fail', () => {\n    ['zoinks', 1.1, -1, 27].forEach((angle) => {\n      assert.throws(() => {\n        sharp().tile({\n          angle\n        });\n      });\n    });\n  });\n\n  it('Valid skipBlanks threshold values pass', () => {\n    [-1, 0, 255, 65535].forEach((skipBlanksThreshold) => {\n      assert.doesNotThrow(() => {\n        sharp().tile({\n          skipBlanks: skipBlanksThreshold\n        });\n      });\n    });\n  });\n\n  it('InvalidskipBlanks threshold values fail', () => {\n    ['zoinks', -2, 65536].forEach((skipBlanksThreshold) => {\n      assert.throws(() => {\n        sharp().tile({\n          skipBlanks: skipBlanksThreshold\n        });\n      });\n    });\n  });\n\n  it('Valid center parameter value passes', () => {\n    assert.doesNotThrow(\n      () => sharp().tile({ center: true })\n    );\n  });\n\n  it('Invalid centre parameter value fails', () => {\n    assert.throws(\n      () => sharp().tile({ centre: 'true' }),\n      /Expected boolean for tileCentre but received true of type string/\n    );\n  });\n\n  it('Valid id parameter value passes', () => {\n    assert.doesNotThrow(() => {\n      sharp().tile({\n        id: 'test'\n      });\n    });\n  });\n\n  it('Invalid id parameter value fails', () => {\n    assert.throws(() => {\n      sharp().tile({\n        id: true\n      });\n    });\n  });\n\n  it('Valid basename parameter value passes', () => {\n    assert.doesNotThrow(\n      () => sharp().tile({ basename: 'pass' })\n    );\n  });\n\n  it('Invalid basename parameter value fails', () => {\n    assert.throws(\n      () => sharp().tile({ basename: true }),\n      /Expected string for basename but received/\n    );\n  });\n\n  if (sharp.format.dz.output.file) {\n    it('Deep Zoom layout', (_t, done) => {\n      const directory = fixtures.path('output.dzi_files');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .toFile(fixtures.path('output.dzi'), (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual('undefined', typeof info.size);\n            assertDeepZoomTiles(directory, 256, 13, done);\n          });\n      });\n    });\n\n    it('Deep Zoom layout with custom size+overlap', (_t, done) => {\n      const directory = fixtures.path('output.512.dzi_files');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            size: 512,\n            overlap: 16\n          })\n          .toFile(fixtures.path('output.512.dzi'), (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual('undefined', typeof info.size);\n            assertDeepZoomTiles(directory, 512 + (2 * 16), 13, () => {\n              assertTileOverlap(directory, 512, done);\n            });\n          });\n      });\n    });\n\n    it('Deep Zoom layout with custom size+angle', (_t, done) => {\n      const directory = fixtures.path('output.512_90.dzi_files');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            size: 512,\n            angle: 90\n          })\n          .toFile(fixtures.path('output.512_90.dzi'), (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual('undefined', typeof info.size);\n            assertDeepZoomTiles(directory, 512, 13, done);\n            // Verifies tiles in 10th level are rotated\n            const tile = path.join(directory, '10', '0_1.jpeg');\n            // verify that the width and height correspond to the rotated image\n            // expected are w=512 and h=170 for the 0_1.jpeg.\n            // if a 0 angle is supplied to the .tile function\n            // the expected values are w=170 and h=512 for the 1_0.jpeg\n            sharp(tile).metadata((err, metadata) => {\n              if (err) {\n                throw err;\n              } else {\n                assert.strictEqual(true, metadata.width === 512);\n                assert.strictEqual(true, metadata.height === 170);\n              }\n            });\n          });\n      });\n    });\n\n    it('Deep Zoom layout with depth of one', (_t, done) => {\n      const directory = fixtures.path('output.512_depth_one.dzi_files');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            size: 512,\n            depth: 'one'\n          })\n          .toFile(fixtures.path('output.512_depth_one.dzi'), (err) => {\n            if (err) throw err;\n            // Verify only one depth generated\n            assertDeepZoomTiles(directory, 512, 1, done);\n          });\n      });\n    });\n\n    it('Deep Zoom layout with depth of onepixel', (_t, done) => {\n      const directory = fixtures.path('output.512_depth_onepixel.dzi_files');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            size: 512,\n            depth: 'onepixel'\n          })\n          .toFile(fixtures.path('output.512_depth_onepixel.dzi'), (err) => {\n            if (err) throw err;\n            // Verify only one depth generated\n            assertDeepZoomTiles(directory, 512, 13, done);\n          });\n      });\n    });\n\n    it('Deep Zoom layout with depth of onetile', (_t, done) => {\n      const directory = fixtures.path('output.256_depth_onetile.dzi_files');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            size: 256,\n            depth: 'onetile'\n          })\n          .toFile(fixtures.path('output.256_depth_onetile.dzi'), (err) => {\n            if (err) throw err;\n            // Verify only one depth generated\n            assertDeepZoomTiles(directory, 256, 5, done);\n          });\n      });\n    });\n\n    it('Deep Zoom layout with skipBlanks', (_t, done) => {\n      const directory = fixtures.path('output.256_skip_blanks.dzi_files');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpgOverlayLayer2)\n          .tile({\n            size: 256,\n            skipBlanks: 0\n          })\n          .toFile(fixtures.path('output.256_skip_blanks.dzi'), (err) => {\n            if (err) throw err;\n            // assert them 0_0.jpeg doesn't exist because it's a white tile\n            const whiteTilePath = path.join(directory, '11', '0_0.jpeg');\n            assert.strictEqual(fs.existsSync(whiteTilePath), false, 'Tile should not exist');\n            // Verify only one depth generated\n            assertDeepZoomTiles(directory, 256, 12, done);\n          });\n      });\n    });\n\n    it('Zoomify layout', (_t, done) => {\n      const directory = fixtures.path('output.zoomify.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            layout: 'zoomify'\n          })\n          .toFile(fixtures.path('output.zoomify.dzi'), (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            fs.stat(path.join(directory, 'ImageProperties.xml'), (err, stat) => {\n              if (err) throw err;\n              assert.strictEqual(true, stat.isFile());\n              assert.strictEqual(true, stat.size > 0);\n              done();\n            });\n          });\n      });\n    });\n\n    it('Zoomify layout with depth one', (_t, done) => {\n      const directory = fixtures.path('output.zoomify.depth_one.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            size: 256,\n            layout: 'zoomify',\n            depth: 'one'\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            assertZoomifyTiles(directory, 1, done);\n          });\n      });\n    });\n\n    it('Zoomify layout with depth onetile', (_t, done) => {\n      const directory = fixtures.path('output.zoomify.depth_onetile.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            size: 256,\n            layout: 'zoomify',\n            depth: 'onetile'\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            assertZoomifyTiles(directory, 5, done);\n          });\n      });\n    });\n\n    it('Zoomify layout with depth onepixel', (_t, done) => {\n      const directory = fixtures.path('output.zoomify.depth_onepixel.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            size: 256,\n            layout: 'zoomify',\n            depth: 'onepixel'\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            assertZoomifyTiles(directory, 13, done);\n          });\n      });\n    });\n\n    it('Zoomify layout with skip blanks', (_t, done) => {\n      const directory = fixtures.path('output.zoomify.skipBlanks.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpgOverlayLayer2)\n          .tile({\n            size: 256,\n            layout: 'zoomify',\n            skipBlanks: 0\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            // assert them 0_0.jpeg doesn't exist because it's a white tile\n            const whiteTilePath = path.join(directory, 'TileGroup0', '2-0-0.jpg');\n            assert.strictEqual(fs.existsSync(whiteTilePath), false, 'Tile should not exist');\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2048, info.width);\n            assert.strictEqual(1536, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            assertZoomifyTiles(directory, 4, done);\n          });\n      });\n    });\n\n    it('Google layout', (_t, done) => {\n      const directory = fixtures.path('output.google.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            layout: 'google'\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            fs.stat(path.join(directory, '0', '0', '0.jpg'), (err, stat) => {\n              if (err) throw err;\n              assert.strictEqual(true, stat.isFile());\n              assert.strictEqual(true, stat.size > 0);\n              done();\n            });\n          });\n      });\n    });\n\n    it('Google layout with jpeg format', (_t, done) => {\n      const directory = fixtures.path('output.jpg.google.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .jpeg({\n            quality: 1\n          })\n          .tile({\n            layout: 'google'\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            const sample = path.join(directory, '0', '0', '0.jpg');\n            sharp(sample).metadata((err, metadata) => {\n              if (err) throw err;\n              assert.strictEqual('jpeg', metadata.format);\n              assert.strictEqual('srgb', metadata.space);\n              assert.strictEqual(3, metadata.channels);\n              assert.strictEqual(false, metadata.hasProfile);\n              assert.strictEqual(false, metadata.hasAlpha);\n              assert.strictEqual(256, metadata.width);\n              assert.strictEqual(256, metadata.height);\n              fs.stat(sample, (err, stat) => {\n                if (err) throw err;\n                assert.strictEqual(true, stat.size < 2000);\n                done();\n              });\n            });\n          });\n      });\n    });\n\n    it('Google layout with png format', (_t, done) => {\n      const directory = fixtures.path('output.png.google.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .png({\n            compressionLevel: 0\n          })\n          .tile({\n            layout: 'google'\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            const sample = path.join(directory, '0', '0', '0.png');\n            sharp(sample).metadata((err, metadata) => {\n              if (err) throw err;\n              assert.strictEqual('png', metadata.format);\n              assert.strictEqual('srgb', metadata.space);\n              assert.strictEqual(3, metadata.channels);\n              assert.strictEqual(false, metadata.hasProfile);\n              assert.strictEqual(false, metadata.hasAlpha);\n              assert.strictEqual(256, metadata.width);\n              assert.strictEqual(256, metadata.height);\n              fs.stat(sample, (err, stat) => {\n                if (err) throw err;\n                assert.strictEqual(true, stat.size > 44000);\n                done();\n              });\n            });\n          });\n      });\n    });\n\n    it('Google layout with webp format', (_t, done) => {\n      const directory = fixtures.path('output.webp.google.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .webp({\n            quality: 1,\n            effort: 0\n          })\n          .tile({\n            layout: 'google'\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            const sample = path.join(directory, '0', '0', '0.webp');\n            sharp(sample).metadata((err, metadata) => {\n              if (err) throw err;\n              assert.strictEqual('webp', metadata.format);\n              assert.strictEqual('srgb', metadata.space);\n              assert.strictEqual(3, metadata.channels);\n              assert.strictEqual(false, metadata.hasProfile);\n              assert.strictEqual(false, metadata.hasAlpha);\n              assert.strictEqual(256, metadata.width);\n              assert.strictEqual(256, metadata.height);\n              fs.stat(sample, (err, stat) => {\n                if (err) throw err;\n                assert.strictEqual(true, stat.size < 2000);\n                done();\n              });\n            });\n          });\n      });\n    });\n\n    it('Google layout with depth one', (_t, done) => {\n      const directory = fixtures.path('output.google_depth_one.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            layout: 'google',\n            depth: 'one',\n            size: 256\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            assertGoogleTiles(directory, 1, done);\n          });\n      });\n    });\n\n    it('Google layout with depth onetile', (_t, done) => {\n      const directory = fixtures.path('output.google_depth_onetile.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            layout: 'google',\n            depth: 'onetile',\n            size: 256\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            assertGoogleTiles(directory, 5, done);\n          });\n      });\n    });\n\n    it('Google layout with default skip Blanks', (_t, done) => {\n      const directory = fixtures.path('output.google_depth_skipBlanks.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputPng)\n          .tile({\n            layout: 'google',\n            size: 256\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n\n            const whiteTilePath = path.join(directory, '4', '8', '0.jpg');\n            assert.strictEqual(fs.existsSync(whiteTilePath), false, 'Tile should not exist');\n\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2809, info.width);\n            assert.strictEqual(2074, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            assertGoogleTiles(directory, 5, done);\n          });\n      });\n    });\n\n    it('Google layout with center image in tile', (_t, done) => {\n      const directory = fixtures.path('output.google_center.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            center: true,\n            layout: 'google'\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            fixtures.assertSimilar(fixtures.expected('tile_centered.jpg'), fs.readFileSync(path.join(directory, '0', '0', '0.jpg')), done);\n          });\n      });\n    });\n\n    it('Google layout with center image in tile centre', (_t, done) => {\n      const directory = fixtures.path('output.google_center.dzi');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            centre: true,\n            layout: 'google'\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            fixtures.assertSimilar(fixtures.expected('tile_centered.jpg'), fs.readFileSync(path.join(directory, '0', '0', '0.jpg')), done);\n          });\n      });\n    });\n\n    it('IIIFv2 layout', (_t, done) => {\n      const name = 'output.iiif.info';\n      const directory = fixtures.path(name);\n      fs.rm(directory, { recursive: true }, () => {\n        const id = 'https://sharp.test.com/iiif';\n        sharp(fixtures.inputJpg)\n          .tile({\n            layout: 'iiif',\n            id\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            const infoJson = require(path.join(directory, 'info.json'));\n            assert.strictEqual('http://iiif.io/api/image/2/context.json', infoJson['@context']);\n            assert.strictEqual(`${id}/${name}`, infoJson['@id']);\n            fs.stat(path.join(directory, '0,0,256,256', '256,', '0', 'default.jpg'), (err, stat) => {\n              if (err) throw err;\n              assert.strictEqual(true, stat.isFile());\n              assert.strictEqual(true, stat.size > 0);\n              done();\n            });\n          });\n      });\n    });\n\n    it('IIIFv3 layout', (_t, done) => {\n      const name = 'output.iiif3.info';\n      const directory = fixtures.path(name);\n      fs.rm(directory, { recursive: true }, () => {\n        const id = 'https://sharp.test.com/iiif3';\n        sharp(fixtures.inputJpg)\n          .tile({\n            layout: 'iiif3',\n            id\n          })\n          .toFile(directory, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual(undefined, info.size);\n            const infoJson = require(path.join(directory, 'info.json'));\n            assert.strictEqual('http://iiif.io/api/image/3/context.json', infoJson['@context']);\n            assert.strictEqual('ImageService3', infoJson.type);\n            assert.strictEqual(`${id}/${name}`, infoJson.id);\n            fs.stat(path.join(directory, '0,0,256,256', '256,256', '0', 'default.jpg'), (err, stat) => {\n              if (err) throw err;\n              assert.strictEqual(true, stat.isFile());\n              assert.strictEqual(true, stat.size > 0);\n              done();\n            });\n          });\n      });\n    });\n\n    it('Write to ZIP container using file extension', (_t, done) => {\n      const container = fixtures.path('output.dz.container.zip');\n      const extractTo = fixtures.path('output.dz.container');\n      const directory = path.join(extractTo, 'output.dz.container_files');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .toFile(container, (err, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual('number', typeof info.size);\n            fs.stat(container, (err, stat) => {\n              if (err) throw err;\n              assert.strictEqual(true, stat.isFile());\n              assert.strictEqual(true, stat.size > 0);\n              extractZip(container, { dir: extractTo })\n                .then(() => {\n                  assertDeepZoomTiles(directory, 256, 13, done);\n                })\n                .catch(_t, done);\n            });\n          });\n      });\n    });\n\n    it('Write to ZIP container using container tile option', (_t, done) => {\n      const container = fixtures.path('output.dz.containeropt.zip');\n      const extractTo = fixtures.path('output.dz.containeropt');\n      const directory = path.join(extractTo, 'output.dz.containeropt_files');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({\n            container: 'zip'\n          })\n          .toFile(container, (err, info) => {\n            // Vips overrides .dzi extension to .zip used by container var below\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual('number', typeof info.size);\n            fs.stat(container, (err, stat) => {\n              if (err) throw err;\n              assert.strictEqual(true, stat.isFile());\n              assert.strictEqual(true, stat.size > 0);\n              extractZip(container, { dir: extractTo })\n                .then(() => {\n                  assertDeepZoomTiles(directory, 256, 13, done);\n                })\n                .catch(_t, done);\n            });\n          });\n      });\n    });\n\n    it('Write ZIP container to Buffer', (_t, done) => {\n      const container = fixtures.path('output.dz.tiles.zip');\n      const extractTo = fixtures.path('output.dz.tiles');\n      const directory = path.join(extractTo, 'output.dz.tiles_files');\n      fs.rm(directory, { recursive: true }, () => {\n        sharp(fixtures.inputJpg)\n          .tile({ basename: 'output.dz.tiles' })\n          .toBuffer((err, data, info) => {\n            if (err) throw err;\n            assert.strictEqual('dz', info.format);\n            assert.strictEqual(2725, info.width);\n            assert.strictEqual(2225, info.height);\n            assert.strictEqual(3, info.channels);\n            assert.strictEqual('number', typeof info.size);\n            fs.writeFileSync(container, data);\n            fs.stat(container, (err, stat) => {\n              if (err) throw err;\n              assert.strictEqual(true, stat.isFile());\n              assert.strictEqual(true, stat.size > 0);\n              extractZip(container, { dir: extractTo })\n                .then(() => {\n                  assertDeepZoomTiles(directory, 256, 13, done);\n                })\n                .catch(_t, done);\n            });\n          });\n      });\n    });\n  }\n});\n"
  },
  {
    "path": "test/unit/timeout.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Timeout', () => {\n  it('Will timeout after 1s when performing slow blur operation', () => assert.rejects(\n    () => sharp(fixtures.inputJpg)\n      .blur(200)\n      .timeout({ seconds: 1 })\n      .toBuffer(),\n    /timeout: [0-9]+% complete/\n  ));\n\n  it('invalid object', () => assert.throws(\n    () => sharp().timeout('fail'),\n    /Expected object for options but received fail of type string/\n  ));\n\n  it('invalid seconds', () => assert.throws(\n    () => sharp().timeout({ seconds: 'fail' }),\n    /Expected integer between 0 and 3600 for seconds but received fail of type string/\n  ));\n});\n"
  },
  {
    "path": "test/unit/tint.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\n// Allow for small rounding differences between platforms\nconst maxDistance = 6;\n\ndescribe('Tint', () => {\n  it('tints rgb image red', (_t, done) => {\n    const output = fixtures.path('output.tint-red.jpg');\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .tint('#FF0000')\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, info.size > 0);\n        fixtures.assertMaxColourDistance(output, fixtures.expected('tint-red.jpg'), maxDistance);\n        done();\n      });\n  });\n\n  it('tints rgb image green', (_t, done) => {\n    const output = fixtures.path('output.tint-green.jpg');\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .tint('#00FF00')\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, info.size > 0);\n        fixtures.assertMaxColourDistance(output, fixtures.expected('tint-green.jpg'), maxDistance);\n        done();\n      });\n  });\n\n  it('tints rgb image blue', (_t, done) => {\n    const output = fixtures.path('output.tint-blue.jpg');\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .tint('#0000FF')\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, info.size > 0);\n        fixtures.assertMaxColourDistance(output, fixtures.expected('tint-blue.jpg'), maxDistance);\n        done();\n      });\n  });\n\n  it('tints rgb image with sepia tone', (_t, done) => {\n    const output = fixtures.path('output.tint-sepia-hex.jpg');\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .tint('#704214')\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertMaxColourDistance(output, fixtures.expected('tint-sepia.jpg'), maxDistance);\n        done();\n      });\n  });\n\n  it('tints rgb image with sepia tone with rgb colour', (_t, done) => {\n    const output = fixtures.path('output.tint-sepia-rgb.jpg');\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .tint([112, 66, 20])\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertMaxColourDistance(output, fixtures.expected('tint-sepia.jpg'), maxDistance);\n        done();\n      });\n  });\n\n  it('tints rgb image with alpha channel', (_t, done) => {\n    const output = fixtures.path('output.tint-alpha.png');\n    sharp(fixtures.inputPngRGBWithAlpha)\n      .resize(320, 240)\n      .tint('#704214')\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        fixtures.assertMaxColourDistance(output, fixtures.expected('tint-alpha.png'), maxDistance);\n        done();\n      });\n  });\n\n  it('tints cmyk image red', (_t, done) => {\n    const output = fixtures.path('output.tint-cmyk.jpg');\n    sharp(fixtures.inputJpgWithCmykProfile)\n      .resize(320, 240)\n      .tint('#FF0000')\n      .toFile(output, (err, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, info.size > 0);\n        fixtures.assertMaxColourDistance(output, fixtures.expected('tint-cmyk.jpg'), maxDistance);\n        done();\n      });\n  });\n});\n"
  },
  {
    "path": "test/unit/toBuffer.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('toBuffer', () => {\n  it('reusing same sharp object does not reset previously passed parameters to toBuffer', async () => {\n    const image = sharp(fixtures.inputJpg);\n    const obj = await image.toBuffer({ resolveWithObject: true });\n    assert.strictEqual(typeof obj, 'object');\n    assert.strictEqual(typeof obj.info, 'object');\n    assert.strictEqual(Buffer.isBuffer(obj.data), true);\n    const data = await image.toBuffer();\n    assert.strictEqual(Buffer.isBuffer(data), true);\n  });\n\n  it('correctly process animated webp with height > 16383', async () => {\n    const data = await sharp(fixtures.inputWebPAnimatedBigHeight, { animated: true })\n      .toBuffer();\n    assert.strictEqual(Buffer.isBuffer(data), true);\n  });\n});\n"
  },
  {
    "path": "test/unit/toFormat.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('toFormat', () => {\n  it('accepts upper case characters as format parameter (string)', async () => {\n    const data = await sharp(fixtures.inputJpg)\n      .resize(8, 8)\n      .toFormat('PNG')\n      .toBuffer();\n\n    const { format } = await sharp(data).metadata();\n    assert.strictEqual(format, 'png');\n  });\n\n  it('accepts upper case characters as format parameter (object)', async () => {\n    const data = await sharp(fixtures.inputJpg)\n      .resize(8, 8)\n      .toFormat({ id: 'PNG' })\n      .toBuffer();\n\n    const { format } = await sharp(data).metadata();\n    assert.strictEqual(format, 'png');\n  });\n});\n"
  },
  {
    "path": "test/unit/trim.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst inRange = require('../../lib/is').inRange;\nconst fixtures = require('../fixtures');\n\ndescribe('Trim borders', () => {\n  it('Skip shrink-on-load', (_t, done) => {\n    const expected = fixtures.expected('alpha-layer-2-trim-resize.jpg');\n    sharp(fixtures.inputJpgOverlayLayer2)\n      .trim()\n      .resize({\n        width: 300,\n        fastShrinkOnLoad: false\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual('jpeg', info.format);\n        assert.strictEqual(300, info.width);\n        assert.strictEqual(true, inRange(info.trimOffsetLeft, -873, -870));\n        assert.strictEqual(-554, info.trimOffsetTop);\n        fixtures.assertSimilar(expected, data, done);\n      });\n  });\n\n  it('Single colour PNG where alpha channel provides the image', () =>\n    sharp(fixtures.inputPngImageInAlpha)\n      .trim()\n      .toBuffer({ resolveWithObject: true })\n      .then(({ data, info }) => {\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(916, info.width);\n        assert.strictEqual(137, info.height);\n        assert.strictEqual(4, info.channels);\n        assert.strictEqual(-6, info.trimOffsetLeft);\n        assert.strictEqual(-20, info.trimOffsetTop);\n      })\n  );\n\n  it('16-bit PNG with alpha channel', (_t, done) => {\n    sharp(fixtures.inputPngWithTransparency16bit)\n      .resize(32, 32)\n      .trim({\n        threshold: 20\n      })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('png', info.format);\n        assert.strictEqual(32, info.width);\n        assert.strictEqual(32, info.height);\n        assert.strictEqual(4, info.channels);\n        assert.strictEqual(-2, info.trimOffsetLeft);\n        assert.strictEqual(-2, info.trimOffsetTop);\n        fixtures.assertSimilar(fixtures.expected('trim-16bit-rgba.png'), data, done);\n      });\n  });\n\n  it('Attempt to trim 2x2 pixel image fails', (_t, done) => {\n    sharp({\n      create: {\n        width: 2,\n        height: 2,\n        channels: 3,\n        background: 'red'\n      }\n    })\n      .trim()\n      .toBuffer()\n      .then(() => {\n        done(new Error('Expected an error'));\n      })\n      .catch(err => {\n        assert.strictEqual('Image to trim must be at least 3x3 pixels', err.message);\n        done();\n      })\n      .catch(_t, done);\n  });\n\n  it('Should rotate before trim', () =>\n    sharp({\n      create: {\n        width: 20,\n        height: 30,\n        channels: 3,\n        background: 'white'\n      }\n    })\n      .rotate(30)\n      .png()\n      .toBuffer()\n      .then(rotated30 =>\n        sharp(rotated30)\n          .rotate(-30)\n          .trim({\n            threshold: 128\n          })\n          .toBuffer({ resolveWithObject: true })\n          .then(({ info }) => {\n            assert.strictEqual(20, info.width);\n            assert.strictEqual(31, info.height);\n            assert.strictEqual(-8, info.trimOffsetTop);\n            assert.strictEqual(-13, info.trimOffsetLeft);\n          })\n      )\n  );\n\n  it('Animated image rejects', () =>\n    assert.rejects(() => sharp(fixtures.inputGifAnimated, { animated: true })\n      .trim()\n      .toBuffer(),\n    /Trim is not supported for multi-page images/\n    )\n  );\n\n  it('Ensure trim uses bounding box of alpha and non-alpha channels', async () => {\n    const { info } = await sharp(fixtures.inputPngTrimIncludeAlpha)\n      .trim()\n      .toBuffer({ resolveWithObject: true });\n\n    const { width, height, trimOffsetTop, trimOffsetLeft } = info;\n    assert.strictEqual(width, 179);\n    assert.strictEqual(height, 123);\n    assert.strictEqual(trimOffsetTop, -44);\n    assert.strictEqual(trimOffsetLeft, -13);\n  });\n\n  it('Ensure greyscale image can be trimmed', async () => {\n    const greyscale = await sharp({\n      create: {\n        width: 16,\n        height: 8,\n        channels: 3,\n        background: 'silver'\n      }\n    })\n      .extend({ left: 12, right: 24, background: 'gray' })\n      .toColourspace('b-w')\n      .png({ compressionLevel: 0 })\n      .toBuffer();\n\n    const { info } = await sharp(greyscale)\n      .trim()\n      .raw()\n      .toBuffer({ resolveWithObject: true });\n\n    const { width, height, trimOffsetTop, trimOffsetLeft } = info;\n    assert.strictEqual(width, 16);\n    assert.strictEqual(height, 8);\n    assert.strictEqual(trimOffsetTop, 0);\n    assert.strictEqual(trimOffsetLeft, -12);\n  });\n\n  it('Ensure CMYK image can be trimmed', async () => {\n    const cmyk = await sharp({\n      create: {\n        width: 16,\n        height: 8,\n        channels: 3,\n        background: 'red'\n      }\n    })\n      .extend({ left: 12, right: 24, background: 'blue' })\n      .toColourspace('cmyk')\n      .jpeg()\n      .toBuffer();\n\n    const { info } = await sharp(cmyk)\n      .trim()\n      .raw()\n      .toBuffer({ resolveWithObject: true });\n\n    const { width, height, trimOffsetTop, trimOffsetLeft } = info;\n    assert.strictEqual(width, 16);\n    assert.strictEqual(height, 8);\n    assert.strictEqual(trimOffsetTop, 0);\n    assert.strictEqual(trimOffsetLeft, -12);\n  });\n\n  it('Ensure trim of image with all pixels same is no-op', async () => {\n    const { info } = await sharp({\n      create: {\n        width: 5,\n        height: 5,\n        channels: 3,\n        background: 'red'\n      }\n    })\n      .trim()\n      .toBuffer({ resolveWithObject: true });\n\n    const { width, height, trimOffsetTop, trimOffsetLeft } = info;\n    assert.strictEqual(width, 5);\n    assert.strictEqual(height, 5);\n    assert.strictEqual(trimOffsetTop, 0);\n    assert.strictEqual(trimOffsetLeft, 0);\n  });\n\n  it('Works with line-art', async () => {\n    const { info } = await sharp(fixtures.inputJpgOverlayLayer2)\n      .trim({ lineArt: true })\n      .toBuffer({ resolveWithObject: true });\n\n    assert.strictEqual(info.trimOffsetTop, -552);\n  });\n\n  describe('Invalid parameters', () => {\n    Object.entries({\n      'Invalid string': 'fail',\n      'Invalid background option': {\n        background: 'fail'\n      },\n      'Negative threshold option': {\n        threshold: -1\n      },\n      'Invalid lineArt': {\n        lineArt: 'fail'\n      }\n    }).forEach(([description, parameter]) => {\n      it(description, () => {\n        assert.throws(() => {\n          sharp().trim(parameter);\n        });\n      });\n    });\n  });\n\n  describe('Specific background colour', () => {\n    it('Doesn\\'t trim at all', async () => {\n      const { info } = await sharp(fixtures.inputPngTrimSpecificColour)\n        .trim({\n          background: 'yellow'\n        })\n        .toBuffer({ resolveWithObject: true });\n\n      const { width, height, trimOffsetTop, trimOffsetLeft } = info;\n      assert.strictEqual(width, 900);\n      assert.strictEqual(height, 600);\n      assert.strictEqual(trimOffsetTop, 0);\n      assert.strictEqual(trimOffsetLeft, 0);\n    });\n\n    it('Only trims the bottom', async () => {\n      const { info } = await sharp(fixtures.inputPngTrimSpecificColour)\n        .trim({\n          background: '#21468B'\n        })\n        .toBuffer({ resolveWithObject: true });\n\n      const { width, height, trimOffsetTop, trimOffsetLeft } = info;\n      assert.strictEqual(width, 900);\n      assert.strictEqual(height, 401);\n      assert.strictEqual(trimOffsetTop, 0);\n      assert.strictEqual(trimOffsetLeft, 0);\n    });\n\n    it('Only trims the bottom, in 16-bit', async () => {\n      const { info } = await sharp(fixtures.inputPngTrimSpecificColour16bit)\n        .trim({\n          background: '#21468B'\n        })\n        .toBuffer({ resolveWithObject: true });\n\n      const { width, height, trimOffsetTop, trimOffsetLeft } = info;\n      assert.strictEqual(width, 900);\n      assert.strictEqual(height, 401);\n      assert.strictEqual(trimOffsetTop, 0);\n      assert.strictEqual(trimOffsetLeft, 0);\n    });\n\n    it('Only trims the bottom, including alpha', async () => {\n      const { info } = await sharp(fixtures.inputPngTrimSpecificColourIncludeAlpha)\n        .trim({\n          background: '#21468B80'\n        })\n        .toBuffer({ resolveWithObject: true });\n\n      const { width, height, trimOffsetTop, trimOffsetLeft } = info;\n      assert.strictEqual(width, 900);\n      assert.strictEqual(height, 401);\n      assert.strictEqual(trimOffsetTop, 0);\n      assert.strictEqual(trimOffsetLeft, 0);\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/unflatten.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('Unflatten', () => {\n  it('unflatten white background', (_t, done) => {\n    sharp(fixtures.inputPng).unflatten()\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('unflatten-white-transparent.png'), data, { threshold: 0 }, done);\n      });\n  });\n  it('unflatten transparent image', (_t, done) => {\n    sharp(fixtures.inputPngTrimSpecificColourIncludeAlpha).unflatten()\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('unflatten-flag-white-transparent.png'), data, { threshold: 0 }, done);\n      });\n  });\n  it('unflatten using threshold', (_t, done) => {\n    sharp(fixtures.inputPngPalette).unflatten().threshold(128, { grayscale: false })\n      .toBuffer((err, data) => {\n        if (err) throw err;\n        fixtures.assertSimilar(fixtures.expected('unflatten-swiss.png'), data, { threshold: 1 }, done);\n      });\n  });\n});\n"
  },
  {
    "path": "test/unit/util.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\nconst semver = require('semver');\nconst sharp = require('../../');\n\ndescribe('Utilities', () => {\n  describe('Cache', () => {\n    it('Can be disabled', (_t, done) => {\n      const check = setInterval(() => {\n        const cache = sharp.cache(false);\n        const empty =\n          cache.memory.current +\n          cache.memory.max +\n          cache.files.current +\n          cache.files.max +\n          cache.items.current +\n          cache.items.max === 0;\n        if (empty) {\n          clearInterval(check);\n          done();\n        }\n      }, 2000);\n    });\n    it('Can be enabled with defaults', () => {\n      const cache = sharp.cache(true);\n      assert.strictEqual(cache.memory.max, 50);\n      assert.strictEqual(cache.files.max, 20);\n      assert.strictEqual(cache.items.max, 100);\n    });\n    it('Can be set to zero', () => {\n      const cache = sharp.cache({\n        memory: 0,\n        files: 0,\n        items: 0\n      });\n      assert.strictEqual(cache.memory.max, 0);\n      assert.strictEqual(cache.files.max, 0);\n      assert.strictEqual(cache.items.max, 0);\n    });\n    it('Can be set to a maximum of 10MB, 100 files and 1000 items', () => {\n      const cache = sharp.cache({\n        memory: 10,\n        files: 100,\n        items: 1000\n      });\n      assert.strictEqual(cache.memory.max, 10);\n      assert.strictEqual(cache.files.max, 100);\n      assert.strictEqual(cache.items.max, 1000);\n    });\n    it('Ignores invalid values', () => {\n      sharp.cache(true);\n      const cache = sharp.cache('spoons');\n      assert.strictEqual(cache.memory.max, 50);\n      assert.strictEqual(cache.files.max, 20);\n      assert.strictEqual(cache.items.max, 100);\n    });\n  });\n\n  describe('Concurrency', () => {\n    it('Can be set to use 16 threads', () => {\n      sharp.concurrency(16);\n      assert.strictEqual(16, sharp.concurrency());\n    });\n    it('Can be reset to default', () => {\n      sharp.concurrency(0);\n      assert.strictEqual(true, sharp.concurrency() > 0);\n    });\n    it('Ignores invalid values', () => {\n      const defaultConcurrency = sharp.concurrency();\n      sharp.concurrency('spoons');\n      assert.strictEqual(defaultConcurrency, sharp.concurrency());\n    });\n  });\n\n  describe('Counters', () => {\n    it('Have zero value at rest', (_t, done) => {\n      queueMicrotask(() => {\n        const counters = sharp.counters();\n        assert.strictEqual(0, counters.queue);\n        assert.strictEqual(0, counters.process);\n        done();\n      });\n    });\n  });\n\n  describe('SIMD', () => {\n    it('Can get current state', () => {\n      const simd = sharp.simd();\n      assert.strictEqual(typeof simd, 'boolean');\n    });\n    it('Can disable', () => {\n      const simd = sharp.simd(false);\n      assert.strictEqual(simd, false);\n    });\n    it('Can attempt to enable', () => {\n      const simd = sharp.simd(true);\n      assert.strictEqual(typeof simd, 'boolean');\n    });\n  });\n\n  describe('Format', () => {\n    it('Contains expected attributes', () => {\n      assert.strictEqual('object', typeof sharp.format);\n      Object.keys(sharp.format).forEach((format) => {\n        assert.strictEqual(true, 'id' in sharp.format[format]);\n        assert.strictEqual(format, sharp.format[format].id);\n        ['input', 'output'].forEach((direction) => {\n          assert.strictEqual(true, direction in sharp.format[format]);\n          assert.strictEqual('object', typeof sharp.format[format][direction]);\n          assert.strictEqual(true, [3, 4].includes(Object.keys(sharp.format[format][direction]).length));\n          assert.strictEqual(true, 'file' in sharp.format[format][direction]);\n          assert.strictEqual(true, 'buffer' in sharp.format[format][direction]);\n          assert.strictEqual(true, 'stream' in sharp.format[format][direction]);\n          assert.strictEqual('boolean', typeof sharp.format[format][direction].file);\n          assert.strictEqual('boolean', typeof sharp.format[format][direction].buffer);\n          assert.strictEqual('boolean', typeof sharp.format[format][direction].stream);\n        });\n      });\n    });\n    it('Raw file=false, buffer=true, stream=true', () => {\n      ['input', 'output'].forEach((direction) => {\n        assert.strictEqual(false, sharp.format.raw[direction].file);\n        assert.strictEqual(true, sharp.format.raw[direction].buffer);\n        assert.strictEqual(true, sharp.format.raw[direction].stream);\n      });\n    });\n    it('vips format supports filesystem only', () => {\n      ['input', 'output'].forEach((direction) => {\n        assert.strictEqual(true, sharp.format.vips[direction].file);\n        assert.strictEqual(false, sharp.format.vips[direction].buffer);\n        assert.strictEqual(false, sharp.format.vips[direction].stream);\n      });\n    });\n    it('input fileSuffix', () => {\n      assert.deepStrictEqual(['.jpg', '.jpeg', '.jpe', '.jfif'], sharp.format.jpeg.input.fileSuffix);\n    });\n    it('output alias', () => {\n      assert.deepStrictEqual(['jpe', 'jpg'], sharp.format.jpeg.output.alias);\n    });\n  });\n\n  describe('Versions', () => {\n    it('Contains expected attributes', () => {\n      assert.strictEqual('object', typeof sharp.versions);\n      assert(semver.valid(sharp.versions.vips));\n      assert(semver.valid(sharp.versions.sharp));\n    });\n  });\n\n  describe('Block', () => {\n    it('Can block a named operation', () => {\n      sharp.block({ operation: ['test'] });\n    });\n    it('Can unblock a named operation', () => {\n      sharp.unblock({ operation: ['test'] });\n    });\n    it('Invalid block operation throws', () => {\n      assert.throws(() => sharp.block(1),\n        /Expected object for options but received 1 of type number/\n      );\n      assert.throws(() => sharp.block({}),\n        /Expected Array<string> for operation but received undefined of type undefined/\n      );\n      assert.throws(() => sharp.block({ operation: 'fail' }),\n        /Expected Array<string> for operation but received fail of type string/\n      );\n      assert.throws(() => sharp.block({ operation: ['maybe', false] }),\n        /Expected Array<string> for operation but received maybe,false of type object/\n      );\n    });\n    it('Invalid unblock operation throws', () => {\n      assert.throws(() => sharp.unblock(1),\n        /Expected object for options but received 1 of type number/\n      );\n      assert.throws(() => sharp.unblock({}),\n        /Expected Array<string> for operation but received undefined of type undefined/\n      );\n      assert.throws(() => sharp.unblock({ operation: 'fail' }),\n        /Expected Array<string> for operation but received fail of type string/\n      );\n      assert.throws(() => sharp.unblock({ operation: ['maybe', false] }),\n        /Expected Array<string> for operation but received maybe,false of type object/\n      );\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/webp.js",
    "content": "/*!\n  Copyright 2013 Lovell Fuller and others.\n  SPDX-License-Identifier: Apache-2.0\n*/\n\nconst fs = require('node:fs');\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert');\n\nconst sharp = require('../../');\nconst fixtures = require('../fixtures');\n\ndescribe('WebP', () => {\n  it('WebP output', (_t, done) => {\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .toFormat(sharp.format.webp)\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('webp', info.format);\n        assert.strictEqual(320, info.width);\n        assert.strictEqual(240, info.height);\n        done();\n      });\n  });\n\n  it('Invalid WebP quality throws error', () => {\n    assert.throws(() => {\n      sharp().webp({ quality: 101 });\n    });\n  });\n\n  it('Invalid WebP alpha quality throws error', () => {\n    assert.throws(() => {\n      sharp().webp({ alphaQuality: 101 });\n    });\n  });\n\n  it('should work for webp alpha quality', (_t, done) => {\n    sharp(fixtures.inputPngAlphaPremultiplicationSmall)\n      .webp({ alphaQuality: 80, effort: 0 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('webp', info.format);\n        fixtures.assertSimilar(fixtures.expected('webp-alpha-80.webp'), data, done);\n      });\n  });\n\n  it('should work for webp lossless', (_t, done) => {\n    sharp(fixtures.inputPngAlphaPremultiplicationSmall)\n      .webp({ lossless: true, effort: 0 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('webp', info.format);\n        fixtures.assertSimilar(fixtures.expected('webp-lossless.webp'), data, done);\n      });\n  });\n\n  it('should work for webp near-lossless', (_t, done) => {\n    sharp(fixtures.inputPngAlphaPremultiplicationSmall)\n      .webp({ nearLossless: true, quality: 50, effort: 0 })\n      .toBuffer((err50, data50, info50) => {\n        if (err50) throw err50;\n        assert.strictEqual(true, data50.length > 0);\n        assert.strictEqual('webp', info50.format);\n        fixtures.assertSimilar(fixtures.expected('webp-near-lossless-50.webp'), data50, done);\n      });\n  });\n\n  it('should use near-lossless when both lossless and nearLossless are specified', (_t, done) => {\n    sharp(fixtures.inputPngAlphaPremultiplicationSmall)\n      .webp({ nearLossless: true, quality: 50, lossless: true, effort: 0 })\n      .toBuffer((err50, data50, info50) => {\n        if (err50) throw err50;\n        assert.strictEqual(true, data50.length > 0);\n        assert.strictEqual('webp', info50.format);\n        fixtures.assertSimilar(fixtures.expected('webp-near-lossless-50.webp'), data50, done);\n      });\n  });\n\n  it('should produce a larger file size using smartSubsample', () =>\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .webp({ smartSubsample: false })\n      .toBuffer()\n      .then(withoutSmartSubsample =>\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .webp({ smartSubsample: true })\n          .toBuffer()\n          .then(withSmartSubsample => {\n            assert.strictEqual(true, withSmartSubsample.length > withoutSmartSubsample.length);\n          })\n      )\n  );\n\n  it('invalid smartSubsample throws', () => {\n    assert.throws(() => {\n      sharp().webp({ smartSubsample: 1 });\n    });\n  });\n\n  it('can produce a different file size using smartDeblock', () =>\n    sharp(fixtures.inputPngOverlayLayer0)\n      .resize(320, 240)\n      .webp({ quality: 30, smartDeblock: false })\n      .toBuffer()\n      .then(withoutSmartDeblock =>\n        sharp(fixtures.inputPngOverlayLayer0)\n          .resize(320, 240)\n          .webp({ quality: 30, smartDeblock: true })\n          .toBuffer()\n          .then(withSmartDeblock => {\n            assert.strictEqual(true, withSmartDeblock.length !== withoutSmartDeblock.length);\n          })\n      )\n  );\n\n  it('invalid smartDeblock throws', () => {\n    assert.throws(\n      () => sharp().webp({ smartDeblock: 1 }),\n      /Expected boolean for webpSmartDeblock but received 1 of type number/\n    );\n  });\n\n  it('should produce a different file size with specific preset', () =>\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .webp({ preset: 'default' })\n      .toBuffer()\n      .then(presetDefault =>\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .webp({ preset: 'picture' })\n          .toBuffer()\n          .then(presetPicture => {\n            assert.notStrictEqual(presetDefault.length, presetPicture.length);\n          })\n      )\n  );\n\n  it('invalid preset throws', () => {\n    assert.throws(\n      () => sharp().webp({ preset: 'fail' }),\n      /Expected one of: default, photo, picture, drawing, icon, text for preset but received fail of type string/\n    );\n  });\n\n  it('should produce a smaller file size with increased effort', () =>\n    sharp(fixtures.inputJpg)\n      .resize(320, 240)\n      .webp()\n      .toBuffer()\n      .then(effort4 =>\n        sharp(fixtures.inputJpg)\n          .resize(320, 240)\n          .webp({ effort: 6 })\n          .toBuffer()\n          .then(effort6 => {\n            assert.strictEqual(true, effort4.length > effort6.length);\n          })\n      )\n  );\n\n  it('should produce different file size with/out shrink-on-load', async () => {\n    const [shrunk, resized] = await Promise.all([\n      sharp(fixtures.inputWebP).resize({ width: 16 }).toBuffer(),\n      sharp(fixtures.inputWebP).resize({ width: 16, fastShrinkOnLoad: false, kernel: 'nearest' }).toBuffer()\n    ]);\n    assert.notStrictEqual(shrunk.length, resized.length);\n  });\n\n  it('invalid effort throws', () => {\n    assert.throws(() => {\n      sharp().webp({ effort: true });\n    });\n  });\n\n  it('out of range effort throws', () => {\n    assert.throws(() => {\n      sharp().webp({ effort: -1 });\n    });\n  });\n\n  it('should set effort to 0', () => {\n    const effort = sharp().webp({ effort: 0 }).options.webpEffort;\n\n    assert.strictEqual(effort, 0);\n  });\n\n  it('valid minSize', () => {\n    assert.doesNotThrow(() => sharp().webp({ minSize: true }));\n  });\n\n  it('invalid minSize throws', () => {\n    assert.throws(\n      () => sharp().webp({ minSize: 1 }),\n      /Expected boolean for webpMinSize but received 1 of type number/\n    );\n  });\n\n  it('valid mixed', () => {\n    assert.doesNotThrow(() => sharp().webp({ mixed: true }));\n  });\n\n  it('invalid mixed throws', () => {\n    assert.throws(\n      () => sharp().webp({ mixed: 'fail' }),\n      /Expected boolean for webpMixed but received fail of type string/\n    );\n  });\n\n  it('invalid loop throws', () => {\n    assert.throws(() => {\n      sharp().webp({ loop: -1 });\n    });\n\n    assert.throws(() => {\n      sharp().webp({ loop: 65536 });\n    });\n  });\n\n  it('invalid delay throws', () => {\n    assert.throws(() => {\n      sharp().webp({ delay: -1 });\n    });\n\n    assert.throws(() => {\n      sharp().webp({ delay: [65536] });\n    });\n  });\n\n  it('should repeat a single delay for all frames', async () => {\n    const updated = await sharp(fixtures.inputWebPAnimated, { pages: -1 })\n      .webp({ delay: 100 })\n      .toBuffer()\n      .then(data => sharp(data, { pages: -1 }).metadata());\n\n    assert.deepStrictEqual(updated.delay, Array(updated.pages).fill(100));\n  });\n\n  it('should limit animation loop', async () => {\n    const updated = await sharp(fixtures.inputWebPAnimated, { pages: -1 })\n      .webp({ loop: 3 })\n      .toBuffer()\n      .then(data => sharp(data, { pages: -1 }).metadata());\n\n    assert.strictEqual(updated.loop, 3);\n  });\n\n  it('should change delay between frames', async () => {\n    const original = await sharp(fixtures.inputWebPAnimated, { pages: -1 }).metadata();\n\n    const expectedDelay = [...Array(original.pages).fill(40)];\n    const updated = await sharp(fixtures.inputWebPAnimated, { pages: -1 })\n      .webp({ delay: expectedDelay })\n      .toBuffer()\n      .then(data => sharp(data, { pages: -1 }).metadata());\n\n    assert.deepStrictEqual(updated.delay, expectedDelay);\n  });\n\n  it('should preserve delay between frames', async () => {\n    const updated = await sharp(fixtures.inputWebPAnimated, { pages: -1 })\n      .webp()\n      .toBuffer()\n      .then(data => sharp(data, { pages: -1 }).metadata());\n\n    assert.deepStrictEqual(updated.delay, [120, 120, 90, 120, 120, 90, 120, 90, 30]);\n  });\n\n  it('should work with streams when only animated is set', (_t, done) => {\n    fs.createReadStream(fixtures.inputWebPAnimated)\n      .pipe(sharp({ animated: true }))\n      .webp({ lossless: true, effort: 0 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('webp', info.format);\n        fixtures.assertSimilar(fixtures.inputWebPAnimated, data, done);\n      });\n  });\n\n  it('should work with streams when only pages is set', (_t, done) => {\n    fs.createReadStream(fixtures.inputWebPAnimated)\n      .pipe(sharp({ pages: -1 }))\n      .webp({ lossless: true, effort: 0 })\n      .toBuffer((err, data, info) => {\n        if (err) throw err;\n        assert.strictEqual(true, data.length > 0);\n        assert.strictEqual('webp', info.format);\n        fixtures.assertSimilar(fixtures.inputWebPAnimated, data, done);\n      });\n  });\n\n  it('should resize animated image to page height', async () => {\n    const updated = await sharp(fixtures.inputWebPAnimated, { pages: -1 })\n      .resize({ height: 570 })\n      .webp({ effort: 0 })\n      .toBuffer()\n      .then(data => sharp(data, { pages: -1 }).metadata());\n\n    assert.strictEqual(updated.height, 570 * 9);\n    assert.strictEqual(updated.pageHeight, 570);\n  });\n\n  it('should take page parameter into account when animated is set', async () => {\n    const updated = await sharp(fixtures.inputWebPAnimated, { animated: true, page: 2 })\n      .resize({ height: 570 })\n      .webp({ effort: 0 })\n      .toBuffer()\n      .then(data => sharp(data, { pages: -1 }).metadata());\n\n    assert.strictEqual(updated.height, 570 * 7);\n    assert.strictEqual(updated.pageHeight, 570);\n  });\n});\n"
  },
  {
    "path": "test/unit.mjs",
    "content": "import { readdir } from 'node:fs/promises';\nimport { run } from 'node:test';\nimport { spec } from 'node:test/reporters';\n\nconst files = (await readdir('./test/unit')).map((f) => `./test/unit/${f}`);\n\nrun({\n  files,\n  concurrency: true,\n  timeout: 60000,\n  coverage: true,\n  coverageIncludeGlobs: ['lib/*.js'],\n  branchCoverage: 100,\n})\n  .compose(new spec())\n  .pipe(process.stdout);\n"
  }
]