diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index b65d48b98..72ffc3793 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -25,7 +25,7 @@ Please select the `main` branch as the destination for your Pull Request so your Please squash your changes into a single commit using a command like `git rebase -i upstream/main`. -To test C++ changes, you can compile the module using `npm run build` and then run the tests using `npm test`. +To test C++ changes, you can compile the module using `npm run build:dist && npm run build` and then run the tests using `npm test`. ## Submit a Pull Request with a new feature diff --git a/.github/ISSUE_TEMPLATE/installation.md b/.github/ISSUE_TEMPLATE/installation.md index f1068198d..de7591db5 100644 --- a/.github/ISSUE_TEMPLATE/installation.md +++ b/.github/ISSUE_TEMPLATE/installation.md @@ -1,6 +1,6 @@ --- name: Installation -about: Something went wrong during either 'npm install sharp' or 'require("sharp")' +about: Something went wrong during either 'npm install sharp' or 'import "sharp"' labels: installation --- diff --git a/.github/ISSUE_TEMPLATE/possible-bug.md b/.github/ISSUE_TEMPLATE/possible-bug.md index c7e130e17..6e1fff328 100644 --- a/.github/ISSUE_TEMPLATE/possible-bug.md +++ b/.github/ISSUE_TEMPLATE/possible-bug.md @@ -14,7 +14,7 @@ labels: triage - [ ] Running `npm install sharp` completes without error. -- [ ] Running `node -e "require('sharp')"` completes without error. +- [ ] Running `node -e "import 'sharp'"` completes without error. If you cannot confirm both of these, please open an [installation issue](https://github.com/lovell/sharp/issues/new?labels=installation&template=installation.md) instead. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f133d7dee..a4284cf79 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -171,7 +171,7 @@ jobs: architecture: ${{ matrix.nodejs_arch }} - uses: actions/checkout@v6 - run: npm install - - run: npm run build + - run: npm run build:dist && npm run build - run: npm run test-unit - if: matrix.package run: npm run package-from-local-build @@ -216,7 +216,7 @@ jobs: run: apk add build-base git python3 font-noto --update-cache - uses: actions/checkout@v6 - run: npm install - - run: npm run build + - run: npm run build:dist && npm run build - run: npm run test-unit - if: matrix.package run: npm run package-from-local-build @@ -279,6 +279,7 @@ jobs: 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 export PATH=$PATH:/opt/nodejs/bin npm install + npm run build:dist npm run build node --test test/unit/io.js npm run package-from-local-build @@ -304,7 +305,7 @@ jobs: with: node-version: "22" - run: npm install - - run: emmake npm run build + - run: npm run build:dist && emmake npm run build - name: Verify emscripten versions match run: | EMSCRIPTEN_VERSION_LIBVIPS=$(node -p "require('@img/sharp-libvips-dev-wasm32/versions').emscripten") diff --git a/.gitignore b/.gitignore index f90893df6..90e6a841a 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,4 @@ package-lock.json .astro docs/dist release-notes.md +dist \ No newline at end of file diff --git a/README.md b/README.md index a8d778165..1e141b298 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,10 @@ npm install sharp ``` ```javascript +// ESM +import sharp from 'sharp'; + +// CJS const sharp = require('sharp'); ``` diff --git a/biome.json b/biome.json index 5556593dd..b2ba9d0e3 100644 --- a/biome.json +++ b/biome.json @@ -1,5 +1,5 @@ { - "$schema": "https://biomejs.dev/schemas/2.4.10/schema.json", + "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", "vcs": { "enabled": true, "clientKind": "git", diff --git a/docs/public/humans.txt b/docs/public/humans.txt index 00efa0d71..7d0d31294 100644 --- a/docs/public/humans.txt +++ b/docs/public/humans.txt @@ -329,3 +329,6 @@ GitHub: https://github.com/arcanis Name: Dmytro Tiapukhin GitHub: https://github.com/eddienubes + +Name: Florian Lefebvre +GitHub: https://github.com/florian-lefebvre diff --git a/docs/src/content/docs/api-constructor.md b/docs/src/content/docs/api-constructor.md index 6cb6afa90..d4190dc53 100644 --- a/docs/src/content/docs/api-constructor.md +++ b/docs/src/content/docs/api-constructor.md @@ -229,8 +229,8 @@ readableStream.pipe(pipeline); ```js // Create a pipeline that will download an image, resize it and format it to different files // Using Promises to know when the pipeline is complete -const fs = require("fs"); -const got = require("got"); +import fs from "node:fs"; +import got from "got"; const sharpStream = sharp({ failOn: 'none' }); const promises = []; diff --git a/docs/src/content/docs/changelog/v0.35.0.md b/docs/src/content/docs/changelog/v0.35.0.md index b0d945065..a420597b1 100644 --- a/docs/src/content/docs/changelog/v0.35.0.md +++ b/docs/src/content/docs/changelog/v0.35.0.md @@ -60,3 +60,8 @@ slug: changelog/v0.35.0 [#4504](https://github.com/lovell/sharp/issues/4504) * Add WebP `exact` option for control over transparent pixel colour values. + +* Add support for ESM + [#4509](https://github.com/lovell/sharp/pull/4509) + [@florian-lefebvre](https://github.com/florian-lefebvre) + diff --git a/install/build.js b/install/build.js index 579e11ad8..8eaa0f5a7 100644 --- a/install/build.js +++ b/install/build.js @@ -8,7 +8,7 @@ const { globalLibvipsVersion, log, spawnRebuild, -} = require('../lib/libvips'); +} = require('../dist/libvips.cjs'); log('Building from source'); log('See https://sharp.pixelplumbing.com/install#building-from-source'); diff --git a/lib/channel.js b/lib/channel.mjs similarity index 98% rename from lib/channel.js rename to lib/channel.mjs index 3c6c0b439..1fdf0a990 100644 --- a/lib/channel.js +++ b/lib/channel.mjs @@ -3,7 +3,7 @@ SPDX-License-Identifier: Apache-2.0 */ -const is = require('./is'); +import is from './is.mjs'; /** * Boolean operations for bandbool. @@ -163,7 +163,7 @@ function bandbool (boolOp) { * @module Sharp * @private */ -module.exports = (Sharp) => { +export default (Sharp) => { Object.assign(Sharp.prototype, { // Public instance functions removeAlpha, diff --git a/lib/colour.js b/lib/colour.mjs similarity index 98% rename from lib/colour.js rename to lib/colour.mjs index e61c248a8..718b20a2a 100644 --- a/lib/colour.js +++ b/lib/colour.mjs @@ -3,8 +3,8 @@ SPDX-License-Identifier: Apache-2.0 */ -const color = require('@img/colour'); -const is = require('./is'); +import color from '@img/colour'; +import is from './is.mjs'; /** * Colourspaces. @@ -175,7 +175,7 @@ function _setBackgroundColourOption (key, value) { * @module Sharp * @private */ -module.exports = (Sharp) => { +export default (Sharp) => { Object.assign(Sharp.prototype, { // Public tint, diff --git a/lib/composite.js b/lib/composite.mjs similarity index 99% rename from lib/composite.js rename to lib/composite.mjs index 1c3e5e629..a8f2f2063 100644 --- a/lib/composite.js +++ b/lib/composite.mjs @@ -3,7 +3,7 @@ SPDX-License-Identifier: Apache-2.0 */ -const is = require('./is'); +import is from './is.mjs'; /** * Blend modes. @@ -206,7 +206,7 @@ function composite (images) { * @module Sharp * @private */ -module.exports = (Sharp) => { +export default (Sharp) => { Sharp.prototype.composite = composite; Sharp.blend = blend; }; diff --git a/lib/constructor.js b/lib/constructor.mjs similarity index 98% rename from lib/constructor.js rename to lib/constructor.mjs index 390a5cb1c..eaa279eb7 100644 --- a/lib/constructor.js +++ b/lib/constructor.mjs @@ -3,11 +3,11 @@ SPDX-License-Identifier: Apache-2.0 */ -const util = require('node:util'); -const stream = require('node:stream'); -const is = require('./is'); +import util from 'node:util'; +import stream from 'node:stream'; +import is from './is.mjs'; -require('./sharp'); +import './sharp.mjs'; // Use NODE_DEBUG=sharp to enable libvips warnings const debuglog = util.debuglog('sharp'); @@ -432,8 +432,8 @@ Object.setPrototypeOf(Sharp, stream.Duplex); * @example * // Create a pipeline that will download an image, resize it and format it to different files * // Using Promises to know when the pipeline is complete - * const fs = require("fs"); - * const got = require("got"); + * import fs from "node:fs"; + * import got from "got"; * const sharpStream = sharp({ failOn: 'none' }); * * const promises = []; @@ -502,4 +502,4 @@ Object.assign(Sharp.prototype, { clone }); * @module Sharp * @private */ -module.exports = Sharp; +export default Sharp; diff --git a/lib/index.js b/lib/index.js deleted file mode 100644 index b80191d71..000000000 --- a/lib/index.js +++ /dev/null @@ -1,16 +0,0 @@ -/*! - Copyright 2013 Lovell Fuller and others. - SPDX-License-Identifier: Apache-2.0 -*/ - -const Sharp = require('./constructor'); -require('./input')(Sharp); -require('./resize')(Sharp); -require('./composite')(Sharp); -require('./operation')(Sharp); -require('./colour')(Sharp); -require('./channel')(Sharp); -require('./output')(Sharp); -require('./utility')(Sharp); - -module.exports = Sharp; diff --git a/lib/index.mjs b/lib/index.mjs new file mode 100644 index 000000000..73a5ad2ed --- /dev/null +++ b/lib/index.mjs @@ -0,0 +1,25 @@ +/*! + Copyright 2013 Lovell Fuller and others. + SPDX-License-Identifier: Apache-2.0 +*/ + +import Sharp from './constructor.mjs'; +import input from './input.mjs'; +import resize from './resize.mjs'; +import composite from './composite.mjs'; +import operation from './operation.mjs'; +import colour from './colour.mjs'; +import channel from './channel.mjs'; +import output from './output.mjs'; +import utility from './utility.mjs'; + +input(Sharp); +resize(Sharp); +composite(Sharp); +operation(Sharp); +colour(Sharp); +channel(Sharp); +output(Sharp); +utility(Sharp); + +export default Sharp; diff --git a/lib/input.js b/lib/input.mjs similarity index 99% rename from lib/input.js rename to lib/input.mjs index 695f6d392..e2f5a0ddf 100644 --- a/lib/input.js +++ b/lib/input.mjs @@ -3,8 +3,8 @@ SPDX-License-Identifier: Apache-2.0 */ -const is = require('./is'); -const sharp = require('./sharp'); +import is from './is.mjs'; +import sharp from './sharp.mjs'; /** * Justification alignment @@ -786,7 +786,7 @@ function stats (callback) { * @module Sharp * @private */ -module.exports = (Sharp) => { +export default (Sharp) => { Object.assign(Sharp.prototype, { // Private _inputOptionsFromObject, diff --git a/lib/is.js b/lib/is.mjs similarity index 99% rename from lib/is.js rename to lib/is.mjs index 3ac9a1a35..bfb4188f8 100644 --- a/lib/is.js +++ b/lib/is.mjs @@ -124,7 +124,7 @@ const nativeError = (native, context) => { return context; }; -module.exports = { +export default { defined, object, plainObject, diff --git a/lib/libvips.js b/lib/libvips.mjs similarity index 88% rename from lib/libvips.js rename to lib/libvips.mjs index 9c9fd89cc..ddd6aa3a3 100644 --- a/lib/libvips.js +++ b/lib/libvips.mjs @@ -3,17 +3,16 @@ SPDX-License-Identifier: Apache-2.0 */ -const { spawnSync } = require('node:child_process'); -const { createHash } = require('node:crypto'); -const semverCoerce = require('semver/functions/coerce'); -const semverGreaterThanOrEqualTo = require('semver/functions/gte'); -const semverSatisfies = require('semver/functions/satisfies'); -const detectLibc = require('detect-libc'); - -const { config, engines, optionalDependencies } = require('../package.json'); +import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import semverCoerce from 'semver/functions/coerce'; +import semverGreaterThanOrEqualTo from 'semver/functions/gte'; +import semverSatisfies from 'semver/functions/satisfies'; +import detectLibc from 'detect-libc'; +import pkg from '../package.json' with { type: 'json' }; /* node:coverage ignore next */ -const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || config.libvips; +const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || pkg.config.libvips; const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version; const prebuiltPlatforms = [ @@ -83,8 +82,8 @@ const buildSharpLibvipsLibDir = () => { const isUnsupportedNodeRuntime = () => { if (process.release?.name === 'node' && process.versions) { - if (!semverSatisfies(process.versions.node, engines.node)) { - return { found: process.versions.node, expected: engines.node }; + if (!semverSatisfies(process.versions.node, pkg.engines.node)) { + return { found: process.versions.node, expected: pkg.engines.node }; } } }; @@ -109,7 +108,7 @@ const sha512 = (s) => createHash('sha512').update(s).digest('hex'); const yarnLocator = () => { try { const identHash = sha512(`imgsharp-libvips-${buildPlatformArch()}`); - const npmVersion = semverCoerce(optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`], { + const npmVersion = semverCoerce(pkg.optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`], { includePrerelease: true }).version; return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10); @@ -197,7 +196,7 @@ const useGlobalLibvips = (logger) => { return !!globalVipsVersion && semverGreaterThanOrEqualTo(globalVipsVersion, minimumLibvipsVersion); }; -module.exports = { +export default { minimumLibvipsVersion, prebuiltPlatforms, buildPlatformArch, diff --git a/lib/operation.js b/lib/operation.mjs similarity index 99% rename from lib/operation.js rename to lib/operation.mjs index b03b2fb76..448d30c2a 100644 --- a/lib/operation.js +++ b/lib/operation.mjs @@ -3,7 +3,7 @@ SPDX-License-Identifier: Apache-2.0 */ -const is = require('./is'); +import is from './is.mjs'; /** * How accurate an operation should be. @@ -958,7 +958,7 @@ function modulate (options) { * @module Sharp * @private */ -module.exports = (Sharp) => { +export default (Sharp) => { Object.assign(Sharp.prototype, { autoOrient, rotate, diff --git a/lib/output.js b/lib/output.mjs similarity index 99% rename from lib/output.js rename to lib/output.mjs index 9b54fccee..381f2f249 100644 --- a/lib/output.js +++ b/lib/output.mjs @@ -3,9 +3,9 @@ SPDX-License-Identifier: Apache-2.0 */ -const path = require('node:path'); -const is = require('./is'); -const sharp = require('./sharp'); +import path from 'node:path'; +import is from './is.mjs'; +import sharp from './sharp.mjs'; const formats = new Map([ ['heic', 'heif'], @@ -1759,7 +1759,7 @@ function _pipeline (callback, stack) { * @module Sharp * @private */ -module.exports = (Sharp) => { +export default (Sharp) => { Object.assign(Sharp.prototype, { // Public toFile, diff --git a/lib/resize.js b/lib/resize.mjs similarity index 99% rename from lib/resize.js rename to lib/resize.mjs index 8084e55ed..e38f74668 100644 --- a/lib/resize.js +++ b/lib/resize.mjs @@ -3,7 +3,7 @@ SPDX-License-Identifier: Apache-2.0 */ -const is = require('./is'); +import is from './is.mjs'; /** * Weighting to apply when using contain/cover fit. @@ -595,7 +595,7 @@ function trim (options) { * @module Sharp * @private */ -module.exports = (Sharp) => { +export default (Sharp) => { Object.assign(Sharp.prototype, { resize, extend, diff --git a/lib/sharp.js b/lib/sharp.js deleted file mode 100644 index 4abe301f3..000000000 --- a/lib/sharp.js +++ /dev/null @@ -1,163 +0,0 @@ -/*! - Copyright 2013 Lovell Fuller and others. - SPDX-License-Identifier: Apache-2.0 -*/ - -// Inspects the runtime environment and exports the relevant sharp.node binary - -const { familySync, versionSync } = require('detect-libc'); - -const { version } = require('../package.json'); -const { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips'); -const runtimePlatform = runtimePlatformArch(); - -/* node:coverage disable */ - -const prebuiltBinaryForRuntime = () => { - switch (runtimePlatform) { - case 'darwin-arm64': - return require('@img/sharp-darwin-arm64/sharp.node'); - case 'darwin-x64': - return require('@img/sharp-darwin-x64/sharp.node'); - case 'linux-arm': - return require('@img/sharp-linux-arm/sharp.node'); - case 'linux-arm64': - return require('@img/sharp-linux-arm64/sharp.node'); - case 'linux-ppc64': - return require('@img/sharp-linux-ppc64/sharp.node'); - case 'linux-riscv64': - return require('@img/sharp-linux-riscv64/sharp.node'); - case 'linux-s390x': - return require('@img/sharp-linux-s390x/sharp.node'); - case 'linux-x64': - return require('@img/sharp-linux-x64/sharp.node'); - case 'linuxmusl-arm64': - return require('@img/sharp-linuxmusl-arm64/sharp.node') ; - case 'linuxmusl-x64': - return require('@img/sharp-linuxmusl-x64/sharp.node'); - case 'win32-arm64': - return require('@img/sharp-win32-arm64/sharp.node'); - case 'win32-ia32': - return require('@img/sharp-win32-ia32/sharp.node'); - case 'win32-x64': - return require('@img/sharp-win32-x64/sharp.node'); - case 'freebsd-arm64': - case 'freebsd-x64': - return require('@img/sharp-freebsd-wasm32/sharp.node'); - case 'linux-wasm32': - return require('@img/sharp-webcontainers-wasm32/sharp.node'); - default: - return require('@img/sharp-wasm32/sharp.node'); - } -}; - -let sharp; -const errors = []; -try { - sharp = require(`../src/build/Release/sharp-${runtimePlatform}-${version}.node`); -} catch (err) { - errors.push(err); -} -if (!sharp) { - try { - sharp = require(`../src/build/Release/sharp-wasm32-${version}.node`); - } catch (err) { - errors.push(err); - } -} -if (!sharp) { - try { - sharp = prebuiltBinaryForRuntime(); - if (['linux-x64', 'linuxmusl-x64'].includes(runtimePlatform) && !sharp._isUsingX64V2()) { - const err = new Error('Prebuilt binaries for Linux x64 require v2 microarchitecture'); - err.code = 'Unsupported CPU'; - errors.push(err); - sharp = null; - } - } catch (err) { - errors.push(err); - } -} - -if (sharp) { - module.exports = sharp; -} else { - const [isLinux, isMacOs, isWindows] = ['linux', 'darwin', 'win32'].map(os => runtimePlatform.startsWith(os)); - - const help = [`Could not load the "sharp" module using the ${runtimePlatform} runtime`]; - errors.forEach(err => { - if (err.code !== 'MODULE_NOT_FOUND') { - help.push(`${err.code}: ${err.message}`); - } - }); - const messages = errors.map(err => err.message).join(' '); - help.push('Possible solutions:'); - // Common error messages - if (isUnsupportedNodeRuntime()) { - const { found, expected } = isUnsupportedNodeRuntime(); - help.push( - '- Please upgrade Node.js:', - ` Found ${found}`, - ` Requires ${expected}` - ); - } else if (prebuiltPlatforms.includes(runtimePlatform)) { - const [os, cpu] = runtimePlatform.split('-'); - const libc = os.endsWith('musl') ? ' --libc=musl' : ''; - help.push( - '- Ensure optional dependencies can be installed:', - ' npm install --include=optional sharp', - '- Ensure your package manager supports multi-platform installation:', - ' See https://sharp.pixelplumbing.com/install#cross-platform', - '- Add platform-specific dependencies:', - ` npm install --os=${os.replace('musl', '')}${libc} --cpu=${cpu} sharp` - ); - } else { - help.push( - `- Manually install libvips >= ${minimumLibvipsVersion}`, - ' See https://sharp.pixelplumbing.com/install#building-from-source', - '- Add WebAssembly-based dependencies:', - ' npm install sharp @img/sharp-wasm32' - ); - } - if (isLinux && /(symbol not found|CXXABI_)/i.test(messages)) { - try { - const { config } = require(`@img/sharp-libvips-${runtimePlatform}/package`); - const libcFound = `${familySync()} ${versionSync()}`; - const libcRequires = `${config.musl ? 'musl' : 'glibc'} ${config.musl || config.glibc}`; - help.push( - '- Update your OS:', - ` Found ${libcFound}`, - ` Requires ${libcRequires}` - ); - } catch (_errEngines) {} - } - if (isLinux && /\/snap\/core[0-9]{2}/.test(messages)) { - help.push( - '- Remove the Node.js Snap, which does not support native modules', - ' snap remove node' - ); - } - if (isMacOs && /Incompatible library version/.test(messages)) { - help.push( - '- Update Homebrew:', - ' brew update && brew upgrade vips' - ); - } - if (errors.some(err => err.code === 'ERR_DLOPEN_DISABLED')) { - help.push('- Run Node.js without using the --no-addons flag'); - } - // Link to installation docs - if (isWindows && /The specified procedure could not be found/.test(messages)) { - help.push( - '- Using the canvas package on Windows?', - ' See https://sharp.pixelplumbing.com/install#canvas-and-windows', - '- Check for outdated versions of sharp in the dependency tree:', - ' npm ls sharp' - ); - } - help.push( - '- Consult the installation documentation:', - ' See https://sharp.pixelplumbing.com/install' - ); - throw new Error(help.join('\n')); -} diff --git a/lib/sharp.mjs b/lib/sharp.mjs new file mode 100644 index 000000000..3276a1d4e --- /dev/null +++ b/lib/sharp.mjs @@ -0,0 +1,157 @@ +/*! + Copyright 2013 Lovell Fuller and others. + SPDX-License-Identifier: Apache-2.0 +*/ + +// Inspects the runtime environment and exports the relevant sharp.node binary + +import { familySync, versionSync } from "detect-libc"; + +import { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } from "./libvips.mjs"; +const runtimePlatform = runtimePlatformArch(); + +/* node:coverage disable */ + +let sharp; +const errors = []; +try { + sharp = await import(`../src/build/Release/sharp-${runtimePlatform}-${version}.node`); +} catch (err) { + errors.push(err); +} +if (!sharp) { + try { + sharp = await import(`../src/build/Release/sharp-wasm32-${version}.node`); + } catch (err) { + errors.push(err); + } +} +if (!sharp) { + try { + switch (runtimePlatform) { + case "darwin-arm64": + sharp = await import("@img/sharp-darwin-arm64/sharp.node"); + break; + case "darwin-x64": + sharp = await import("@img/sharp-darwin-x64/sharp.node"); + break; + case "linux-arm": + sharp = await import("@img/sharp-linux-arm/sharp.node"); + break; + case "linux-arm64": + sharp = await import("@img/sharp-linux-arm64/sharp.node"); + break; + case "linux-ppc64": + sharp = await import("@img/sharp-linux-ppc64/sharp.node"); + break; + case "linux-riscv64": + sharp = await import("@img/sharp-linux-riscv64/sharp.node"); + break; + case "linux-s390x": + sharp = await import("@img/sharp-linux-s390x/sharp.node"); + break; + case "linux-x64": + sharp = await import("@img/sharp-linux-x64/sharp.node"); + break; + case "linuxmusl-arm64": + sharp = await import("@img/sharp-linuxmusl-arm64/sharp.node"); + break; + case "linuxmusl-x64": + sharp = await import("@img/sharp-linuxmusl-x64/sharp.node"); + break; + case "win32-arm64": + sharp = await import("@img/sharp-win32-arm64/sharp.node"); + break; + case "win32-ia32": + sharp = await import("@img/sharp-win32-ia32/sharp.node"); + break; + case "win32-x64": + sharp = await import("@img/sharp-win32-x64/sharp.node"); + break; + case "freebsd-arm64": + case "freebsd-x64": + sharp = await import("@img/sharp-freebsd-wasm32/sharp.node"); + break; + case "linux-wasm32": + sharp = await import("@img/sharp-webcontainers-wasm32/sharp.node"); + break; + default: + sharp = await import("@img/sharp-wasm32/sharp.node"); + break; + } + if (["linux-x64", "linuxmusl-x64"].includes(runtimePlatform) && !sharp._isUsingX64V2()) { + const err = new Error("Prebuilt binaries for Linux x64 require v2 microarchitecture"); + err.code = "Unsupported CPU"; + errors.push(err); + sharp = null; + } + } catch (err) { + errors.push(err); + } +} + +if (!sharp) { + const [isLinux, isMacOs, isWindows] = ["linux", "darwin", "win32"].map((os) => runtimePlatform.startsWith(os)); + + const help = [`Could not load the "sharp" module using the ${runtimePlatform} runtime`]; + errors.forEach((err) => { + if (err.code !== "MODULE_NOT_FOUND") { + help.push(`${err.code}: ${err.message}`); + } + }); + const messages = errors.map((err) => err.message).join(" "); + help.push("Possible solutions:"); + // Common error messages + if (isUnsupportedNodeRuntime()) { + const { found, expected } = isUnsupportedNodeRuntime(); + help.push("- Please upgrade Node.js:", ` Found ${found}`, ` Requires ${expected}`); + } else if (prebuiltPlatforms.includes(runtimePlatform)) { + const [os, cpu] = runtimePlatform.split("-"); + const libc = os.endsWith("musl") ? " --libc=musl" : ""; + help.push( + "- Ensure optional dependencies can be installed:", + " npm install --include=optional sharp", + "- Ensure your package manager supports multi-platform installation:", + " See https://sharp.pixelplumbing.com/install#cross-platform", + "- Add platform-specific dependencies:", + ` npm install --os=${os.replace("musl", "")}${libc} --cpu=${cpu} sharp`, + ); + } else { + help.push( + `- Manually install libvips >= ${minimumLibvipsVersion}`, + " See https://sharp.pixelplumbing.com/install#building-from-source", + "- Add WebAssembly-based dependencies:", + " npm install sharp @img/sharp-wasm32", + ); + } + if (isLinux && /(symbol not found|CXXABI_)/i.test(messages)) { + try { + const { config } = await import(`@img/sharp-libvips-${runtimePlatform}/package`); + const libcFound = `${familySync()} ${versionSync()}`; + const libcRequires = `${config.musl ? "musl" : "glibc"} ${config.musl || config.glibc}`; + help.push("- Update your OS:", ` Found ${libcFound}`, ` Requires ${libcRequires}`); + } catch (_errEngines) {} + } + if (isLinux && /\/snap\/core[0-9]{2}/.test(messages)) { + help.push("- Remove the Node.js Snap, which does not support native modules", " snap remove node"); + } + if (isMacOs && /Incompatible library version/.test(messages)) { + help.push("- Update Homebrew:", " brew update && brew upgrade vips"); + } + if (errors.some((err) => err.code === "ERR_DLOPEN_DISABLED")) { + help.push("- Run Node.js without using the --no-addons flag"); + } + // Link to installation docs + if (isWindows && /The specified procedure could not be found/.test(messages)) { + help.push( + "- Using the canvas package on Windows?", + " See https://sharp.pixelplumbing.com/install#canvas-and-windows", + "- Check for outdated versions of sharp in the dependency tree:", + " npm ls sharp", + ); + } + help.push("- Consult the installation documentation:", " See https://sharp.pixelplumbing.com/install"); + throw new Error(help.join("\n")); +} + +export default sharp; diff --git a/lib/utility.js b/lib/utility.mjs similarity index 93% rename from lib/utility.js rename to lib/utility.mjs index 4e597e1df..0645f1db5 100644 --- a/lib/utility.js +++ b/lib/utility.mjs @@ -3,12 +3,13 @@ SPDX-License-Identifier: Apache-2.0 */ -const events = require('node:events'); -const detectLibc = require('detect-libc'); +import events from 'node:events'; +import detectLibc from 'detect-libc'; -const is = require('./is'); -const { runtimePlatformArch } = require('./libvips'); -const sharp = require('./sharp'); +import is from './is.mjs'; +import { runtimePlatformArch } from './libvips.mjs'; +import sharp from './sharp.mjs'; +import pkg from "../package.json" with { type: "json" }; const runtimePlatform = runtimePlatformArch(); const libvipsVersion = sharp.libvipsVersion(); @@ -61,19 +62,19 @@ let versions = { if (!libvipsVersion.isGlobal) { if (!libvipsVersion.isWasm) { try { - versions = require(`@img/sharp-${runtimePlatform}/versions`); + versions = await import(`@img/sharp-${runtimePlatform}/versions`); } catch (_) { try { - versions = require(`@img/sharp-libvips-${runtimePlatform}/versions`); + versions = await import(`@img/sharp-libvips-${runtimePlatform}/versions`); } catch (_) {} } } else { try { - versions = require('@img/sharp-wasm32/versions'); + versions = await import('@img/sharp-wasm32/versions'); } catch (_) {} } } -versions.sharp = require('../package.json').version; +versions.sharp = pkg.version; /* node:coverage ignore next 5 */ if (versions.heif && format.heif) { @@ -156,7 +157,8 @@ if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) { sharp.concurrency(1); } else if (detectLibc.familySync() === detectLibc.MUSL && sharp.concurrency() === 1024) { // Reduce default concurrency when musl thread over-subscription detected - sharp.concurrency(require('node:os').availableParallelism()); + const { availableParallelism } = await import('node:os') + sharp.concurrency(availableParallelism()); } /** @@ -277,7 +279,7 @@ function unblock (options) { * @module Sharp * @private */ -module.exports = (Sharp) => { +export default (Sharp) => { Sharp.cache = cache; Sharp.concurrency = concurrency; Sharp.counters = counters; diff --git a/npm/freebsd-wasm32/export/package.mjs b/npm/freebsd-wasm32/export/package.mjs new file mode 100644 index 000000000..d561aa57f --- /dev/null +++ b/npm/freebsd-wasm32/export/package.mjs @@ -0,0 +1 @@ +export { default } from '@img/sharp-wasm32/package.json' with { type: 'json' }; diff --git a/npm/freebsd-wasm32/export/sharp.node.mjs b/npm/freebsd-wasm32/export/sharp.node.mjs new file mode 100644 index 000000000..006986282 --- /dev/null +++ b/npm/freebsd-wasm32/export/sharp.node.mjs @@ -0,0 +1 @@ +export { default } from "@img/sharp-wasm32/sharp.node"; diff --git a/npm/freebsd-wasm32/export/versions.mjs b/npm/freebsd-wasm32/export/versions.mjs new file mode 100644 index 000000000..b53d54669 --- /dev/null +++ b/npm/freebsd-wasm32/export/versions.mjs @@ -0,0 +1 @@ +export { default } from "@img/sharp-wasm32/versions.json" with { type: "json" }; diff --git a/npm/freebsd-wasm32/package.json b/npm/freebsd-wasm32/package.json index 24f4d7a14..f38384428 100644 --- a/npm/freebsd-wasm32/package.json +++ b/npm/freebsd-wasm32/package.json @@ -21,9 +21,18 @@ }, "type": "commonjs", "exports": { - "./sharp.node": "./export/sharp.node.cjs", - "./package": "./export/package.cjs", - "./versions": "./export/versions.cjs" + "./sharp.node": { + "import": "./export/sharp.node.mjs", + "require": "./export/sharp.node.cjs" + }, + "./package": { + "import": "./export/package.mjs", + "require": "./export/package.cjs" + }, + "./versions": { + "import": "./export/versions.mjs", + "require": "./export/versions.cjs" + } }, "dependencies": { "@img/sharp-wasm32": "0.35.0-rc.2" @@ -34,4 +43,4 @@ "os": [ "freebsd" ] -} +} \ No newline at end of file diff --git a/npm/from-local-build.js b/npm/from-local-build.js index 49b27ec84..399d80ccc 100644 --- a/npm/from-local-build.js +++ b/npm/from-local-build.js @@ -8,7 +8,7 @@ const { copyFileSync, cpSync, readFileSync, writeFileSync, appendFileSync } = require('node:fs'); const { basename, join } = require('node:path'); -const { buildPlatformArch } = require('../lib/libvips'); +const { buildPlatformArch } = require('../dist/libvips.cjs'); const readme = readFileSync(join(__dirname, '..', 'README.md'), 'utf8'); const licensing = readme.substring(readme.indexOf('## Licensing')); diff --git a/npm/webcontainers-wasm32/export/package.mjs b/npm/webcontainers-wasm32/export/package.mjs new file mode 100644 index 000000000..d561aa57f --- /dev/null +++ b/npm/webcontainers-wasm32/export/package.mjs @@ -0,0 +1 @@ +export { default } from '@img/sharp-wasm32/package.json' with { type: 'json' }; diff --git a/npm/webcontainers-wasm32/export/sharp.node.mjs b/npm/webcontainers-wasm32/export/sharp.node.mjs new file mode 100644 index 000000000..006986282 --- /dev/null +++ b/npm/webcontainers-wasm32/export/sharp.node.mjs @@ -0,0 +1 @@ +export { default } from "@img/sharp-wasm32/sharp.node"; diff --git a/npm/webcontainers-wasm32/export/versions.mjs b/npm/webcontainers-wasm32/export/versions.mjs new file mode 100644 index 000000000..b53d54669 --- /dev/null +++ b/npm/webcontainers-wasm32/export/versions.mjs @@ -0,0 +1 @@ +export { default } from "@img/sharp-wasm32/versions.json" with { type: "json" }; diff --git a/npm/webcontainers-wasm32/package.json b/npm/webcontainers-wasm32/package.json index 7ad609906..61fa63c39 100644 --- a/npm/webcontainers-wasm32/package.json +++ b/npm/webcontainers-wasm32/package.json @@ -21,9 +21,18 @@ }, "type": "commonjs", "exports": { - "./sharp.node": "./export/sharp.node.cjs", - "./package": "./export/package.cjs", - "./versions": "./export/versions.cjs" + "./sharp.node": { + "import": "./export/sharp.node.mjs", + "require": "./export/sharp.node.cjs" + }, + "./package": { + "import": "./export/package.mjs", + "require": "./export/package.cjs" + }, + "./versions": { + "import": "./export/versions.mjs", + "require": "./export/versions.cjs" + } }, "dependencies": { "@img/sharp-wasm32": "0.35.0-rc.2" @@ -34,4 +43,4 @@ "cpu": [ "wasm32" ] -} +} \ No newline at end of file diff --git a/package.json b/package.json index 5d7020628..56f50f3b3 100644 --- a/package.json +++ b/package.json @@ -90,10 +90,12 @@ "Dennis Beatty ", "Ingvar Stepanyan ", "Don Denton ", - "Dmytro Tiapukhin " + "Dmytro Tiapukhin ", + "Florian Lefebvre " ], "scripts": { "build": "node install/build.js", + "build:dist": "node scripts/build.mjs", "clean": "rm -rf src/build/ test/fixtures/output.*", "test": "npm run lint && npm run test-unit", "lint": "npm run lint-cpp && npm run lint-js && npm run lint-types", @@ -110,13 +112,21 @@ "docs-publish": "cd docs && npm run build && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp" }, "type": "commonjs", - "main": "lib/index.js", - "types": "lib/index.d.ts", "files": [ + "dist", "install", - "lib", + "lib/index.d.ts", "src/*.{cc,h,gyp}" ], + "main": "./dist/index.cjs", + "module": "./dist/index.mjs", + "types": "./lib/index.d.ts", + "exports": { + ".": { + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" + } + }, "repository": { "type": "git", "url": "git://github.com/lovell/sharp.git" @@ -200,4 +210,4 @@ "funding": { "url": "https://opencollective.com/libvips" } -} +} \ No newline at end of file diff --git a/scripts/build.mjs b/scripts/build.mjs new file mode 100644 index 000000000..01845ad9f --- /dev/null +++ b/scripts/build.mjs @@ -0,0 +1,34 @@ +// @ts-check +import * as fs from "node:fs/promises"; + +const distDir = new URL("../dist/", import.meta.url); + +await fs.rm(distDir, { force: true, recursive: true }); +await fs.mkdir(new URL("../dist/", import.meta.url), { recursive: true }); + +const libDir = new URL("../lib/", import.meta.url); + +/** + * @param {string} input + * @returns {string} + */ +function cjsToEsm(input) { + return input + // Turn import into require() and .mjs into .cjs + .replace( + /import\s+(.+)\s+from\s+('[^']+'|"[^"]+")(?:\s+with\s+\{[^}]*\})?;?/g, + (_, bindings, path) => `const ${bindings} = require(${path.replace(".mjs", ".cjs")});`, + ) + .replace(/import\s+('[^']+'|"[^"]+")(?:\s+with\s+\{[^}]*\})?;?/g, (_, path) => `require(${path.replace(".mjs", ".cjs")});`) + // Transforms TLA + .replaceAll("await import(", "require(") + .replaceAll("export default", "module.exports =") +} + +const entries = (await fs.readdir(libDir, { recursive: true })).filter(e => e.endsWith('.mjs')); + +for (const entry of entries) { + await fs.cp(new URL(entry, libDir), new URL(entry, distDir)); + const contents = await fs.readFile(new URL(entry, libDir), "utf-8"); + await fs.writeFile(new URL(entry.replace(".mjs", ".cjs"), distDir), cjsToEsm(contents)); +} diff --git a/src/binding.gyp b/src/binding.gyp index 8ab773ec3..639943404 100644 --- a/src/binding.gyp +++ b/src/binding.gyp @@ -3,14 +3,14 @@ { 'variables': { - 'vips_version': ' path.join(__dirname, filename); diff --git a/test/unit/clahe.js b/test/unit/clahe.js index f3d68ebbb..ed00a5411 100644 --- a/test/unit/clahe.js +++ b/test/unit/clahe.js @@ -6,7 +6,7 @@ const { describe, it } = require('node:test'); const assert = require('node:assert'); -const sharp = require('../../lib'); +const sharp = require('../../dist/index.cjs'); const fixtures = require('../fixtures'); describe('Clahe', () => { diff --git a/test/unit/failOn.js b/test/unit/failOn.js index 7b58340d6..f7f0af842 100644 --- a/test/unit/failOn.js +++ b/test/unit/failOn.js @@ -7,7 +7,7 @@ const { describe, it } = require('node:test'); const assert = require('node:assert'); const fs = require('node:fs'); -const sharp = require('../../lib'); +const sharp = require('../../dist/index.cjs'); const fixtures = require('../fixtures'); describe('failOn', () => { diff --git a/test/unit/io.js b/test/unit/io.js index a18b56468..fca1c30f5 100644 --- a/test/unit/io.js +++ b/test/unit/io.js @@ -11,7 +11,7 @@ const { isMarkedAsUntransferable } = require('node:worker_threads'); const sharp = require('../../'); const fixtures = require('../fixtures'); -const { buildPlatformArch } = require('../../lib/libvips'); +const { buildPlatformArch } = require('../../dist/libvips.cjs'); const outputJpg = fixtures.path('output.jpg'); diff --git a/test/unit/libvips.js b/test/unit/libvips.js index 4a62fbbe8..0c0100560 100644 --- a/test/unit/libvips.js +++ b/test/unit/libvips.js @@ -7,7 +7,7 @@ const { after, before, describe, it } = require('node:test'); const assert = require('node:assert'); const fs = require('node:fs'); const semver = require('semver'); -const libvips = require('../../lib/libvips'); +const libvips = require('../../dist/libvips.cjs'); const originalPlatform = process.platform; diff --git a/test/unit/text.js b/test/unit/text.js index 029b45f1f..4c36e8f20 100644 --- a/test/unit/text.js +++ b/test/unit/text.js @@ -8,7 +8,7 @@ const assert = require('node:assert'); const sharp = require('../../'); const fixtures = require('../fixtures'); -const { inRange } = require('../../lib/is'); +const { inRange } = require('../../dist/is.cjs'); describe('Text to image', () => { it('text with default values', async (t) => { diff --git a/test/unit/trim.js b/test/unit/trim.js index f17582f9e..d7c8b8690 100644 --- a/test/unit/trim.js +++ b/test/unit/trim.js @@ -7,7 +7,7 @@ const { describe, it } = require('node:test'); const assert = require('node:assert'); const sharp = require('../../'); -const inRange = require('../../lib/is').inRange; +const inRange = require('../../dist/is.cjs').inRange; const fixtures = require('../fixtures'); describe('Trim borders', () => {