Skip to content

feat!: add file transformers and migrate upload sizes to variants - #17827

Merged
paulpopus merged 59 commits into
mainfrom
feat/file-transformers
Oct 6, 2026
Merged

paulpopus merged 59 commits into
mainfrom
feat/file-transformers

Conversation

@paulpopus

@paulpopus paulpopus commented Aug 17, 2026 •

Copy link
Copy Markdown
Member

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-sharp package 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.transformers defines an ordered transformer pipeline.
  • Each transformer declares its MIME types and supported operations.
  • Upload transformations run before Payload writes the final file.
  • Request transformations run after collection read access succeeds.
  • First-party storage adapters can return source bytes without redirecting to a public or signed URL.
  • generatePayloadFileURL builds URLs for the access-controlled Payload file endpoint.
  • Dynamic Sharp resizing is disabled by default.

Breaking changes and migration

Follow these steps in order.

1. Move Sharp configuration

Install the new package:

pnpm add @payloadcms/transformer-sharp

The following configuration has been removed:

  • The top-level sharp config property.
  • upload.imageSizes.
  • upload.constructorOptions.
  • upload.formatOptions.
  • upload.resizeOptions.
  • upload.trimOptions.
  • upload.withMetadata.

Configure these options through sharpTransformer({ collections }). Rename imageSizes to variants.

Before:

import sharp from 'sharp'
import { buildConfig } from 'payload'

export default buildConfig({
  sharp,
  collections: [
    {
      slug: 'media',
      upload: {
        resizeOptions: {
          height: 2048,
          width: 2048,
        },
        imageSizes: [
          {
            height: 300,
            name: 'thumbnail',
            width: 400,
          },
        ],
      },
    },
  ],
})

After:

import { sharpTransformer } from '@payloadcms/transformer-sharp'
import { buildConfig } from 'payload'

export default buildConfig({
  collections: [
    {
      slug: 'media',
      upload: true,
    },
  ],
  upload: {
    transformers: [
      sharpTransformer({
        collections: {
          media: {
            resizeOptions: {
              height: 2048,
              width: 2048,
            },
            variants: [
              {
                height: 300,
                name: 'thumbnail',
                width: 400,
              },
            ],
          },
        },
      }),
    ],
  },
})

The package includes Sharp. Pass sharp to sharpTransformer({ sharp }) only when the project requires a specific Sharp build or version.

Run the config codemod:

npx @payloadcms/codemod --transform migrate-sharp-to-transformer

The codemod moves supported inline configuration and renames imageSizes to variants. Review its notes because indirect or computed configuration can require manual changes.

The following Sharp-specific types are no longer exported from payload:

  • SharpDependency
  • ImageUploadFormatOptions
  • ImageUploadTrimOptions
  • SharpImageSizeOptions

Import SharpDependency and SharpCollectionConfig from @payloadcms/transformer-sharp. Use properties of SharpCollectionConfig when an individual option type is required.

2. Rename stored sizes data to variants

Generated image data now uses variants in stored documents, Local API results, REST responses, GraphQL, queries, selections, and generated types.

- media.sizes?.thumbnail?.url
+ media.variants?.thumbnail?.url

- where: { 'sizes.thumbnail.filename': { equals: filename } }
+ where: { 'variants.thumbnail.filename': { equals: filename } }

- select: { sizes: { thumbnail: true } }
+ select: { variants: { thumbnail: true } }

GraphQL queries must select variants instead of sizes. Regenerate project types after updating the config and database.

Existing upload data requires the predefined sizes-to-variants migration. The migration supports MongoDB, Postgres, Vercel Postgres, SQLite, and Cloudflare D1.

For example, with Postgres:

payload migrate:create --file @payloadcms/db-postgres/sizes-to-variants
payload migrate

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 empty variants_* 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 variants field, 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.

  • A stored file must belong to an upload document. An unowned file now returns 404.
  • access.read can run once for transformed access and once for ordinary access.
  • req.fileTransform is true only during the transformed access check.
  • No transformer or storage retrieval runs before access succeeds.
  • Transformer responses always include Payload CORS headers.
  • Direct storage URLs bypass Payload access control.

Use generatePayloadFileURL when application code must link to the access-controlled file endpoint.

Custom storage adapters receive params.operation. Return the complete source body for operation: 'transform' instead of returning an external redirect.

Dynamic Sharp resizing

Dynamic resizing is opt-in:

sharpTransformer({
  dynamic: {
    collections: ['media'],
    maxHeight: 1280,
    maxWidth: 1280,
    withoutEnlargement: true,
  },
})

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:

  1. Payload 3 to 4 migration guide
  2. Upload overview
  3. File transformer API
  4. Storage adapter integration
  5. @payloadcms/transformer-sharp README

Validation 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 variants conflicts, index preservation, retries, rollbacks, and partially completed migrations.

Written with AI

@paulpopus paulpopus changed the title feat: file transformers feat!: file transformers Aug 17, 2026
@paulpopus paulpopus changed the title feat!: file transformers feat!: add dynamic image resizing and support for file transformers adapters Aug 18, 2026
@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

📦 esbuild Bundle Analysis for payload

This analysis was generated by esbuild-bundle-analyzer. 🤖

Meta File Out File Size (raw) Note
packages/next/meta_index.json esbuild/index.js 216.84 KB ⚠️ +2.07 KB (+1.0%)
packages/payload/meta_index.json esbuild/index.js 1.88 MB ⚠️ +92.00 KB (+5.1%)
packages/payload/meta_shared.json esbuild/exports/shared.js 563.49 KB ⚠️ +14.18 KB (+2.6%)
packages/richtext-lexical/meta_client.json esbuild/exports/client_optimized/index.js 296.15 KB ⚠️ +9.65 KB (+3.4%)
packages/ui/meta_client.json esbuild/exports/client_optimized/index.js 36.90 KB ⚠️ +360 B (+1.0%)
packages/ui/meta_shared.json esbuild/exports/shared_optimized/index.js 18.98 KB ⚠️ +34 B (+0.2%)
Largest paths These visualization shows top 20 largest paths in the bundle.

Meta file: packages/next/meta_index.json, Out file: esbuild/index.js

Path Size
../../node_modules ${{\color{Goldenrod}{ ████████████████████████▋ }}}$ 98.8%, 212.32 KB
dist/adapters/router.js ${{\color{Goldenrod}{ }}}$ 0.3%, 718 B
dist/adapters/server.js ${{\color{Goldenrod}{ }}}$ 0.2%, 533 B
dist/adapters/layout.js ${{\color{Goldenrod}{ }}}$ 0.2%, 529 B
dist/adapters/views.js ${{\color{Goldenrod}{ }}}$ 0.2%, 324 B
dist/utilities/initAdminContext.js ${{\color{Goldenrod}{ }}}$ 0.1%, 315 B
dist/utilities/selectiveCache.js ${{\color{Goldenrod}{ }}}$ 0.1%, 263 B
dist/esbuildEntry.js ${{\color{Goldenrod}{ }}}$ 0.0%, 0 B

Meta file: packages/payload/meta_index.json, Out file: esbuild/index.js

Path Size
../../node_modules ${{\color{Goldenrod}{ █████████████████▉ }}}$ 71.7%, 1.34 MB
dist/collections/operations ${{\color{Goldenrod}{ ▋ }}}$ 2.9%, 54.67 KB
dist/fields/hooks ${{\color{Goldenrod}{ ▋ }}}$ 2.5%, 46.14 KB
dist/auth/operations ${{\color{Goldenrod}{ ▏ }}}$ 0.9%, 16.95 KB
dist/globals/operations ${{\color{Goldenrod}{ ▏ }}}$ 0.9%, 16.18 KB
dist/utilities/configToJSONSchema.js ${{\color{Goldenrod}{ ▏ }}}$ 0.9%, 16.02 KB
dist/queues/operations ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 14.31 KB
dist/fields/config ${{\color{Goldenrod}{ ▏ }}}$ 0.7%, 13.65 KB
dist/utilities/telemetry ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 11.88 KB
dist/collections/config ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 10.98 KB
dist/fields/validations.js ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 10.82 KB
dist/cli/commands ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 9.92 KB
dist/config/orderable ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 8.76 KB
dist/uploads/fetchAPI-multipart ${{\color{Goldenrod}{ }}}$ 0.4%, 8.38 KB
dist/database/migrations ${{\color{Goldenrod}{ }}}$ 0.4%, 8.16 KB
dist/config/sanitize.js ${{\color{Goldenrod}{ }}}$ 0.4%, 8.01 KB
dist/hierarchy/utils ${{\color{Goldenrod}{ }}}$ 0.4%, 7.66 KB
dist/index.js ${{\color{Goldenrod}{ }}}$ 0.4%, 7.54 KB
dist/auth/strategies ${{\color{Goldenrod}{ }}}$ 0.4%, 7.36 KB
dist/utilities/entityInputSchema ${{\color{Goldenrod}{ }}}$ 0.4%, 7.34 KB
(other) ${{\color{Goldenrod}{ ███████ }}}$ 28.3%, 529.33 KB

Meta file: packages/payload/meta_shared.json, Out file: esbuild/exports/shared.js

Path Size
../../node_modules ${{\color{Goldenrod}{ ██████████████████████▏ }}}$ 88.8%, 495.80 KB
dist/fields/validations.js ${{\color{Goldenrod}{ ▍ }}}$ 1.9%, 10.79 KB
dist/fields/config ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 5.83 KB
dist/utilities/traverseFields.js ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 4.34 KB
dist/utilities/deepCopyObject.js ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 3.52 KB
dist/collections/config ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 3.40 KB
dist/config/orderable ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 3.13 KB
dist/fields/baseFields ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 2.79 KB
dist/config/client.js ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 2.56 KB
dist/auth/cookies.js ${{\color{Goldenrod}{ }}}$ 0.3%, 1.55 KB
dist/utilities/flattenTopLevelFields.js ${{\color{Goldenrod}{ }}}$ 0.3%, 1.42 KB
dist/utilities/getVersionsConfig.js ${{\color{Goldenrod}{ }}}$ 0.2%, 1.04 KB
dist/globals/config ${{\color{Goldenrod}{ }}}$ 0.2%, 939 B
dist/uploads/generatePayloadFileURL.js ${{\color{Goldenrod}{ }}}$ 0.2%, 864 B
dist/utilities/unflatten.js ${{\color{Goldenrod}{ }}}$ 0.2%, 850 B
dist/utilities/flattenAllFields.js ${{\color{Goldenrod}{ }}}$ 0.1%, 798 B
dist/utilities/sanitizeUserDataForEmail.js ${{\color{Goldenrod}{ }}}$ 0.1%, 713 B
dist/auth/extractJWT.js ${{\color{Goldenrod}{ }}}$ 0.1%, 696 B
dist/utilities/getFieldPermissions.js ${{\color{Goldenrod}{ }}}$ 0.1%, 651 B
dist/utilities/fieldPath.js ${{\color{Goldenrod}{ }}}$ 0.1%, 639 B
(other) ${{\color{Goldenrod}{ ██▊ }}}$ 11.2%, 62.77 KB

Meta file: packages/richtext-lexical/meta_client.json, Out file: esbuild/exports/client_optimized/index.js

Path Size
dist/features/blocks ${{\color{Goldenrod}{ ███▋ }}}$ 14.6%, 42.74 KB
dist/lexical/plugins ${{\color{Goldenrod}{ ██▉ }}}$ 11.8%, 34.51 KB
dist/lexical/ui ${{\color{Goldenrod}{ ██▊ }}}$ 11.4%, 33.54 KB
dist/features/table ${{\color{Goldenrod}{ ██▎ }}}$ 9.4%, 27.46 KB
dist/features/link ${{\color{Goldenrod}{ █▋ }}}$ 6.5%, 18.92 KB
dist/features/toolbars ${{\color{Goldenrod}{ █▌ }}}$ 6.3%, 18.41 KB
dist/features/upload ${{\color{Goldenrod}{ █▏ }}}$ 4.9%, 14.28 KB
dist/features/textState ${{\color{Goldenrod}{ ▉ }}}$ 3.8%, 11.08 KB
dist/lexical/utils ${{\color{Goldenrod}{ ▊ }}}$ 3.4%, 10.02 KB
dist/features/relationship ${{\color{Goldenrod}{ ▊ }}}$ 3.2%, 9.43 KB
dist/features/converters ${{\color{Goldenrod}{ ▋ }}}$ 2.9%, 8.41 KB
dist/utilities/fieldsDrawer ${{\color{Goldenrod}{ ▋ }}}$ 2.8%, 8.12 KB
dist/features/debug ${{\color{Goldenrod}{ ▋ }}}$ 2.5%, 7.40 KB
dist/lexical/config ${{\color{Goldenrod}{ ▍ }}}$ 1.8%, 5.14 KB
dist/features/indent ${{\color{Goldenrod}{ ▎ }}}$ 1.4%, 4.19 KB
dist/features/lists ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 3.67 KB
dist/lexical/LexicalEditor.js ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 3.33 KB
dist/features/format ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 3.28 KB
dist/features/horizontalRule ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 3.18 KB
dist/field/Field.js ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 3.05 KB
(other) ${{\color{Goldenrod}{ █████████████████████▎ }}}$ 85.4%, 250.20 KB

Meta file: packages/ui/meta_client.json, Out file: esbuild/exports/client_optimized/index.js

Path Size
dist/exports/client ${{\color{Goldenrod}{ █████████████████████████ }}}$ 100.0%, 27.17 KB

Meta file: packages/ui/meta_shared.json, Out file: esbuild/exports/shared_optimized/index.js

Path Size
dist/graphics/Logo ${{\color{Goldenrod}{ ███████▋ }}}$ 30.7%, 5.61 KB
../../node_modules ${{\color{Goldenrod}{ ███▌ }}}$ 14.5%, 2.65 KB
dist/graphics/Icon ${{\color{Goldenrod}{ ██ }}}$ 8.3%, 1.51 KB
dist/utilities/formatDocTitle ${{\color{Goldenrod}{ █▊ }}}$ 7.2%, 1.32 KB
dist/providers/TableColumns ${{\color{Goldenrod}{ █▏ }}}$ 4.7%, 866 B
dist/utilities/getGlobalData.js ${{\color{Goldenrod}{ █ }}}$ 4.2%, 762 B
dist/utilities/api.js ${{\color{Goldenrod}{ █ }}}$ 4.1%, 756 B
dist/utilities/groupNavItems.js ${{\color{Goldenrod}{ █ }}}$ 4.1%, 745 B
dist/elements/Translation ${{\color{Goldenrod}{ ▋ }}}$ 2.7%, 493 B
dist/utilities/handleTakeOver.js ${{\color{Goldenrod}{ ▌ }}}$ 2.4%, 440 B
dist/utilities/traverseForLocalizedFields.js ${{\color{Goldenrod}{ ▌ }}}$ 2.3%, 419 B
dist/elements/withMergedProps ${{\color{Goldenrod}{ ▍ }}}$ 1.9%, 339 B
dist/utilities/getNavGroups.js ${{\color{Goldenrod}{ ▍ }}}$ 1.8%, 338 B
dist/utilities/getVisibleEntities.js ${{\color{Goldenrod}{ ▍ }}}$ 1.8%, 329 B
dist/elements/WithServerSideProps ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 232 B
dist/layouts/Root ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 230 B
dist/utilities/handleGoBack.js ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 180 B
dist/fields/mergeFieldStyles.js ${{\color{Goldenrod}{ ▏ }}}$ 0.9%, 158 B
dist/forms/Form ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 152 B
dist/utilities/handleBackToDashboard.js ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 152 B
(other) ${{\color{Goldenrod}{ █████████████████▎ }}}$ 69.3%, 12.68 KB
Details

Next to the size is how much the size has increased or decreased compared with the base branch of this PR.

  • ‼️: Size increased by 20% or more. Special attention should be given to this.
  • ⚠️: Size increased in acceptable range (lower than 20%).
  • ✅: No change or even downsized.
  • 🗑️: The out file is deleted: not found in base branch.
  • 🆕: The out file is newly found: will be added to base branch.

@paulpopus
paulpopus marked this pull request as ready for review August 20, 2026 18:53
@paulpopus
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
paulpopus marked this pull request as ready for review September 23, 2026 12:17
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.
Comment thread test/upload-transformers/e2e.spec.ts Resolved
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
@socket-security

socket-security Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Added@​payloadcms/​transformer-sharp@​3.82.1N/AN/AN/AN/AN/A

View full report

r1tsuu and others added 2 commits October 5, 2026 12:55
> [!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]>
@paulpopus paulpopus changed the title feat!: add dynamic image resizing and support for file transformers adapters feat!: add file transformers, support for dynamic transforms and migrate upload sizes to variants Oct 5, 2026
@paulpopus paulpopus changed the title feat!: add file transformers, support for dynamic transforms and migrate upload sizes to variants feat!: add file transformers and migrate upload sizes to variants Oct 5, 2026
@paulpopus
paulpopus merged commit ed0e138 into main Oct 6, 2026
285 checks passed
@paulpopus
paulpopus deleted the feat/file-transformers branch October 6, 2026 14:35
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
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants