Repository navigation
feat!: add file transformers and migrate upload sizes to variants - #17827
Merged
Merged
Conversation
Contributor
📦 esbuild Bundle Analysis for payloadThis analysis was generated by esbuild-bundle-analyzer. 🤖
Largest pathsThese visualization shows top 20 largest paths in the bundle.Meta file: packages/next/meta_index.json, Out file: esbuild/index.js
Meta file: packages/payload/meta_index.json, Out file: esbuild/index.js
Meta file: packages/payload/meta_shared.json, Out file: esbuild/exports/shared.js
Meta file: packages/richtext-lexical/meta_client.json, Out file: esbuild/exports/client_optimized/index.js
Meta file: packages/ui/meta_client.json, Out file: esbuild/exports/client_optimized/index.js
Meta file: packages/ui/meta_shared.json, Out file: esbuild/exports/shared_optimized/index.js
DetailsNext to the size is how much the size has increased or decreased compared with the base branch of this PR.
|
paulpopus
marked this pull request as ready for review
August 20, 2026 18:53
paulpopus
requested review from
AlessioGr,
DanRibbens,
JarrodMFlesch,
denolfe and
jacobsfletch
as code owners
August 20, 2026 18:53
paulpopus
marked this pull request as draft
September 21, 2026 17:06
Resolves 37 conflicts between the file-transformer refactor and 141 commits of upload work on main. Notable semantic resolutions: - `generateFileData` keeps the transformer pipeline from this branch and main's large-client-upload handling. A transformer only runs when the full bytes are available (`hasFullFileContents`); otherwise the temp file is copied straight to its destination or skipped, never buffered. Dimension probing is likewise gated to image types, since probing reads the file. Main's filename-ownership, upload-reference, detected-mime, and external-upload-source fixes are preserved. - `cropImage`/`image-resizing` stay deleted; main's only change to them (the corrected animated-image mime list) already lives in core's `isAnimatedImage`. - `canResizeImage` is restored in core, which still needs it for `isProcessableImage` and `getFileContentRequirement`. - `getFileContentRequirement` now reads `upload.hasImageAdjustments` - the transformer-agnostic projection `sharpTransformer` writes back - instead of the removed per-collection Sharp options. - Storage adapters keep this branch's `operation: 'transform'` handler and main's `doc`-based prefix resolution (dropping the client-supplied `prefix` query param) and XML content-security-policy handling. Their specs move from the renamed `getFileKey` to `buildStoragePathData`. - Template `package.json` files keep main's dependency bumps and only drop `sharp` in favour of `@payloadcms/transformer-sharp`, so the lockfile differs from main solely by that new workspace package. - Test suites and fixtures added on either side are migrated to the other's conventions: `upload-transformers` and the shared animated-resize/transformer-contract helpers move to the `test.suite` fixture, and the `media-header-only-with-sizes` client-upload fixtures declare their `imageSizes` through `sharpTransformer`.
paulpopus
marked this pull request as ready for review
September 23, 2026 12:17
# Conflicts: # packages/codemod/README.md
…ingle-dimension resize
resolveUploadDocument looks up the filename without access filtering, and filenames are only unique per prefix. Without a ?prefix it could match another tenant's document, which was then passed as `doc` to storage handlers — they trust `doc` for the object key, so the other tenant's file was served. Use the document checkFileAccess authorized instead, re-planning the pipeline from its mimeType and re-checking transform access when needed.
paulpopus
commented
Oct 2, 2026
paulpopus
pushed a commit
that referenced
this pull request
Oct 5, 2026
> [!NOTE] > Part 3 of 3 in a stacked PR. See #17827 for the full description, breaking changes and migration. > 1. #17827 — tests, fixtures, test configuration and generated test types > 2. #18410 — Payload core, storage adapters, codemod, templates and documentation > 3. **This PR** — `@payloadcms/transformer-sharp`, its README, workspace registration and lockfile > > This is the top of the stack, where CI is expected to pass. ## Scope - New `@payloadcms/transformer-sharp` package and README: upload-time processing (`variants`, crop, focal point, format/trim/resize options, metadata) and opt-in dynamic resizing - Sharp logic moved out of `payload` (`getImageResizeAction`, `sanitizeResizeConfig`, `optionallyAppendMetadata`) - Workspace registration: `build:transformer-sharp` script, root `tsconfig.json` reference - `sharp` removed from `payload`, bumped `0.32.6` → `0.35.4`; lockfile
> [!NOTE] > Part 2 of 3 in a stacked PR. See #17827 for the full description, breaking changes and migration. > 1. #17827 — tests, fixtures, test configuration and generated test types > 2. **This PR** — Payload core, storage adapters, codemod, templates and documentation > 3. #18411 — `@payloadcms/transformer-sharp`, its README, workspace registration and lockfile ## Scope - `payload`: `upload.transformers` pipeline, dynamic file requests behind `access.read` / `req.fileTransform`, `generatePayloadFileURL`, removal of the built-in Sharp processing and Sharp-specific config/types - `@payloadcms/ui`: upload and file manager updates - Storage adapters and `plugin-cloud-storage`: internal `transform` file-handler operation - `@payloadcms/codemod`: `migrate-sharp-to-transformer` - `create-payload-app` and templates: migrated to `sharpTransformer` - Docs: `upload/transformers.mdx`, upload and storage adapter docs, v4 migration guide
|
Review the following changes in direct dependencies. Learn more about Socket for GitHub.
|
> [!NOTE] > Stacked on #18411. Draft. ### What? Upload documents now store generated image sizes under `variants` instead of `sizes`, matching the `variants` config option. ```diff - doc.sizes?.thumbnail?.url + doc.variants?.thumbnail?.url ``` ### How? - Renames the stored field and every place that reads or queries it, across core, the admin UI, the storage plugins, tests, templates and docs. - Adds a `sizes-to-variants` migration for each database adapter (MongoDB, Postgres, Vercel Postgres, SQLite, D1): `payload migrate:create --file @payloadcms/db-<adapter>/sizes-to-variants`. On SQL databases it renames the columns in place, so no data is lost. - Stops the predefined migration before it changes data or indexes when legacy `sizes` storage conflicts with custom `variants` storage. - Escapes custom SQL identifiers, makes SQLite index replacement safe to retry, and preserves and validates MongoDB index definitions, including partial filters and text-index weights. - Fixes the `db-postgres` and `db-vercel-postgres` builds, which shipped `migration-utils` importing a predefined-migration helper that was only published as `.mjs`, so importing `@payloadcms/db-postgres/migration-utils` failed. ### Breaking changes Payload 4 uses `variants` as the top-level field for generated upload variants. An upload collection can already define a custom field with this name. If a collection has a custom `variants` field, rename it before running the predefined migration: 1. Choose a new field name, such as `customVariants`. 2. Update the collection config to use the new name. 3. Write a custom migration that moves the existing custom data from `variants` to the new field. 4. Run the predefined `sizes-to-variants` migration after the custom data has moved. 5. Start Payload 4 only after both migrations succeed. The predefined migration cannot choose a name or merge custom `variants` data because Payload cannot determine the intended schema. It checks MongoDB documents, SQL columns, and SQL snapshots for conflicts and reports what must be moved before it can continue. A partly completed migration that contains only expected generated variant fields remains safe to retry. ### Testing - `test/sizes-to-variants` covers the migration on MongoDB, SQLite and Postgres, including camelCase variant names and running inside a transaction, the way `payload migrate` does. - Regression coverage includes custom `variants` collisions, quoted SQL identifiers, SQLite retry and rerun behaviour, MongoDB partial filters and index options, text indexes, and incompatible destination indexes. - End to end on blank projects outside the monorepo, upgrading a real Payload 3.90.2 project to this branch's packed packages: 1. Set up and seed with 3.x (`sharp` + `imageSizes`), using migrations for SQL. 2. Upgrade and run the `migrate-sharp-to-transformer` codemod. 3. Run the `sizes-to-variants` migration. 4. For SQL, generate a plain v4 migration and check it creates v4's new tables without dropping any `sizes`/`variants` columns. 5. Compare every stored size before and after, run runtime checks, then roll back with `migrate:down`, migrate up again and compare. | | Postgres | SQLite | MongoDB | | ------------------------------- | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | Config | drafts + localization, camelCase/webp sizes, custom `dbName`, a collection without sizes, upload relationship | versions without drafts, crop/focal point, `generateImageName`, upload in an array, `hasMany` upload | drafts + 3 locales, `generateImageName`, avif size, upload in a block, polymorphic `hasMany` upload | | Documents and versions compared | 15 | 10 | 16 | Runtime checks after the upgrade cover `where` and `select` on `variants.*`, generated files on disk, and new uploads. Index names match the v4 schema. ### Notes - The `templates/with-vercel-website` initial migration still creates `sizes_*` columns and needs regenerating. Written with AI --------- Co-authored-by: Paul Popus <[email protected]>
Written with AI
Written with AI
Written with AI
Written with AI
Written with AI
Written with AI
# Conflicts: # packages/create-payload-app/src/lib/init-tanstack.spec.ts # pnpm-lock.yaml
r1tsuu
approved these changes
Oct 6, 2026
paulpopus
added a commit
that referenced
this pull request
Oct 6, 2026
## Summary This PR updates the upload select unit test for the Payload 4 variants contract. The test now uses `upload.variants` and verifies `select.variants`. ## Why [#18414](#18414) added the test against the former `imageSizes` and `sizes` names. [#17827](#17827) merged after that test's last successful CI run and changed the production contract to `variants`. ## Validation - The complete unit suite passes with 3,625 tests. - The React Server Component suite passes with two tests. - The audit found no other test fixtures or select assertions that use the removed contract. - Prettier and `git diff --check` pass. Written with AI
Contributor
|
🚀 This is included in version v4.0.0-canary.38 |
denolfe
added a commit
that referenced
this pull request
Oct 28, 2026
`create-payload-app` generated v3-style storage and sharp config for v4 projects. This PR fixes both. It unblocks the [`post-release-templates` run](https://github.com/payloadcms/payload/actions/runs/40528045733/job/122273000849) that failed for `v4.0.0-beta.5` with `TypeError: plugin is not a function`. This PR supersedes the `create-payload-app` commit in #18991. It does not include that PR's template generator changes. Generated config for a template with sharp disabled: ```diff export default buildConfig({ - plugins: [vercelBlobStorage({ ... })], - upload: { - transformers: [sharpTransformer()], - }, + plugins: [], + storage: [vercelBlobStorage({ ... })], }) ``` ## Root Cause #16596 moved storage adapters from `plugins` to the `storage` config key. `buildConfig` calls each `plugins` entry as a function. A storage adapter in `plugins` throws `TypeError: plugin is not a function`. `addStorageAdapter` still inserted adapters into `plugins`. Its specs asserted that shape, so CI stayed green. #17827 moved image processing to `upload.transformers: [sharpTransformer()]`. `removeSharp` only removed the v3 `sharp` property and import. Templates generated with sharp disabled kept the transformer and its package. ## Changes - **Storage adapters go into `storage`** - `addStorageAdapter` finds or creates the `storage` array. It does not change `plugins`. - A shorthand `storage` property (`storage,` pointing at a variable) becomes `storage: [...storage, adapter]`. - A new `storage` property goes before trailing comments in the config object. Adding it after them produced `},,`. - **`removeSharp` handles `sharpTransformer`** - Removes the `@payloadcms/transformer-sharp` import and the `sharpTransformer()` entry in `upload.transformers`. - Removes `transformers` and `upload` when they become empty. Other transformers and upload options stay. - Removes the `@payloadcms/transformer-sharp` dependency from `package.json`. - **Generated configs are type-checked** - The AST integration spec type-checks each generated `payload.config.ts` against the workspace `payload` sources. It uses the template's own tsconfig, so no build is needed. - A storage adapter in `plugins` fails this check: `StorageAdapter` is not assignable to `Plugin`. - **Fixes found by the type check** - The `gcsStorage` config sets the required `options` (project ID and API endpoint). - The `website` and `with-vercel-website` templates fall back to `''` for `PAYLOAD_SECRET`. 🤖 Written with AI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR adds a general file transformer API, moves Sharp processing into a separate package, and renames generated upload sizes to variants.
Summary
Payload can now run ordered file transformers during uploads and file requests. Transformers can process uploaded files, serve request-time transformations, or support both operations.
The new
@payloadcms/transformer-sharppackage provides the existing Sharp upload processing. It also adds optional request-time image resizing.Image size configuration and stored upload data now use the term
variants. This PR includes a config codemod and predefined database migrations for existing projects.How
upload.transformersdefines an ordered transformer pipeline.generatePayloadFileURLbuilds URLs for the access-controlled Payload file endpoint.Breaking changes and migration
Follow these steps in order.
1. Move Sharp configuration
Install the new package:
The following configuration has been removed:
sharpconfig property.upload.imageSizes.upload.constructorOptions.upload.formatOptions.upload.resizeOptions.upload.trimOptions.upload.withMetadata.Configure these options through
sharpTransformer({ collections }). RenameimageSizestovariants.Before:
After:
The package includes Sharp. Pass
sharptosharpTransformer({ sharp })only when the project requires a specific Sharp build or version.Run the config codemod:
The codemod moves supported inline configuration and renames
imageSizestovariants. Review its notes because indirect or computed configuration can require manual changes.The following Sharp-specific types are no longer exported from
payload:SharpDependencyImageUploadFormatOptionsImageUploadTrimOptionsSharpImageSizeOptionsImport
SharpDependencyandSharpCollectionConfigfrom@payloadcms/transformer-sharp. Use properties ofSharpCollectionConfigwhen an individual option type is required.2. Rename stored
sizesdata tovariantsGenerated image data now uses
variantsin stored documents, Local API results, REST responses, GraphQL, queries, selections, and generated types.GraphQL queries must select
variantsinstead ofsizes. Regenerate project types after updating the config and database.Existing upload data requires the predefined
sizes-to-variantsmigration. The migration supports MongoDB, Postgres, Vercel Postgres, SQLite, and Cloudflare D1.For example, with Postgres:
Replace the database package with the package used by the project.
Do not use a plain generated migration for this rename on SQL databases. A plain migration can drop the
sizes_*columns and create emptyvariants_*columns.The predefined migration renames the columns, fields, and indexes in place. It also updates SQL migration snapshots.
If an upload collection already has a custom
variantsfield, rename that field and migrate its data first. The predefined migration stops before making changes when it detects conflicting custom data or storage.3. Account for file endpoint changes
Registering any transformer changes how every file request for its declared MIME types is handled, even when dynamic resizing is disabled.
404.access.readcan run once for transformed access and once for ordinary access.req.fileTransformistrueonly during the transformed access check.Use
generatePayloadFileURLwhen application code must link to the access-controlled file endpoint.Custom storage adapters receive
params.operation. Return the complete source body foroperation: 'transform'instead of returning an external redirect.Dynamic Sharp resizing
Dynamic resizing is opt-in:
Dynamic results are not stored or cached by Payload. Restrict allowed transformations through
access.read, set suitable size limits, and use external caching and rate limits where required.Documentation
Read the documentation in this order:
@payloadcms/transformer-sharpREADMEValidation coverage
Coverage includes transformer ordering, MIME matching, access modes, upload processing, dynamic requests, response headers, storage retrieval, and direct-to-storage uploads.
Migration coverage includes MongoDB, Postgres, and SQLite. It covers document versions, localized data, custom database names, custom
variantsconflicts, index preservation, retries, rollbacks, and partially completed migrations.Written with AI