@jhb.software/payload-alt-text-plugin 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +275 -20
  2. package/dist/endpoints/bulkGenerateAltTexts.js +21 -8
  3. package/dist/endpoints/bulkGenerateAltTexts.js.map +1 -1
  4. package/dist/endpoints/generateAltText.js +16 -5
  5. package/dist/endpoints/generateAltText.js.map +1 -1
  6. package/dist/hooks/revalidateAltTextHealth.js +31 -17
  7. package/dist/hooks/revalidateAltTextHealth.js.map +1 -1
  8. package/dist/index.d.ts +8 -1
  9. package/dist/index.js +3 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/plugin.js +43 -7
  12. package/dist/plugin.js.map +1 -1
  13. package/dist/resolvers/anthropic.d.ts +65 -0
  14. package/dist/resolvers/anthropic.js +141 -0
  15. package/dist/resolvers/anthropic.js.map +1 -0
  16. package/dist/resolvers/createVisionResolver.d.ts +148 -0
  17. package/dist/resolvers/createVisionResolver.js +300 -0
  18. package/dist/resolvers/createVisionResolver.js.map +1 -0
  19. package/dist/resolvers/mistral.d.ts +53 -0
  20. package/dist/resolvers/mistral.js +114 -0
  21. package/dist/resolvers/mistral.js.map +1 -0
  22. package/dist/resolvers/openAI.d.ts +32 -3
  23. package/dist/resolvers/openAI.js +63 -144
  24. package/dist/resolvers/openAI.js.map +1 -1
  25. package/dist/resolvers/types.d.ts +24 -1
  26. package/dist/resolvers/types.js.map +1 -1
  27. package/dist/translations/index.js.map +1 -1
  28. package/dist/types/AltTextPluginConfig.d.ts +86 -18
  29. package/dist/types/AltTextPluginConfig.js.map +1 -1
  30. package/dist/utilities/altTextHealth.d.ts +3 -1
  31. package/dist/utilities/altTextHealth.js +74 -8
  32. package/dist/utilities/altTextHealth.js.map +1 -1
  33. package/dist/utilities/mimeTypes.d.ts +54 -1
  34. package/dist/utilities/mimeTypes.js +41 -2
  35. package/dist/utilities/mimeTypes.js.map +1 -1
  36. package/dist/utilities/stableStringify.d.ts +9 -0
  37. package/dist/utilities/stableStringify.js +19 -0
  38. package/dist/utilities/stableStringify.js.map +1 -0
  39. package/package.json +14 -15
package/README.md CHANGED
@@ -6,11 +6,12 @@ A [Payload CMS](https://payloadcms.com/) plugin that adds AI-powered alt text ge
6
6
 
7
7
  - Generate alt text for images using AI in the Payload Admin UI
8
8
  - Supports any AI provider using a resolver pattern (e.g., OpenAI, Anthropic, etc.)
9
- - Comes with a ready-to-use OpenAI resolver out of the box
9
+ - Comes with ready-to-use OpenAI, Anthropic and Mistral resolvers out of the box
10
10
  - Automatic keyword extraction for improved admin search
11
11
  - Bulk generation for processing multiple images at once
12
12
  - Full localization support
13
13
  - Dashboard health widget with cached coverage insights across all configured upload collections
14
+ - Multi-tenant aware: the health report can be scoped to the tenant the request is for
14
15
 
15
16
  When the plugin is enabled for an upload collection, it will:
16
17
 
@@ -77,27 +78,43 @@ This is also the recommended escape hatch if you hit Payload's Postgres SQL-buil
77
78
 
78
79
  ### Plugin Options
79
80
 
80
- | Option | Type | Required | Description |
81
- | ---------------------------- | ------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
82
- | `collections` | `(CollectionSlug \| CollectionObj)[]` | Yes | Collections to enable alt text generation for (see [Per-collection options](#per-collection-options)) |
83
- | `resolver` | `AltTextResolver` | Yes | Alt text resolver to use (e.g., `openAIResolver`) |
84
- | `getImageThumbnail` | `Function` | Yes | Function to get the thumbnail URL from an image document |
85
- | `enabled` | `boolean` | No | Whether to enable the plugin |
86
- | `locale` | `string` | No | Locale for alt text generation (required when localization is disabled) |
87
- | `maxBulkGenerateConcurrency` | `number` | No | Maximum concurrent API requests for bulk operations (default: 16) |
88
- | `maxBulkGenerateIds` | `number` | No | Maximum number of image IDs accepted per bulk generate request; larger requests are rejected with `400`. Duplicate IDs are collapsed before the limit is applied (default: 100) |
89
- | `fieldsOverride` | `Function` | No | Override the default fields inserted by the plugin |
90
- | `healthCheck` | `boolean \| Function` | No | Alt text health tracking (REST endpoint, cache revalidation hooks, dashboard widget). `false` disables it; `true` enables it gated by `access`; a `({ req }) => boolean` function enables it and gates both the endpoint and the widget — use it to restrict the collection-wide report, e.g. to admins (default: `true`) |
81
+ | Option | Type | Required | Description |
82
+ | ---------------------------- | ------------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
83
+ | `collections` | `(CollectionSlug \| CollectionObj)[]` | Yes | Collections to enable alt text generation for (see [Per-collection options](#per-collection-options)) |
84
+ | `resolver` | `AltTextResolver` | Yes | Alt text resolver to use (e.g., `openAIResolver`) |
85
+ | `getImageThumbnail` | `Function` | Yes | Function to get the thumbnail URL from an image document |
86
+ | `enabled` | `boolean` | No | Whether to enable the plugin |
87
+ | `access` | `({ req }) => boolean \| Promise<boolean>` | No | Access control for the plugin's REST endpoints. Defaults to `({ req }) => !!req.user` (any authenticated user) — see [Authentication](#authentication) |
88
+ | `locale` | `string` | No | Locale for alt text generation (required when localization is disabled) |
89
+ | `maxBulkGenerateConcurrency` | `number` | No | Maximum concurrent API requests for bulk operations (default: 16) |
90
+ | `maxBulkGenerateIds` | `number` | No | Maximum number of image IDs accepted per bulk generate request; larger requests are rejected with `400`. Duplicate IDs are collapsed before the limit is applied (default: 100) |
91
+ | `fieldsOverride` | `Function` | No | Override the default fields inserted by the plugin |
92
+ | `healthCheck` | `boolean \| AltTextHealthCheckConfig` | No | Alt text health tracking (REST endpoint, cache revalidation hooks, dashboard widget). `false` disables it; `true` enables it for every document, gated by `access`; an object enables it and configures its `access` gate and `baseFilter` (see [Health report](#dashboard-widget)) (default: `true`) |
93
+ | `imageThumbnailMimeType` | `string` | No | The MIME type `getImageThumbnail` delivers. Set it when your thumbnail URL transcodes the image, so the stored format no longer decides whether generation is possible (see [Transcoding thumbnails](#transcoding-thumbnails)) |
94
+
95
+ `getImageThumbnail` receives the document and `{ collection, req }`, so a single function can build different URLs per collection:
96
+
97
+ ```ts
98
+ getImageThumbnail: (doc, { collection }) =>
99
+ collection === 'media' ? cloudinaryThumbnail(doc) : String(doc.url)
100
+ ```
101
+
102
+ It may also be async, so the URL can be signed on demand:
103
+
104
+ ```ts
105
+ getImageThumbnail: async (doc, { req }) => await presignThumbnailUrl(String(doc.url), req)
106
+ ```
91
107
 
92
108
  ### Per-collection options
93
109
 
94
110
  Each entry in `collections` may be either a bare collection slug (shorthand, defaults to `['image/*']` for `mimeTypes`) or an object with the following fields:
95
111
 
96
- | Option | Type | Required | Description |
97
- | ----------- | ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
98
- | `slug` | `CollectionSlug` | Yes | The collection slug |
99
- | `mimeTypes` | `string[]` | No | MIME types the plugin tracks, validates, and generates for. Supports wildcards like `image/*`. Defaults to `['image/*']`. |
100
- | `validate` | `TextareaFieldValidation` | No | Custom validator that fully replaces the default required-alt check. Import `validateAltText` from the plugin to compose around the default behavior (see [Custom validator](#custom-validator)). |
112
+ | Option | Type | Required | Description |
113
+ | ------------------------ | ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
114
+ | `slug` | `CollectionSlug` | Yes | The collection slug |
115
+ | `mimeTypes` | `string[]` | No | MIME types the plugin tracks, validates, and generates for. Supports wildcards like `image/*`. Defaults to `['image/*']`. |
116
+ | `validate` | `TextareaFieldValidation` | No | Custom validator that fully replaces the default required-alt check. Import `validateAltText` from the plugin to compose around the default behavior (see [Custom validator](#custom-validator)). |
117
+ | `imageThumbnailMimeType` | `string \| null` | No | Overrides the plugin-level option of the same name for this collection. `null` opts the collection out of a plugin-level default (see [Transcoding thumbnails](#transcoding-thumbnails)). |
101
118
 
102
119
  ```ts
103
120
  payloadAltTextPlugin({
@@ -109,6 +126,39 @@ payloadAltTextPlugin({
109
126
  })
110
127
  ```
111
128
 
129
+ #### Transcoding thumbnails
130
+
131
+ The resolver never sees the stored file — it only receives the URL returned by `getImageThumbnail`. When a resolver declares `supportedMimeTypes`, the plugin checks a document's stored `mimeType` against that list, which is a safe default but wrong as soon as your thumbnail URL transcodes: an AVIF or HEIC upload served through a Cloudinary `f_webp` transformation reaches the provider as WebP, yet gets rejected on its stored format.
132
+
133
+ Declare what your thumbnail URL actually delivers to remove the mismatch:
134
+
135
+ ```ts
136
+ payloadAltTextPlugin({
137
+ collections: ['media'],
138
+ resolver: openAIResolver({ apiKey: process.env.OPENAI_API_KEY }),
139
+ // Always transcodes to WebP, whatever the source format is
140
+ getImageThumbnail: (doc) => String(doc.url).replace('/upload/', '/upload/w_600,f_webp/'),
141
+ imageThumbnailMimeType: 'image/webp',
142
+ })
143
+ ```
144
+
145
+ With the declaration in place, the source format no longer gates generation — the admin button stays enabled and the endpoints stop rejecting on `mimeType`. Which source formats get alt text at all is still governed by each collection's `mimeTypes`. The declaration is validated against the resolver's `supportedMimeTypes` once at config load, so transcoding into a format your resolver cannot handle fails at boot instead of once per image.
146
+
147
+ Only declare a format your transformation **always** produces. A `f_auto`-style transformation negotiates the format from the fetching client's `Accept` header and may serve the source format back, so leave it unset there and let the conservative source check apply. If you want AVIF sources to work, transcode explicitly.
148
+
149
+ Collections may override the plugin-level value, or opt out of it with `null` when they are served raw:
150
+
151
+ ```ts
152
+ payloadAltTextPlugin({
153
+ collections: [
154
+ 'media', // inherits image/webp
155
+ { slug: 'documents', imageThumbnailMimeType: null }, // checked on its stored mimeType
156
+ ],
157
+ imageThumbnailMimeType: 'image/webp',
158
+ // ...
159
+ })
160
+ ```
161
+
112
162
  #### Custom validator
113
163
 
114
164
  The default validator requires alt text on every tracked document. Some workflows — folder moves, partial API updates, or localized setups with `fallback: false` where some locales are intentionally empty — need to skip that check when the request body does not touch `alt`. Pass a `validate` function to override the default, and compose around the exported `validateAltText` to keep the standard behavior for full updates:
@@ -156,6 +206,44 @@ buildConfig({
156
206
 
157
207
  Set `healthCheck: false` in the plugin config to disable the REST endpoint, cache revalidation hooks, and dashboard widget. If your project replaces the default dashboard via `admin.components.views.dashboard`, you need to integrate the widget into your custom dashboard yourself.
158
208
 
209
+ #### Gating and scoping the report
210
+
211
+ `healthCheck` also takes an object. The main use of `baseFilter` is multi-tenancy: scope the report to the tenant selected in the admin panel, whose id [@payloadcms/plugin-multi-tenant](https://payloadcms.com/docs/plugins/multi-tenant) keeps in the `payload-tenant` cookie.
212
+
213
+ ```ts
214
+ import { getTenantFromCookie } from '@payloadcms/plugin-multi-tenant/utilities'
215
+
216
+ healthCheck: {
217
+ // Restrict the collection-wide report more strictly than the per-document
218
+ // generate endpoints. Gates the REST endpoint and hides the widget.
219
+ access: ({ req }) => req.user?.role === 'admin',
220
+ // Narrow what the report counts, e.g. to the tenant selected in the admin panel.
221
+ baseFilter: ({ collection, req }) => {
222
+ const tenant = getTenantFromCookie(req.headers, req.payload.db.defaultIDType)
223
+
224
+ return tenant ? { tenant: { equals: tenant } } : {}
225
+ },
226
+ }
227
+ ```
228
+
229
+ `baseFilter` returns a `Where` that is ANDed onto the scan's MIME type filter. It is resolved once per configured collection, so a collection that does not carry the constraining field — a media library shared across tenants, say — can return `{}` and be scanned whole. Returning `{}` for every collection is the default behaviour.
230
+
231
+ The scan is cached across requests, and its cache key is derived from the resolved filters: a narrowed scan always gets its own cache entry, so one tenant's counts can never be served to another. Cache invalidation stays per collection, so a write in one tenant refreshes the report for all of them.
232
+
233
+ This scopes what the report counts, not who may see it — use `access` for that. Independently of both, the report always omits the collections the requesting user cannot read.
234
+
235
+ #### Skipping cache revalidation for individual writes
236
+
237
+ The plugin invalidates the cached health scan via `afterChange` and `afterDelete` hooks. For writes that don't need to invalidate the cache — typically seed data created from `payload.onInit`, batch imports, or migrations — pass `context: { disableRevalidate: true }` to skip the revalidation:
238
+
239
+ ```ts
240
+ await payload.create({
241
+ collection: 'media',
242
+ data: {/* ... */},
243
+ context: { disableRevalidate: true },
244
+ })
245
+ ```
246
+
159
247
  ### Resolvers
160
248
 
161
249
  This plugin is designed to work seamlessly with various AI providers by accepting a customizable resolver as a configuration option.
@@ -173,16 +261,166 @@ openAIResolver({
173
261
  })
174
262
  ```
175
263
 
264
+ | Option | Type | Required | Description |
265
+ | -------------------- | ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
266
+ | `apiKey` | `string` | Yes | API key for authentication |
267
+ | `model` | `string` | No | Model to use (default: `gpt-4.1-nano`) |
268
+ | `baseUrl` | `string` | No | Base URL for an OpenAI-compatible provider, version segment included (default: `https://api.openai.com/v1`; e.g. Nebius, Azure) |
269
+ | `supportedMimeTypes` | `string[]` | No | Image formats the provider accepts (default: `['image/jpeg', 'image/png', 'image/gif', 'image/webp']`, per OpenAI's vision docs). Override it when using a `baseUrl` whose provider differs |
270
+ | `timeoutMs` | `number` | No | Abort after this many milliseconds, retries included (default: `30000`) |
271
+ | `instructions` | `function` | No | Customizes the prompt, see [Customizing the instructions](#customizing-the-instructions) |
272
+
273
+ #### Mistral Resolver
274
+
275
+ ```ts
276
+ import { mistralResolver } from '@jhb.software/payload-alt-text-plugin'
277
+
278
+ mistralResolver({
279
+ apiKey: process.env.MISTRAL_API_KEY,
280
+ model: 'mistral-medium-latest', // default; any vision-capable Mistral model works
281
+ })
282
+ ```
283
+
284
+ Unlike the OpenAI resolver, this one downloads the image and sends the bytes
285
+ rather than handing Mistral the thumbnail URL. Mistral's own fetcher needs the
286
+ file to be reachable from the public internet, which is never the case in local
287
+ development and not the case for private buckets; some hosts also refuse it
288
+ outright (`File could not be fetched from url`, error 3310). Sending the bytes
289
+ costs one extra download and removes that whole class of failure.
290
+
291
+ Because there is no image conversion step, `supportedMimeTypes` is limited to
292
+ what the Mistral API accepts directly: JPEG, PNG, GIF and WebP. Documents in
293
+ other formats — SVG or AVIF, for instance — keep their generate button disabled.
294
+
295
+ | Option | Type | Required | Description |
296
+ | -------------- | ---------- | -------- | ---------------------------------------------------------------------------------------- |
297
+ | `apiKey` | `string` | Yes | API key for authentication |
298
+ | `model` | `string` | No | Model to use (default: `mistral-medium-latest`) |
299
+ | `baseUrl` | `string` | No | Base URL of the Mistral API (default: `https://api.mistral.ai/v1`) |
300
+ | `timeoutMs` | `number` | No | Abort after this many milliseconds, image download included (default: `30000`) |
301
+ | `instructions` | `function` | No | Customizes the prompt, see [Customizing the instructions](#customizing-the-instructions) |
302
+
303
+ #### Anthropic Resolver
304
+
305
+ ```ts
306
+ import { anthropicResolver } from '@jhb.software/payload-alt-text-plugin'
307
+
308
+ anthropicResolver({
309
+ apiKey: process.env.ANTHROPIC_API_KEY,
310
+ model: 'claude-opus-5', // default; `claude-sonnet-5` is cheaper for a large library
311
+ effort: 'low', // optional; describing an image needs little thinking
312
+ })
313
+ ```
314
+
315
+ Like the Mistral resolver, this one downloads the image and sends the bytes.
316
+ Claude can fetch an image URL itself, but that requires the file to be reachable
317
+ from the public internet, which is never the case in local development and not
318
+ the case for private buckets. Sending the bytes also supplies the `media_type`
319
+ that a base64 image block requires and a URL cannot carry.
320
+
321
+ `supportedMimeTypes` is limited to what the Messages API accepts: JPEG, PNG, GIF
322
+ and WebP. Documents in other formats keep their generate button disabled.
323
+
324
+ | Option | Type | Required | Description |
325
+ | -------------- | ------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
326
+ | `apiKey` | `string` | Yes | API key for authentication |
327
+ | `model` | `string` | No | Model to use (default: `claude-opus-5`). `claude-sonnet-5` is cheaper; `claude-haiku-4-5` works too, but only without `effort` |
328
+ | `effort` | `'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max'` | No | How long Claude thinks before answering. `low` is plenty for describing an image and keeps the spend down. Omitted, the field is not sent and Claude uses its default (`high`), so models without effort support stay usable |
329
+ | `baseUrl` | `string` | No | Base URL of the Anthropic API (default: `https://api.anthropic.com`) |
330
+ | `timeoutMs` | `number` | No | Abort after this many milliseconds, image download included (default: `30000`) |
331
+ | `instructions` | `function` | No | Customizes the prompt, see [Customizing the instructions](#customizing-the-instructions) |
332
+
333
+ ### Customizing the instructions
334
+
335
+ Every bundled resolver accepts an `instructions` function that receives the
336
+ instructions the resolver would send on its own, so a house style rule can be
337
+ appended without restating the rules the plugin depends on:
338
+
339
+ ```ts
340
+ openAIResolver({
341
+ apiKey: process.env.OPENAI_API_KEY!,
342
+ instructions: ({ defaultInstructions }) =>
343
+ `${defaultInstructions}\n\nName the product line when its packaging is legible. Never guess at a person's role.`,
344
+ })
345
+ ```
346
+
347
+ It is called once per generation and receives `{ defaultInstructions, locales, filename }`.
348
+ Returning something entirely different is allowed — the image and the required
349
+ response shape travel separately from the instructions, so a replacement cannot
350
+ break the resolver's contract with its provider.
351
+
176
352
  ## Custom Resolver
177
353
 
178
- You can create your own resolver by implementing the `AltTextResolver` interface.
354
+ For another LLM provider, `createVisionResolver` is usually the shortest path: it
355
+ owns the prompt, the per-locale response schema, the optional image download and
356
+ the strict reading of the response, leaving only the provider call to `generate`.
357
+ Every bundled resolver is built on it.
358
+
359
+ ```ts
360
+ import { createVisionResolver, VisionProviderError } from '@jhb.software/payload-alt-text-plugin'
361
+
362
+ export const myResolver = ({ apiKey }: { apiKey: string }) =>
363
+ createVisionResolver({
364
+ apiKey,
365
+ // `image` is only present when `inlineImage` is set; otherwise pass
366
+ // `imageThumbnailUrl` to the provider and let it fetch the file.
367
+ generate: async ({ image, instructions, maxTokens, responseSchema, signal }) => {
368
+ if (!image) {
369
+ throw new Error('The image was not downloaded')
370
+ }
371
+
372
+ const response = await fetch('https://api.example.com/v1/vision', {
373
+ body: JSON.stringify({ instructions, image: image.dataUri, schema: responseSchema }),
374
+ headers: { Authorization: `Bearer ${apiKey}` },
375
+ method: 'POST',
376
+ signal,
377
+ })
378
+
379
+ // A rate limit or an outage is worth another attempt: throwing
380
+ // `VisionProviderError` lets the factory retry it. Any other error fails
381
+ // the generation immediately, with its message shown in the admin panel.
382
+ if (!response.ok) {
383
+ throw new VisionProviderError({
384
+ body: await response.text(),
385
+ label: 'My Provider',
386
+ status: response.status,
387
+ })
388
+ }
389
+
390
+ // Return the parsed JSON object.
391
+ return await response.json()
392
+ },
393
+ inlineImage: true,
394
+ key: 'my-provider',
395
+ label: 'My Provider',
396
+ supportedMimeTypes: ['image/jpeg', 'image/png', 'image/webp'],
397
+ })
398
+ ```
399
+
400
+ A provider call that fails with `VisionProviderError` is retried twice, with a
401
+ short backoff, when the status is a rate limit (`429`) or a server-side failure
402
+ (`5xx`) — a bulk generation trips those routinely, and giving up on the first one
403
+ leaves documents without an alt text. Any other status fails immediately: a `4xx`
404
+ would fail identically on every attempt. The resolver's `timeoutMs` covers the
405
+ attempts together.
406
+
407
+ Pass the provider's response as `body` and it is written to the server log, never
408
+ to the error the admin panel shows — that message reaches everyone allowed to
409
+ generate an alt text, and a provider's error text is not written with them in
410
+ mind: OpenAI quotes the rejected API key back in a 401. The panel gets the
411
+ provider name and the status.
412
+
413
+ For a provider that does not fit that shape at all, implement the
414
+ `AltTextResolver` interface directly.
415
+
416
+ Alongside `imageThumbnailUrl`, the resolver receives `imageThumbnailMimeType` — the format served at that URL, when the collection declares one via [`imageThumbnailMimeType`](#transcoding-thumbnails). Resolvers that hand the URL to the provider can ignore it. Resolvers that inline the bytes need it, because an explicit media type cannot be sniffed from a URL: Anthropic image blocks require `media_type` and Gemini's `inline_data` requires `mime_type`. It is `undefined` when nothing was declared. Resolvers built on `createVisionResolver` get this for free: `image.mediaType` is the type the host actually served, with the declaration standing in when the host sent none or a generic `application/octet-stream`.
179
417
 
180
418
  ```ts
181
419
  import type { AltTextResolver } from '@jhb.software/payload-alt-text-plugin'
182
420
 
183
421
  export const customResolver = (): AltTextResolver => ({
184
422
  key: 'custom',
185
- resolve: async ({ imageThumbnailUrl, filename, locale, req }) => {
423
+ resolve: async ({ imageThumbnailUrl, imageThumbnailMimeType, filename, locale, req }) => {
186
424
  // Your custom alt text generation logic here
187
425
  const altText = await generateAltText(imageThumbnailUrl, filename, locale, req)
188
426
 
@@ -205,7 +443,24 @@ export const customResolver = (): AltTextResolver => ({
205
443
 
206
444
  ## REST API Endpoints
207
445
 
208
- The plugin registers the following REST API endpoints under `/api/alt-text/`. All endpoints require authentication by default (configurable via the `access` option). Beyond that gate, the generate endpoints enforce each collection's own access control on the documents they read and write, and the health endpoint reports only the collections the requesting user can read (and can be gated separately via the `healthCheck` function).
446
+ The plugin registers the following REST API endpoints under `/api/alt-text/`.
447
+
448
+ ### Authentication
449
+
450
+ The endpoints require an authenticated request and respond with `401` otherwise. By default any authenticated Payload user (admin session or API key) is allowed:
451
+
452
+ ```ts
453
+ ;({ req }) => !!req.user
454
+ ```
455
+
456
+ That default fits a setup where every Payload user is trusted staff. Generating alt text spends money at the configured provider and the bulk endpoint writes to many documents at once, so projects with public sign-up, customer-facing accounts, or any user tier that should not incur provider cost must narrow it via the `access` option:
457
+
458
+ ```ts
459
+ // Only allow editors to use the generate endpoints
460
+ access: ({ req }) => req.user?.role === 'editor'
461
+ ```
462
+
463
+ Beyond that gate, the generate endpoints enforce each collection's own access control on the documents they read and write, and the health endpoint reports only the collections the requesting user can read (and can be gated separately via `healthCheck.access`).
209
464
 
210
465
  ### `POST /api/alt-text/generate`
211
466
 
@@ -2,7 +2,7 @@ import pMap from 'p-map';
2
2
  import { APIError, Forbidden } from 'payload';
3
3
  import { ZodError } from 'zod';
4
4
  import { localesFromConfig } from '../utilities/localesFromConfig.js';
5
- import { matchesMimeType } from '../utilities/mimeTypes.js';
5
+ import { getUnsupportedSourceMimeTypeError, matchesMimeType } from '../utilities/mimeTypes.js';
6
6
  import { bulkGenerateAltTextsRequestSchema, formatZodError } from './schemas.js';
7
7
  /**
8
8
  * Generates and updates alt text for multiple images in all locales.
@@ -85,7 +85,7 @@ import { bulkGenerateAltTextsRequestSchema, formatZodError } from './schemas.js'
85
85
  req
86
86
  });
87
87
  updatedDocs++;
88
- console.log(`${updatedDocs}/${uniqueIds.length} updated (${Math.round(updatedDocs / uniqueIds.length * 100)}%)`);
88
+ req.payload.logger.info(`${updatedDocs}/${uniqueIds.length} updated (${Math.round(updatedDocs / uniqueIds.length * 100)}%)`);
89
89
  } catch (error) {
90
90
  // A Forbidden means the user has no read/update access to the
91
91
  // collection at all — it applies to every id, so fail the whole
@@ -94,14 +94,16 @@ import { bulkGenerateAltTextsRequestSchema, formatZodError } from './schemas.js'
94
94
  if (error instanceof Forbidden) {
95
95
  throw error;
96
96
  }
97
- console.error(`Error generating alt text for ${id}:`, error);
97
+ req.payload.logger.error({
98
+ err: error
99
+ }, `Error generating alt text for ${id}`);
98
100
  erroredDocs.push(id);
99
101
  }
100
102
  }, {
101
103
  concurrency
102
104
  });
103
105
  if (erroredDocs.length > 0) {
104
- console.error(`Failed for: ${erroredDocs.join(', ')}`);
106
+ req.payload.logger.error(`Failed for: ${erroredDocs.join(', ')}`);
105
107
  }
106
108
  return Response.json({
107
109
  erroredDocs,
@@ -123,7 +125,9 @@ import { bulkGenerateAltTextsRequestSchema, formatZodError } from './schemas.js'
123
125
  status: error.status
124
126
  });
125
127
  }
126
- console.error('Error in bulk generation:', error);
128
+ req.payload.logger.error({
129
+ err: error
130
+ }, 'Error in bulk generation');
127
131
  return Response.json({
128
132
  error: `Error generating alt text: ${error instanceof Error ? error.message : 'Unknown error'}`
129
133
  }, {
@@ -151,12 +155,21 @@ async function generateAndUpdateAltText({ id, collection, locales, payload, plug
151
155
  if (mimeType && !matchesMimeType(mimeType, collectionConfig.mimeTypes)) {
152
156
  throw new Error(`Alt text is not tracked for files of type "${mimeType}" in the "${collection}" collection. Tracked types: ${collectionConfig.mimeTypes.join(', ')}.`);
153
157
  }
154
- if (mimeType && pluginConfig.resolver.supportedMimeTypes && !pluginConfig.resolver.supportedMimeTypes.includes(mimeType)) {
155
- throw new Error(`Alt text generation is not supported for files of type "${mimeType}". Supported types: ${pluginConfig.resolver.supportedMimeTypes.join(', ')}.`);
158
+ const unsupportedSourceError = getUnsupportedSourceMimeTypeError({
159
+ declaredThumbnailMimeType: collectionConfig.imageThumbnailMimeType,
160
+ mimeType,
161
+ supportedMimeTypes: pluginConfig.resolver.supportedMimeTypes
162
+ });
163
+ if (unsupportedSourceError) {
164
+ throw new Error(unsupportedSourceError);
156
165
  }
157
- const imageThumbnailUrl = pluginConfig.getImageThumbnail(imageDoc);
166
+ const imageThumbnailUrl = await pluginConfig.getImageThumbnail(imageDoc, {
167
+ collection,
168
+ req
169
+ });
158
170
  const result = await pluginConfig.resolver.resolveBulk({
159
171
  filename: 'filename' in imageDoc && typeof imageDoc.filename === 'string' ? imageDoc.filename : undefined,
172
+ imageThumbnailMimeType: collectionConfig.imageThumbnailMimeType,
160
173
  imageThumbnailUrl,
161
174
  locales,
162
175
  req
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/endpoints/bulkGenerateAltTexts.ts"],"sourcesContent":["import type { BasePayload, CollectionSlug, PayloadHandler, PayloadRequest } from 'payload'\n\nimport pMap from 'p-map'\nimport { APIError, Forbidden } from 'payload'\nimport { ZodError } from 'zod'\n\nimport type { AltTextPluginConfig } from '../types/AltTextPluginConfig.js'\n\nimport { localesFromConfig } from '../utilities/localesFromConfig.js'\nimport { matchesMimeType } from '../utilities/mimeTypes.js'\nimport { bulkGenerateAltTextsRequestSchema, formatZodError } from './schemas.js'\n\n/**\n * Generates and updates alt text for multiple images in all locales.\n */\nexport const bulkGenerateAltTextsEndpoint =\n (access: AltTextPluginConfig['access']): PayloadHandler =>\n async (req: PayloadRequest) => {\n try {\n if (!(await access({ req }))) {\n return Response.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const data = 'json' in req && typeof req.json === 'function' ? await req.json() : null\n\n const { collection, ids } = bulkGenerateAltTextsRequestSchema.parse(data)\n\n let updatedDocs = 0\n const erroredDocs: (number | string)[] = []\n\n // Get plugin config from payload config\n const pluginConfig = req.payload.config.custom?.altTextPluginConfig as\n | AltTextPluginConfig\n | undefined\n\n if (!pluginConfig) {\n return Response.json({ error: 'Plugin config not found' }, { status: 500 })\n }\n\n // Treat the configured collections as an allowlist. Reject any other\n // collection before touching the Local API, so the endpoint can only ever\n // operate on the upload collections the plugin manages.\n const collectionConfig = pluginConfig.collections.find((entry) => entry.slug === collection)\n\n if (!collectionConfig) {\n return Response.json(\n { error: `Collection \"${collection}\" is not managed by the alt text plugin.` },\n { status: 403 },\n )\n }\n\n if (!pluginConfig.resolver) {\n return Response.json({ error: 'No alt text resolver configured' }, { status: 500 })\n }\n\n const concurrency = pluginConfig.maxBulkGenerateConcurrency\n\n // De-duplicate so the same image is never generated (and billed) twice,\n // then bound the batch so a single request cannot fan out into an\n // unbounded number of paid resolver calls.\n const uniqueIds = [...new Set(ids)]\n\n if (uniqueIds.length > pluginConfig.maxBulkGenerateIds) {\n return Response.json(\n {\n error: `Too many ids: ${uniqueIds.length} exceeds the maximum of ${pluginConfig.maxBulkGenerateIds} per request.`,\n },\n { status: 400 },\n )\n }\n\n // determine target locales based on config\n const locales = localesFromConfig(req.payload.config)\n const targetLocales = locales ?? [pluginConfig.locale!]\n if (!targetLocales) {\n return Response.json(\n {\n error:\n 'Could not determine target locales for alt text generation. Please check your plugin configuration.',\n },\n { status: 500 },\n )\n }\n\n await pMap(\n uniqueIds,\n async (id) => {\n try {\n await generateAndUpdateAltText({\n id,\n collection,\n locales: targetLocales,\n payload: req.payload,\n pluginConfig,\n req,\n })\n updatedDocs++\n console.log(\n `${updatedDocs}/${uniqueIds.length} updated (${Math.round((updatedDocs / uniqueIds.length) * 100)}%)`,\n )\n } catch (error) {\n // A Forbidden means the user has no read/update access to the\n // collection at all — it applies to every id, so fail the whole\n // request with a real 403 instead of silently listing all ids as\n // errored. Row-level NotFound stays a per-doc error (partial success).\n if (error instanceof Forbidden) {\n throw error\n }\n console.error(`Error generating alt text for ${id}:`, error)\n erroredDocs.push(id)\n }\n },\n { concurrency },\n )\n\n if (erroredDocs.length > 0) {\n console.error(`Failed for: ${erroredDocs.join(', ')}`)\n }\n\n return Response.json({\n erroredDocs,\n totalDocs: uniqueIds.length,\n updatedDocs,\n })\n } catch (error) {\n if (error instanceof ZodError) {\n return Response.json(formatZodError(error), { status: 400 })\n }\n // Surface Payload access errors (Forbidden 403) with their real status so\n // an agent gets an accurate, non-retryable signal instead of a 500.\n if (error instanceof APIError) {\n return Response.json({ error: error.message }, { status: error.status })\n }\n console.error('Error in bulk generation:', error)\n return Response.json(\n {\n error: `Error generating alt text: ${error instanceof Error ? error.message : 'Unknown error'}`,\n },\n { status: 500 },\n )\n }\n }\n\nasync function generateAndUpdateAltText({\n id,\n collection,\n locales,\n payload,\n pluginConfig,\n req,\n}: {\n collection: CollectionSlug\n id: number | string\n locales: string[]\n payload: BasePayload\n pluginConfig: AltTextPluginConfig\n req: PayloadRequest\n}) {\n const imageDoc = await payload.findByID({\n id,\n collection,\n depth: 0,\n // Run under the requesting user's access, not Payload's default\n // `overrideAccess: true`, so collection-level access control applies.\n overrideAccess: false,\n user: req.user,\n })\n\n if (!imageDoc) {\n throw new Error('Image not found')\n }\n\n const mimeType =\n 'mimeType' in imageDoc && typeof imageDoc.mimeType === 'string' ? imageDoc.mimeType : undefined\n\n // The handler validates `collection` against the configured collections before\n // reaching this helper, so a matching entry is guaranteed.\n const collectionConfig = pluginConfig.collections.find((entry) => entry.slug === collection)!\n\n if (mimeType && !matchesMimeType(mimeType, collectionConfig.mimeTypes)) {\n throw new Error(\n `Alt text is not tracked for files of type \"${mimeType}\" in the \"${collection}\" collection. Tracked types: ${collectionConfig.mimeTypes.join(', ')}.`,\n )\n }\n\n if (\n mimeType &&\n pluginConfig.resolver.supportedMimeTypes &&\n !pluginConfig.resolver.supportedMimeTypes.includes(mimeType)\n ) {\n throw new Error(\n `Alt text generation is not supported for files of type \"${mimeType}\". Supported types: ${pluginConfig.resolver.supportedMimeTypes.join(', ')}.`,\n )\n }\n\n const imageThumbnailUrl = pluginConfig.getImageThumbnail(imageDoc)\n\n const result = await pluginConfig.resolver.resolveBulk({\n filename:\n 'filename' in imageDoc && typeof imageDoc.filename === 'string'\n ? imageDoc.filename\n : undefined,\n imageThumbnailUrl,\n locales,\n req,\n })\n\n if (!result.success) {\n throw new Error(result.error || 'Failed to generate alt text')\n }\n\n for (const locale of locales) {\n const localeResult = result.results[locale]\n if (localeResult) {\n await payload.update({\n id,\n collection,\n data: {\n alt: localeResult.altText,\n keywords: localeResult.keywords,\n },\n locale,\n // Run under the requesting user's access, not Payload's default\n // `overrideAccess: true`, so collection-level access control applies.\n overrideAccess: false,\n user: req.user,\n })\n }\n }\n}\n"],"names":["pMap","APIError","Forbidden","ZodError","localesFromConfig","matchesMimeType","bulkGenerateAltTextsRequestSchema","formatZodError","bulkGenerateAltTextsEndpoint","access","req","Response","json","error","status","data","collection","ids","parse","updatedDocs","erroredDocs","pluginConfig","payload","config","custom","altTextPluginConfig","collectionConfig","collections","find","entry","slug","resolver","concurrency","maxBulkGenerateConcurrency","uniqueIds","Set","length","maxBulkGenerateIds","locales","targetLocales","locale","id","generateAndUpdateAltText","console","log","Math","round","push","join","totalDocs","message","Error","imageDoc","findByID","depth","overrideAccess","user","mimeType","undefined","mimeTypes","supportedMimeTypes","includes","imageThumbnailUrl","getImageThumbnail","result","resolveBulk","filename","success","localeResult","results","update","alt","altText","keywords"],"mappings":"AAEA,OAAOA,UAAU,QAAO;AACxB,SAASC,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAC7C,SAASC,QAAQ,QAAQ,MAAK;AAI9B,SAASC,iBAAiB,QAAQ,oCAAmC;AACrE,SAASC,eAAe,QAAQ,4BAA2B;AAC3D,SAASC,iCAAiC,EAAEC,cAAc,QAAQ,eAAc;AAEhF;;CAEC,GACD,OAAO,MAAMC,+BACX,CAACC,SACD,OAAOC;QACL,IAAI;YACF,IAAI,CAAE,MAAMD,OAAO;gBAAEC;YAAI,IAAK;gBAC5B,OAAOC,SAASC,IAAI,CAAC;oBAAEC,OAAO;gBAAe,GAAG;oBAAEC,QAAQ;gBAAI;YAChE;YAEA,MAAMC,OAAO,UAAUL,OAAO,OAAOA,IAAIE,IAAI,KAAK,aAAa,MAAMF,IAAIE,IAAI,KAAK;YAElF,M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Aa0C,iBAAiB,CAACX;IAEzD,MAAMY,SAAS,MAAM3C,aAAaU,QAAQ,CAACkC,WAAW,CAAC;QACrDC,UACE,cAAcd,YAAY,OAAOA,SAASc,QAAQ,KAAK,WACnDd,SAASc,QAAQ,GACjBR;QACNI;QACAxB;QACA5B;IACF;IAEA,IAAI,CAACsD,OAAOG,OAAO,EAAE;QACnB,MAAM,IAAIhB,MAAMa,OAAOnD,KAAK,IAAI;IAClC;IAEA,KAAK,MAAM2B,UAAUF,QAAS;QAC5B,MAAM8B,eAAeJ,OAAOK,OAAO,CAAC7B,OAAO;QAC3C,IAAI4B,cAAc;YAChB,MAAM9C,QAAQgD,MAAM,CAAC;gBACnB7B;gBACAzB;gBACAD,MAAM;oBACJwD,KAAKH,aAAaI,OAAO;oBACzBC,UAAUL,aAAaK,QAAQ;gBACjC;gBACAjC;gBACA,gEAAgE;gBAChE,sEAAsE;gBACtEe,gBAAgB;gBAChBC,MAAM9C,IAAI8C,IAAI;YAChB;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/endpoints/bulkGenerateAltTexts.ts"],"sourcesContent":["import type { BasePayload, CollectionSlug, PayloadHandler, PayloadRequest } from 'payload'\n\nimport pMap from 'p-map'\nimport { APIError, Forbidden } from 'payload'\nimport { ZodError } from 'zod'\n\nimport type { AltTextPluginConfig } from '../types/AltTextPluginConfig.js'\n\nimport { localesFromConfig } from '../utilities/localesFromConfig.js'\nimport { getUnsupportedSourceMimeTypeError, matchesMimeType } from '../utilities/mimeTypes.js'\nimport { bulkGenerateAltTextsRequestSchema, formatZodError } from './schemas.js'\n\n/**\n * Generates and updates alt text for multiple images in all locales.\n */\nexport const bulkGenerateAltTextsEndpoint =\n (access: AltTextPluginConfig['access']): PayloadHandler =>\n async (req: PayloadRequest) => {\n try {\n if (!(await access({ req }))) {\n return Response.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const data = 'json' in req && typeof req.json === 'function' ? await req.json() : null\n\n const { collection, ids } = bulkGenerateAltTextsRequestSchema.parse(data)\n\n let updatedDocs = 0\n const erroredDocs: (number | string)[] = []\n\n // Get plugin config from payload config\n const pluginConfig = req.payload.config.custom?.altTextPluginConfig as\n AltTextPluginConfig | undefined\n\n if (!pluginConfig) {\n return Response.json({ error: 'Plugin config not found' }, { status: 500 })\n }\n\n // Treat the configured collections as an allowlist. Reject any other\n // collection before touching the Local API, so the endpoint can only ever\n // operate on the upload collections the plugin manages.\n const collectionConfig = pluginConfig.collections.find((entry) => entry.slug === collection)\n\n if (!collectionConfig) {\n return Response.json(\n { error: `Collection \"${collection}\" is not managed by the alt text plugin.` },\n { status: 403 },\n )\n }\n\n if (!pluginConfig.resolver) {\n return Response.json({ error: 'No alt text resolver configured' }, { status: 500 })\n }\n\n const concurrency = pluginConfig.maxBulkGenerateConcurrency\n\n // De-duplicate so the same image is never generated (and billed) twice,\n // then bound the batch so a single request cannot fan out into an\n // unbounded number of paid resolver calls.\n const uniqueIds = [...new Set(ids)]\n\n if (uniqueIds.length > pluginConfig.maxBulkGenerateIds) {\n return Response.json(\n {\n error: `Too many ids: ${uniqueIds.length} exceeds the maximum of ${pluginConfig.maxBulkGenerateIds} per request.`,\n },\n { status: 400 },\n )\n }\n\n // determine target locales based on config\n const locales = localesFromConfig(req.payload.config)\n const targetLocales = locales ?? [pluginConfig.locale!]\n if (!targetLocales) {\n return Response.json(\n {\n error:\n 'Could not determine target locales for alt text generation. Please check your plugin configuration.',\n },\n { status: 500 },\n )\n }\n\n await pMap(\n uniqueIds,\n async (id) => {\n try {\n await generateAndUpdateAltText({\n id,\n collection,\n locales: targetLocales,\n payload: req.payload,\n pluginConfig,\n req,\n })\n updatedDocs++\n req.payload.logger.info(\n `${updatedDocs}/${uniqueIds.length} updated (${Math.round((updatedDocs / uniqueIds.length) * 100)}%)`,\n )\n } catch (error) {\n // A Forbidden means the user has no read/update access to the\n // collection at all — it applies to every id, so fail the whole\n // request with a real 403 instead of silently listing all ids as\n // errored. Row-level NotFound stays a per-doc error (partial success).\n if (error instanceof Forbidden) {\n throw error\n }\n req.payload.logger.error({ err: error }, `Error generating alt text for ${id}`)\n erroredDocs.push(id)\n }\n },\n { concurrency },\n )\n\n if (erroredDocs.length > 0) {\n req.payload.logger.error(`Failed for: ${erroredDocs.join(', ')}`)\n }\n\n return Response.json({\n erroredDocs,\n totalDocs: uniqueIds.length,\n updatedDocs,\n })\n } catch (error) {\n if (error instanceof ZodError) {\n return Response.json(formatZodError(error), { status: 400 })\n }\n // Surface Payload access errors (Forbidden 403) with their real status so\n // an agent gets an accurate, non-retryable signal instead of a 500.\n if (error instanceof APIError) {\n return Response.json({ error: error.message }, { status: error.status })\n }\n req.payload.logger.error({ err: error }, 'Error in bulk generation')\n return Response.json(\n {\n error: `Error generating alt text: ${error instanceof Error ? error.message : 'Unknown error'}`,\n },\n { status: 500 },\n )\n }\n }\n\nasync function generateAndUpdateAltText({\n id,\n collection,\n locales,\n payload,\n pluginConfig,\n req,\n}: {\n collection: CollectionSlug\n id: number | string\n locales: string[]\n payload: BasePayload\n pluginConfig: AltTextPluginConfig\n req: PayloadRequest\n}) {\n const imageDoc = await payload.findByID({\n id,\n collection,\n depth: 0,\n // Run under the requesting user's access, not Payload's default\n // `overrideAccess: true`, so collection-level access control applies.\n overrideAccess: false,\n user: req.user,\n })\n\n if (!imageDoc) {\n throw new Error('Image not found')\n }\n\n const mimeType =\n 'mimeType' in imageDoc && typeof imageDoc.mimeType === 'string' ? imageDoc.mimeType : undefined\n\n // The handler validates `collection` against the configured collections before\n // reaching this helper, so a matching entry is guaranteed.\n const collectionConfig = pluginConfig.collections.find((entry) => entry.slug === collection)!\n\n if (mimeType && !matchesMimeType(mimeType, collectionConfig.mimeTypes)) {\n throw new Error(\n `Alt text is not tracked for files of type \"${mimeType}\" in the \"${collection}\" collection. Tracked types: ${collectionConfig.mimeTypes.join(', ')}.`,\n )\n }\n\n const unsupportedSourceError = getUnsupportedSourceMimeTypeError({\n declaredThumbnailMimeType: collectionConfig.imageThumbnailMimeType,\n mimeType,\n supportedMimeTypes: pluginConfig.resolver.supportedMimeTypes,\n })\n if (unsupportedSourceError) {\n throw new Error(unsupportedSourceError)\n }\n\n const imageThumbnailUrl = await pluginConfig.getImageThumbnail(imageDoc, { collection, req })\n\n const result = await pluginConfig.resolver.resolveBulk({\n filename:\n 'filename' in imageDoc && typeof imageDoc.filename === 'string'\n ? imageDoc.filename\n : undefined,\n imageThumbnailMimeType: collectionConfig.imageThumbnailMimeType,\n imageThumbnailUrl,\n locales,\n req,\n })\n\n if (!result.success) {\n throw new Error(result.error || 'Failed to generate alt text')\n }\n\n for (const locale of locales) {\n const localeResult = result.results[locale]\n if (localeResult) {\n await payload.update({\n id,\n collection,\n data: {\n alt: localeResult.altText,\n keywords: localeResult.keywords,\n },\n locale,\n // Run under the requesting user's access, not Payload's default\n // `overrideAccess: true`, so collection-level access control applies.\n overrideAccess: false,\n user: req.user,\n })\n }\n }\n}\n"],"names":["pMap","APIError","Forbidden","ZodError","localesFromConfig","getUnsupportedSourceMimeTypeError","matchesMimeType","bulkGenerateAltTextsRequestSchema","formatZodError","bulkGenerateAltTextsEndpoint","access","req","Response","json","error","status","data","collection","ids","parse","updatedDocs","erroredDocs","pluginConfig","payload","config","custom","altTextPluginConfig","collectionConfig","collections","find","entry","slug","resolver","concurrency","maxBulkGenerateConcurrency","uniqueIds","Set","length","maxBulkGenerateIds","locales","targetLocales","locale","id","generateAndUpdateAltText","logger","info","Math","round","err","push","join","totalDocs","message","Error","imageDoc","findByID","depth","overrideAccess","user","mimeType","undefined","mimeTypes","unsupportedSourceError","declaredThumbnailMimeType","imageThumbnailMimeType","supportedMimeTypes","imageThumbnailUrl","getImageThumbnail","result","resolveBulk","filename","success","localeResult","results","update","alt","altText","keywords"],"mappings":"AAEA,OAAOA,UAAU,QAAO;AACxB,SAASC,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAC7C,SAASC,QAAQ,QAAQ,MAAK;AAI9B,SAASC,iBAAiB,QAAQ,oCAAmC;AAC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esMimeType } from '../utilities/mimeTypes.js';
3
+ import { getUnsupportedSourceMimeTypeError, matchesMimeType } from '../utilities/mimeTypes.js';
4
4
  import { formatZodError, generateAltTextRequestSchema } from './schemas.js';
5
5
  /**
6
6
  * Generates alt text for a single image using the configured resolver.
@@ -80,9 +80,14 @@ import { formatZodError, generateAltTextRequestSchema } from './schemas.js';
80
80
  status: 400
81
81
  });
82
82
  }
83
- if (mimeType && pluginConfig.resolver.supportedMimeTypes && !pluginConfig.resolver.supportedMimeTypes.includes(mimeType)) {
83
+ const unsupportedSourceError = getUnsupportedSourceMimeTypeError({
84
+ declaredThumbnailMimeType: collectionConfig.imageThumbnailMimeType,
85
+ mimeType,
86
+ supportedMimeTypes: pluginConfig.resolver.supportedMimeTypes
87
+ });
88
+ if (unsupportedSourceError) {
84
89
  return Response.json({
85
- error: `Alt text generation is not supported for files of type "${mimeType}". Supported types: ${pluginConfig.resolver.supportedMimeTypes.join(', ')}.`
90
+ error: unsupportedSourceError
86
91
  }, {
87
92
  status: 400
88
93
  });
@@ -106,9 +111,13 @@ import { formatZodError, generateAltTextRequestSchema } from './schemas.js';
106
111
  status: 500
107
112
  });
108
113
  }
109
- const imageThumbnailUrl = pluginConfig.getImageThumbnail(imageDoc);
114
+ const imageThumbnailUrl = await pluginConfig.getImageThumbnail(imageDoc, {
115
+ collection,
116
+ req
117
+ });
110
118
  const result = await pluginConfig.resolver.resolve({
111
119
  filename: 'filename' in imageDoc && typeof imageDoc.filename === 'string' ? imageDoc.filename : undefined,
120
+ imageThumbnailMimeType: collectionConfig.imageThumbnailMimeType,
112
121
  imageThumbnailUrl,
113
122
  locale: targetLocale,
114
123
  req
@@ -156,7 +165,9 @@ import { formatZodError, generateAltTextRequestSchema } from './schemas.js';
156
165
  status: error.status
157
166
  });
158
167
  }
159
- console.error('Error generating alt text:', error);
168
+ req.payload.logger.error({
169
+ err: error
170
+ }, 'Error generating alt text');
160
171
  return Response.json({
161
172
  error: `Error generating alt text: ${error instanceof Error ? error.message : 'Unknown error'}`
162
173
  }, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/endpoints/generateAltText.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\n\nimport { APIError } from 'payload'\nimport { ZodError } from 'zod'\n\nimport type { AltTextPluginConfig } from '../types/AltTextPluginConfig.js'\n\nimport { matchesMimeType } from '../utilities/mimeTypes.js'\nimport { formatZodError, generateAltTextRequestSchema } from './schemas.js'\n\n/**\n * Generates alt text for a single image using the configured resolver.\n *\n * By default, returns the result without updating the document (preview mode).\n * Pass `update: true` in the request body to also persist the generated alt text\n * and keywords to the document — useful for programmatic/agent workflows.\n *\n * The response always includes the `id` and `collection` for easy correlation.\n */\nexport const generateAltTextEndpoint =\n (access: AltTextPluginConfig['access']): PayloadHandler =>\n async (req: PayloadRequest) => {\n try {\n if (!(await access({ req }))) {\n return Response.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const data = 'json' in req && typeof req.json === 'function' ? await req.json() : null\n\n const { id, collection, locale, update } = generateAltTextRequestSchema.parse(data)\n\n const pluginConfig = req.payload.config.custom?.altTextPluginConfig as\n | AltTextPluginConfig\n | undefined\n\n if (!pluginConfig) {\n return Response.json({ error: 'Plugin config not found' }, { status: 500 })\n }\n\n // Treat the configured collections as an allowlist. Reject any other\n // collection before touching the Local API, so the endpoint can only ever\n // operate on the upload collections the plugin manages.\n const collectionConfig = pluginConfig.collections.find((entry) => entry.slug === collection)\n\n if (!collectionConfig) {\n return Response.json(\n { error: `Collection \"${collection}\" is not managed by the alt text plugin.` },\n { status: 403 },\n )\n }\n\n const imageDoc = await req.payload.findByID({\n id,\n collection,\n depth: 0,\n // Run under the requesting user's access, not Payload's default\n // `overrideAccess: true`, so collection-level access control applies.\n overrideAccess: false,\n user: req.user,\n })\n\n if (!imageDoc) {\n return Response.json({ error: 'Image not found' }, { status: 404 })\n }\n\n if (!pluginConfig.getImageThumbnail) {\n return Response.json(\n { error: 'getImageThumbnail function not configured' },\n { status: 500 },\n )\n }\n\n if (!pluginConfig.resolver) {\n return Response.json({ error: 'No alt text resolver configured' }, { status: 500 })\n }\n\n const mimeType =\n 'mimeType' in imageDoc && typeof imageDoc.mimeType === 'string'\n ? imageDoc.mimeType\n : undefined\n\n if (mimeType && !matchesMimeType(mimeType, collectionConfig.mimeTypes)) {\n return Response.json(\n {\n error: `Alt text is not tracked for files of type \"${mimeType}\" in the \"${collection}\" collection. Tracked types: ${collectionConfig.mimeTypes.join(', ')}.`,\n },\n { status: 400 },\n )\n }\n\n if (\n mimeType &&\n pluginConfig.resolver.supportedMimeTypes &&\n !pluginConfig.resolver.supportedMimeTypes.includes(mimeType)\n ) {\n return Response.json(\n {\n error: `Alt text generation is not supported for files of type \"${mimeType}\". Supported types: ${pluginConfig.resolver.supportedMimeTypes.join(', ')}.`,\n },\n { status: 400 },\n )\n }\n\n // When localization is enabled, the requested locale must be one of the\n // configured locales. Reject anything else before it can be written to an\n // unconfigured locale or interpolated into the resolver's prompt.\n if (\n locale != null &&\n pluginConfig.locales.length > 0 &&\n !pluginConfig.locales.includes(locale)\n ) {\n return Response.json(\n {\n error: `Locale \"${locale}\" is not configured. Configured locales: ${pluginConfig.locales.join(', ')}.`,\n },\n { status: 400 },\n )\n }\n\n // determine target locale\n const targetLocale = locale ?? pluginConfig.locale\n if (!targetLocale) {\n return Response.json(\n {\n error:\n 'Could not determine target locale for alt text generation. Please check your plugin configuration.',\n },\n { status: 500 },\n )\n }\n\n const imageThumbnailUrl = pluginConfig.getImageThumbnail(imageDoc)\n\n const result = await pluginConfig.resolver.resolve({\n filename:\n 'filename' in imageDoc && typeof imageDoc.filename === 'string'\n ? imageDoc.filename\n : undefined,\n imageThumbnailUrl,\n locale: targetLocale,\n req,\n })\n\n if (!result.success) {\n return Response.json(\n { error: result.error || 'Failed to generate alt text' },\n { status: 500 },\n )\n }\n\n if (update) {\n await req.payload.update({\n id,\n collection,\n data: {\n alt: result.result.altText,\n keywords: result.result.keywords,\n },\n locale: targetLocale,\n // Run under the requesting user's access, not Payload's default\n // `overrideAccess: true`, so collection-level access control applies.\n overrideAccess: false,\n user: req.user,\n })\n }\n\n return Response.json({ id, collection, ...result.result })\n } catch (error) {\n if (error instanceof ZodError) {\n return Response.json(formatZodError(error), { status: 400 })\n }\n // Surface Payload access errors (Forbidden 403 / NotFound 404) with their\n // real status so an agent gets an accurate, non-retryable signal instead\n // of a misleading 500.\n if (error instanceof APIError) {\n return Response.json({ error: error.message }, { status: error.status })\n }\n console.error('Error generating alt text:', error)\n return Response.json(\n {\n error: `Error generating alt text: ${error instanceof Error ? error.message : 'Unknown error'}`,\n },\n { status: 500 },\n )\n }\n }\n"],"names":["APIError","ZodError","matchesMimeType","formatZodError","generateAltTextRequestSchema","generateAltTextEndpoint","access","req","Response","json","error","status","data","id","collection","locale","update","parse","pluginConfig","payload","config","custom","altTextPluginConfig","collectionConfig","collections","find","entry","slug","imageDoc","findByID","depth","overrideAccess","user","getImageThumbnail","resolver","mimeType","undefined","mimeTypes","join","supportedMimeTypes","includes","locales","length","targetLocale","imageThumbnailUrl","result","resolve","filename","success","alt","altText","keywords","message","console","Error"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAClC,SAASC,QAAQ,QAAQ,MAAK;AAI9B,SAASC,eAAe,QAAQ,4BAA2B;AAC3D,SAASC,cAAc,EAAEC,4BAA4B,QAAQ,eAAc;AAE3E;;;;;;;;CAQC,GACD,OAAO,MAAMC,0BACX,CAACC,SACD,OAAOC;QACL,IAAI;YACF,IAAI,CAAE,MAAMD,OAAO;gBAAEC;YAAI,IAAK;gBAC5B,OAAOC,SAASC,IAAI,CAAC;oBAAEC,OAAO;gBAAe,GAAG;oBAAEC,QAAQ;gBAAI;YAChE;YAEA,MAAMC,OAAO,UAAUL,OAAO,OAAOA,IAAIE,IAAI,KAAK,aAAa,MAAMF,IAAIE,IAAI,KAAK;YAElF,MAAM,EAAEI,EAAE,EAAEC,UAAU,EAAEC,MAAM,EAAEC,MAAM,EAAE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ACRpC;YACF;YAEA,IAAI,CAACsC,OAAOG,OAAO,EAAE;gBACnB,OAAOxC,SAASC,IAAI,CAClB;oBAAEC,OAAOmC,OAAOnC,KAAK,IAAI;gBAA8B,GACvD;oBAAEC,QAAQ;gBAAI;YAElB;YAEA,IAAIK,QAAQ;gBACV,MAAMT,IAAIY,OAAO,CAACH,MAAM,CAAC;oBACvBH;oBACAC;oBACAF,MAAM;wBACJqC,KAAKJ,OAAOA,MAAM,CAACK,OAAO;wBAC1BC,UAAUN,OAAOA,MAAM,CAACM,QAAQ;oBAClC;oBACApC,QAAQ4B;oBACR,gEAAgE;oBAChE,sEAAsE;oBACtEZ,gBAAgB;oBAChBC,MAAMzB,IAAIyB,IAAI;gBAChB;YACF;YAEA,OAAOxB,SAASC,IAAI,CAAC;gBAAEI;gBAAIC;gBAAY,GAAG+B,OAAOA,MAAM;YAAC;QAC1D,EAAE,OAAOnC,OAAO;YACd,IAAIA,iBAAiBT,UAAU;gBAC7B,OAAOO,SAASC,IAAI,CAACN,eAAeO,QAAQ;oBAAEC,QAAQ;gBAAI;YAC5D;YACA,0EAA0E;YAC1E,yEAAyE;YACzE,uBAAuB;YACvB,IAAID,iBAAiBV,UAAU;gBAC7B,OAAOQ,SAASC,IAAI,CAAC;oBAAEC,OAAOA,MAAM0C,OAAO;gBAAC,GAAG;oBAAEzC,QAAQD,MAAMC,MAAM;gBAAC;YACxE;YACA0C,QAAQ3C,KAAK,CAAC,8BAA8BA;YAC5C,OAAOF,SAASC,IAAI,CAClB;gBACEC,OAAO,CAAC,2BAA2B,EAAEA,iBAAiB4C,QAAQ5C,MAAM0C,OAAO,GAAG,iBAAiB;YACjG,GACA;gBAAEzC,QAAQ;YAAI;QAElB;IACF,EAAC"}
1
+ {"version":3,"sources":["../../src/endpoints/generateAltText.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\n\nimport { APIError } from 'payload'\nimport { ZodError } from 'zod'\n\nimport type { AltTextPluginConfig } from '../types/AltTextPluginConfig.js'\n\nimport { getUnsupportedSourceMimeTypeError, matchesMimeType } from '../utilities/mimeTypes.js'\nimport { formatZodError, generateAltTextRequestSchema } from './schemas.js'\n\n/**\n * Generates alt text for a single image using the configured resolver.\n *\n * By default, returns the result without updating the document (preview mode).\n * Pass `update: true` in the request body to also persist the generated alt text\n * and keywords to the document — useful for programmatic/agent workflows.\n *\n * The response always includes the `id` and `collection` for easy correlation.\n */\nexport const generateAltTextEndpoint =\n (access: AltTextPluginConfig['access']): PayloadHandler =>\n async (req: PayloadRequest) => {\n try {\n if (!(await access({ req }))) {\n return Response.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const data = 'json' in req && typeof req.json === 'function' ? await req.json() : null\n\n const { id, collection, locale, update } = generateAltTextRequestSchema.parse(data)\n\n const pluginConfig = req.payload.config.custom?.altTextPluginConfig as\n AltTextPluginConfig | undefined\n\n if (!pluginConfig) {\n return Response.json({ error: 'Plugin config not found' }, { status: 500 })\n }\n\n // Treat the configured collections as an allowlist. Reject any other\n // collection before touching the Local API, so the endpoint can only ever\n // operate on the upload collections the plugin manages.\n const collectionConfig = pluginConfig.collections.find((entry) => entry.slug === collection)\n\n if (!collectionConfig) {\n return Response.json(\n { error: `Collection \"${collection}\" is not managed by the alt text plugin.` },\n { status: 403 },\n )\n }\n\n const imageDoc = await req.payload.findByID({\n id,\n collection,\n depth: 0,\n // Run under the requesting user's access, not Payload's default\n // `overrideAccess: true`, so collection-level access control applies.\n overrideAccess: false,\n user: req.user,\n })\n\n if (!imageDoc) {\n return Response.json({ error: 'Image not found' }, { status: 404 })\n }\n\n if (!pluginConfig.getImageThumbnail) {\n return Response.json(\n { error: 'getImageThumbnail function not configured' },\n { status: 500 },\n )\n }\n\n if (!pluginConfig.resolver) {\n return Response.json({ error: 'No alt text resolver configured' }, { status: 500 })\n }\n\n const mimeType =\n 'mimeType' in imageDoc && typeof imageDoc.mimeType === 'string'\n ? imageDoc.mimeType\n : undefined\n\n if (mimeType && !matchesMimeType(mimeType, collectionConfig.mimeTypes)) {\n return Response.json(\n {\n error: `Alt text is not tracked for files of type \"${mimeType}\" in the \"${collection}\" collection. Tracked types: ${collectionConfig.mimeTypes.join(', ')}.`,\n },\n { status: 400 },\n )\n }\n\n const unsupportedSourceError = getUnsupportedSourceMimeTypeError({\n declaredThumbnailMimeType: collectionConfig.imageThumbnailMimeType,\n mimeType,\n supportedMimeTypes: pluginConfig.resolver.supportedMimeTypes,\n })\n if (unsupportedSourceError) {\n return Response.json({ error: unsupportedSourceError }, { status: 400 })\n }\n\n // When localization is enabled, the requested locale must be one of the\n // configured locales. Reject anything else before it can be written to an\n // unconfigured locale or interpolated into the resolver's prompt.\n if (\n locale != null &&\n pluginConfig.locales.length > 0 &&\n !pluginConfig.locales.includes(locale)\n ) {\n return Response.json(\n {\n error: `Locale \"${locale}\" is not configured. Configured locales: ${pluginConfig.locales.join(', ')}.`,\n },\n { status: 400 },\n )\n }\n\n // determine target locale\n const targetLocale = locale ?? pluginConfig.locale\n if (!targetLocale) {\n return Response.json(\n {\n error:\n 'Could not determine target locale for alt text generation. Please check your plugin configuration.',\n },\n { status: 500 },\n )\n }\n\n const imageThumbnailUrl = await pluginConfig.getImageThumbnail(imageDoc, { collection, req })\n\n const result = await pluginConfig.resolver.resolve({\n filename:\n 'filename' in imageDoc && typeof imageDoc.filename === 'string'\n ? imageDoc.filename\n : undefined,\n imageThumbnailMimeType: collectionConfig.imageThumbnailMimeType,\n imageThumbnailUrl,\n locale: targetLocale,\n req,\n })\n\n if (!result.success) {\n return Response.json(\n { error: result.error || 'Failed to generate alt text' },\n { status: 500 },\n )\n }\n\n if (update) {\n await req.payload.update({\n id,\n collection,\n data: {\n alt: result.result.altText,\n keywords: result.result.keywords,\n },\n locale: targetLocale,\n // Run under the requesting user's access, not Payload's default\n // `overrideAccess: true`, so collection-level access control applies.\n overrideAccess: false,\n user: req.user,\n })\n }\n\n return Response.json({ id, collection, ...result.result })\n } catch (error) {\n if (error instanceof ZodError) {\n return Response.json(formatZodError(error), { status: 400 })\n }\n // Surface Payload access errors (Forbidden 403 / NotFound 404) with their\n // real status so an agent gets an accurate, non-retryable signal instead\n // of a misleading 500.\n if (error instanceof APIError) {\n return Response.json({ error: error.message }, { status: error.status })\n }\n req.payload.logger.error({ err: error }, 'Error generating alt text')\n return Response.json(\n {\n error: `Error generating alt text: ${error instanceof Error ? error.message : 'Unknown error'}`,\n },\n { status: 500 },\n )\n }\n }\n"],"names":["APIError","ZodError","getUnsupportedSourceMimeTypeError","matchesMimeType","formatZodError","generateAltTextRequestSchema","generateAltTextEndpoint","access","req","Response","json","error","status","data","id","collection","locale","update","parse","pluginConfig","payload","config","custom","altTextPluginConfig","collectionConfig","collections","find","entry","slug","imageDoc","findByID","depth","overrideAccess","user","getImageThumbnail","resolver","mimeType","undefined","mimeTypes","join","unsupportedSourceError","declaredThumbnailMimeType","imageThumbnailMimeType","supportedMimeTypes","locales","length","includes","targetLocale","imageThumbnailUrl","result","resolve","filename","success","alt","altText","keywords","message","logger","err","Error"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAClC,SAASC,QAAQ,QAAQ,MAAK;AAI9B,SAASC,iCAAiC,EAAEC,eAAe,QAAQ,4BAA2B;AAC9F,SAASC,cAAc,EAAEC,4BAA4B,QAAQ,eAAc;AAE3E;;;;;;;;CAQC,GACD,OAAO,MAAMC,0BACX,CAACC,SACD,OAAOC;QACL,IAAI;YACF,IAAI,CAAE,MAAMD,OAAO;gBAAEC;YAAI,IAAK;gBAC5B,OAAOC,SAASC,IAAI,CAAC;oBAAEC,OAAO;gBAAe,GAAG;oBAAEC,QAAQ;gBAAI;YAChE;YAEA,MAAMC,OAAO,UAAUL,OAAO,OAAOA,IAAIE,IAAI,KAAK,aAAa,MAAMF,IAAIE,IAAI,KAAK;YAElF,MAAM,EAAEI,EAAE,EAAEC,UAAU,EAAEC,MAAM,EAAEC,MAAM,EAAE,GAAGZ,6BAA6Ba,KAAK,CAACL;YAE9E,MAAMM,eA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