@payloadcms/transformer-sharp 4.0.0-beta.0 → 4.0.0-beta.10

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 (36) hide show
  1. package/dist/createTransformUpload.d.ts +14 -0
  2. package/dist/createTransformUpload.d.ts.map +1 -0
  3. package/dist/{prepareLegacyUpload.js → createTransformUpload.js} +15 -24
  4. package/dist/createTransformUpload.js.map +1 -0
  5. package/dist/{prepareLegacyUpload.spec.js → createTransformUpload.spec.js} +12 -24
  6. package/dist/createTransformUpload.spec.js.map +1 -0
  7. package/dist/initSharpCollections.d.ts +6 -6
  8. package/dist/initSharpCollections.d.ts.map +1 -1
  9. package/dist/initSharpCollections.js +14 -58
  10. package/dist/initSharpCollections.js.map +1 -1
  11. package/dist/initSharpCollections.spec.js +20 -7
  12. package/dist/initSharpCollections.spec.js.map +1 -1
  13. package/dist/readSavedTransforms.d.ts +14 -0
  14. package/dist/readSavedTransforms.d.ts.map +1 -0
  15. package/dist/readSavedTransforms.js +42 -0
  16. package/dist/readSavedTransforms.js.map +1 -0
  17. package/dist/sharpTransformer.d.ts.map +1 -1
  18. package/dist/sharpTransformer.js +14 -6
  19. package/dist/sharpTransformer.js.map +1 -1
  20. package/dist/sharpTransformer.spec.js +30 -0
  21. package/dist/sharpTransformer.spec.js.map +1 -1
  22. package/dist/transformFile.d.ts +4 -4
  23. package/dist/transformFile.d.ts.map +1 -1
  24. package/dist/transformFile.js +31 -16
  25. package/dist/transformFile.js.map +1 -1
  26. package/dist/transformFile.spec.js +210 -24
  27. package/dist/transformFile.spec.js.map +1 -1
  28. package/dist/types.d.ts +23 -13
  29. package/dist/types.d.ts.map +1 -1
  30. package/dist/types.js +3 -2
  31. package/dist/types.js.map +1 -1
  32. package/package.json +17 -19
  33. package/dist/prepareLegacyUpload.d.ts +0 -14
  34. package/dist/prepareLegacyUpload.d.ts.map +0 -1
  35. package/dist/prepareLegacyUpload.js.map +0 -1
  36. package/dist/prepareLegacyUpload.spec.js.map +0 -1
@@ -132,27 +132,26 @@ describe('createTransformFile', ()=>{
132
132
  sharpDependency: sharp
133
133
  });
134
134
  const result = await transformFile({
135
- file,
136
- options: {
137
- collectionUpload: {
138
- resizeOptions
139
- },
140
- crop: {
141
- cropData: {
135
+ doc: {
136
+ _transforms: {
137
+ crop: {
142
138
  height: 40,
143
- unit: '%',
144
139
  width: 40,
145
140
  x: 25,
146
141
  y: 25
147
- },
148
- heightInPixels: 40,
149
- originalDimensions: {
150
- height: 100,
151
- width: 100
152
- },
153
- widthInPixels: 40
142
+ }
143
+ }
144
+ },
145
+ file,
146
+ options: {
147
+ collectionUpload: {
148
+ resizeOptions
154
149
  },
155
- kind: 'main'
150
+ kind: 'main',
151
+ originalDimensions: {
152
+ height: 100,
153
+ width: 100
154
+ }
156
155
  },
157
156
  req: makeReq()
158
157
  });
@@ -161,14 +160,138 @@ describe('createTransformFile', ()=>{
161
160
  expect(metadata.height).toBe(expectedSize);
162
161
  });
163
162
  });
163
+ describe('main crop', ()=>{
164
+ const cropMain = async ({ crop, cropSize, image })=>{
165
+ const transformFile = createTransformFile({
166
+ sharpDependency: sharp
167
+ });
168
+ const result = await transformFile({
169
+ doc: crop ? {
170
+ _transforms: {
171
+ crop
172
+ }
173
+ } : {},
174
+ file: new File([
175
+ image
176
+ ], 'photo.png', {
177
+ type: 'image/png'
178
+ }),
179
+ options: {
180
+ collectionUpload: {},
181
+ cropSize,
182
+ kind: 'main',
183
+ originalDimensions: {
184
+ height: 10,
185
+ width: 100
186
+ }
187
+ },
188
+ req: makeReq()
189
+ });
190
+ return sharp(await toBuffer(result.file));
191
+ };
192
+ it('should start the crop at the saved pixel, not 1px before it', async ()=>{
193
+ // Red columns 0-28, blue from column 29. The crop is read from `doc._transforms` in pixels,
194
+ // so it starts on the first blue column.
195
+ const blue = await makeImageBuffer({
196
+ background: {
197
+ b: 255,
198
+ g: 0,
199
+ r: 0
200
+ },
201
+ height: 10,
202
+ width: 71
203
+ });
204
+ const image = await sharp({
205
+ create: {
206
+ background: {
207
+ b: 0,
208
+ g: 0,
209
+ r: 255
210
+ },
211
+ channels: 3,
212
+ height: 10,
213
+ width: 100
214
+ }
215
+ }).composite([
216
+ {
217
+ input: blue,
218
+ left: 29,
219
+ top: 0
220
+ }
221
+ ]).png().toBuffer();
222
+ const cropped = await cropMain({
223
+ crop: {
224
+ height: 10,
225
+ width: 10,
226
+ x: 29,
227
+ y: 0
228
+ },
229
+ image
230
+ });
231
+ const raw = await cropped.raw().toBuffer({
232
+ resolveWithObject: true
233
+ });
234
+ expect(sampleRawPixel({
235
+ ...raw,
236
+ x: 0,
237
+ y: 0
238
+ })).toEqual({
239
+ b: 255,
240
+ g: 0,
241
+ r: 0
242
+ });
243
+ });
244
+ it('should keep a crop inside the image when the request crop size is larger than the saved crop', async ()=>{
245
+ // The request's `widthInPixels` is 70, and 31 + 70 would pass the right edge of a 100px image.
246
+ const cropped = await cropMain({
247
+ crop: {
248
+ height: 10,
249
+ width: 69,
250
+ x: 31,
251
+ y: 0
252
+ },
253
+ cropSize: {
254
+ height: 10,
255
+ width: 70
256
+ },
257
+ image: await makeImageBuffer({
258
+ height: 10,
259
+ width: 100
260
+ })
261
+ });
262
+ expect((await cropped.metadata()).width).toBe(70);
263
+ });
264
+ it('should extract the request crop size from the top-left corner when no crop is saved', async ()=>{
265
+ // A full-image selection saves no crop, but the request can still send a smaller
266
+ // `widthInPixels`/`heightInPixels` to extract.
267
+ const cropped = await cropMain({
268
+ cropSize: {
269
+ height: 5,
270
+ width: 20
271
+ },
272
+ image: await makeImageBuffer({
273
+ height: 10,
274
+ width: 100
275
+ })
276
+ });
277
+ expect(await cropped.metadata()).toMatchObject({
278
+ height: 5,
279
+ width: 20
280
+ });
281
+ });
282
+ });
164
283
  describe('size (transformSize)', ()=>{
165
284
  // Each original forces one resize-priority branch, and a focal point at 80% pushes the
166
285
  // 50px extract window against the clamped far edge, so a correct crop is entirely blue.
167
286
  it.each([
168
287
  {
169
- focalPoint: {
170
- x: 80,
171
- y: 50
288
+ doc: {
289
+ _transforms: {
290
+ focalPoint: {
291
+ x: 79.6,
292
+ y: 50
293
+ }
294
+ }
172
295
  },
173
296
  original: {
174
297
  height: 100,
@@ -186,10 +309,11 @@ describe('createTransformFile', ()=>{
186
309
  }
187
310
  ]
188
311
  },
312
+ // A document saved before `_transforms` existed has only `focalX`/`focalY`.
189
313
  {
190
- focalPoint: {
191
- x: 50,
192
- y: 80
314
+ doc: {
315
+ focalX: 50,
316
+ focalY: 80
193
317
  },
194
318
  original: {
195
319
  height: 200,
@@ -207,7 +331,7 @@ describe('createTransformFile', ()=>{
207
331
  }
208
332
  ]
209
333
  }
210
- ])('should extract the focal-point region along the $original.splitAxis axis', async ({ focalPoint, original, samples })=>{
334
+ ])('should extract the saved focal-point region along the $original.splitAxis axis', async ({ doc, original, samples })=>{
211
335
  const buffer = await makeTwoColorImage(original);
212
336
  const file = new File([
213
337
  buffer
@@ -218,16 +342,17 @@ describe('createTransformFile', ()=>{
218
342
  sharpDependency: sharp
219
343
  });
220
344
  const result = await transformFile({
345
+ doc,
221
346
  file,
222
347
  options: {
223
348
  collectionUpload: {},
224
- focalPoint,
225
349
  imageResizeConfig: {
226
350
  name: 'thumb',
227
351
  height: 50,
228
352
  width: 50
229
353
  },
230
354
  kind: 'size',
355
+ canUseFocalPoint: true,
231
356
  originalDimensions: {
232
357
  height: original.height,
233
358
  width: original.width
@@ -253,6 +378,67 @@ describe('createTransformFile', ()=>{
253
378
  });
254
379
  }
255
380
  });
381
+ // A focal point at the center is not saved, so it means "no focal point". The size then uses
382
+ // its own `position`: a left-aligned 50px cut of the 100px resize is red. A cut around the
383
+ // center would end on blue.
384
+ it.each([
385
+ {
386
+ name: 'no saved focal point',
387
+ doc: {}
388
+ },
389
+ {
390
+ name: 'a legacy focal point at the center',
391
+ doc: {
392
+ focalX: 50,
393
+ focalY: 50
394
+ }
395
+ }
396
+ ])('should resize with the size config when there is $name', async ({ doc })=>{
397
+ const buffer = await makeTwoColorImage({
398
+ height: 100,
399
+ splitAxis: 'x',
400
+ width: 200
401
+ });
402
+ const transformFile = createTransformFile({
403
+ sharpDependency: sharp
404
+ });
405
+ const result = await transformFile({
406
+ doc,
407
+ file: new File([
408
+ buffer
409
+ ], 'photo.png', {
410
+ type: 'image/png'
411
+ }),
412
+ options: {
413
+ canUseFocalPoint: true,
414
+ collectionUpload: {},
415
+ imageResizeConfig: {
416
+ name: 'thumb',
417
+ height: 50,
418
+ position: 'left',
419
+ width: 50
420
+ },
421
+ kind: 'size',
422
+ originalDimensions: {
423
+ height: 100,
424
+ width: 200
425
+ }
426
+ },
427
+ req: makeReq()
428
+ });
429
+ const raw = await sharp(await toBuffer(result.file)).raw().toBuffer({
430
+ resolveWithObject: true
431
+ });
432
+ expect(sampleRawPixel({
433
+ ...raw,
434
+ x: 40,
435
+ y: 25
436
+ })).toEqual({
437
+ b: 0,
438
+ g: 0,
439
+ r: 255
440
+ });
441
+ });
256
442
  });
257
443
  });
258
444
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/transformFile.spec.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport sharp from 'sharp'\nimport { describe, expect, it } from 'vitest'\n\nimport type { SharpUploadTaskOptions } from './types.js'\n\nimport { createTransformFile } from './transformFile.js'\n\nconst makeReq = (): PayloadRequest => ({}) as PayloadRequest\n\nconst toBuffer = async (file: File): Promise<Buffer> => Buffer.from(await file.arrayBuffer())\n\nconst makeImageBuffer = async ({\n background = { b: 0, g: 128, r: 255 },\n height,\n width,\n}: {\n background?: { b: number; g: number; r: number }\n height: number\n width: number\n}): Promise<Buffer> =>\n sharp({ create: { background, channels: 3, height, width } })\n .png()\n .toBuffer()\n\n/**\n * A two-colour image split along `splitAxis` (red/blue halves) — proves the\n * focal-point extract region in `transformSize` lands where the math says,\n * not just that the output dimensions are right.\n */\nconst makeTwoColorImage = async ({\n height,\n splitAxis,\n width,\n}: {\n height: number\n splitAxis: 'x' | 'y'\n width: number\n}): Promise<Buffer> => {\n const raw = Buffer.alloc(width * height * 3)\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (y * width + x) * 3\n const isFirstHalf = splitAxis === 'x' ? x < width / 2 : y < height / 2\n\n if (isFirstHalf) {\n raw[idx] = 255 // red\n } else {\n raw[idx + 2] = 255 // blue\n }\n }\n }\n\n return sharp(raw, { raw: { channels: 3, height, width } })\n .png()\n .toBuffer()\n}\n\nconst sampleRawPixel = ({\n data,\n info,\n x,\n y,\n}: {\n data: Buffer\n info: { channels: number; width: number }\n x: number\n y: number\n}): { b: number; g: number; r: number } => {\n const idx = (y * info.width + x) * info.channels\n return { b: data[idx + 2]!, g: data[idx + 1]!, r: data[idx]! }\n}\n\ndescribe('createTransformFile', () => {\n describe('main (transformMain)', () => {\n it('should trim uniform-colour padding from the main file', async () => {\n const square = await makeImageBuffer({\n background: { b: 0, g: 0, r: 0 },\n height: 20,\n width: 20,\n })\n const framed = await sharp({\n create: { background: { b: 255, g: 255, r: 255 }, channels: 3, height: 60, width: 60 },\n })\n .composite([{ input: square, left: 20, top: 20 }])\n .png()\n .toBuffer()\n const file = new File([framed], 'photo.png', { type: 'image/png' })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n file,\n options: {\n collectionUpload: { trimOptions: {} },\n kind: 'main',\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const metadata = await sharp(await toBuffer(result.file!)).metadata()\n expect(metadata.width).toBe(20)\n expect(metadata.height).toBe(20)\n })\n\n it.each([\n // Re-applied by default, so the 40x40 crop is resized down to 20x20.\n { expectedSize: 20, resizeOptions: { fit: 'cover' as const, height: 20, width: 20 } },\n { expectedSize: 40, resizeOptions: { height: 20, width: 20, withoutEnlargement: true } },\n ])(\n 'should re-apply resizeOptions to the crop output unless withoutEnlargement is set (%#)',\n async ({ expectedSize, resizeOptions }) => {\n const buffer = await makeImageBuffer({ height: 100, width: 100 })\n const file = new File([buffer], 'photo.png', { type: 'image/png' })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n file,\n options: {\n collectionUpload: { resizeOptions },\n crop: {\n cropData: { height: 40, unit: '%', width: 40, x: 25, y: 25 },\n heightInPixels: 40,\n originalDimensions: { height: 100, width: 100 },\n widthInPixels: 40,\n },\n kind: 'main',\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const metadata = await sharp(await toBuffer(result.file!)).metadata()\n expect(metadata.width).toBe(expectedSize)\n expect(metadata.height).toBe(expectedSize)\n },\n )\n })\n\n describe('size (transformSize)', () => {\n // Each original forces one resize-priority branch, and a focal point at 80% pushes the\n // 50px extract window against the clamped far edge, so a correct crop is entirely blue.\n it.each([\n {\n focalPoint: { x: 80, y: 50 },\n original: { height: 100, splitAxis: 'x' as const, width: 200 },\n samples: [\n { x: 10, y: 25 },\n { x: 40, y: 25 },\n ],\n },\n {\n focalPoint: { x: 50, y: 80 },\n original: { height: 200, splitAxis: 'y' as const, width: 100 },\n samples: [\n { x: 25, y: 10 },\n { x: 25, y: 40 },\n ],\n },\n ])(\n 'should extract the focal-point region along the $original.splitAxis axis',\n async ({ focalPoint, original, samples }) => {\n const buffer = await makeTwoColorImage(original)\n const file = new File([buffer], 'photo.png', { type: 'image/png' })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n file,\n options: {\n collectionUpload: {},\n focalPoint,\n imageResizeConfig: { name: 'thumb', height: 50, width: 50 },\n kind: 'size',\n originalDimensions: { height: original.height, width: original.width },\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const { data, info } = await sharp(await toBuffer(result.file!))\n .raw()\n .toBuffer({ resolveWithObject: true })\n expect(info.width).toBe(50)\n expect(info.height).toBe(50)\n for (const { x, y } of samples) {\n expect(sampleRawPixel({ data, info, x, y })).toEqual({ b: 255, g: 0, r: 0 })\n }\n },\n )\n })\n})\n"],"names":["sharp","describe","expect","it","createTransformFile","makeReq","toBuffer","file","Buffer","from","arrayBuffer","makeImageBuffer","background","b","g","r","height","width","create","channels","png","makeTwoColorImage","splitAxis","raw","alloc","y","x","idx","isFirstHalf","sampleRawPixel","data","info","square","framed","composite","input","left","top","File","type","transformFile","sharpDependency","result","options","collectionUpload","trimOptions","kind","req","metadata","toBe","each","expectedSize","resizeOptions","fit","withoutEnlargement","buffer","crop","cropData","unit","heightInPixels","originalDimensions","widthInPixels","focalPoint","original","samples","imageResizeConfig","name","resolveWithObject","toEqual"],"mappings":"AAEA,OAAOA,WAAW,QAAO;AACzB,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAI7C,SAASC,mBAAmB,QAAQ,qBAAoB;AAExD,MAAMC,UAAU,IAAuB,CAAA,CAAC,CAAA;AAExC,MAAMC,WAAW,OAAOC,OAAgCC,OAAOC,IAAI,CAAC,MAAMF,KAAKG,WAAW;AAE1F,MAAMC,kBAAkB,OAAO,EAC7BC,aAAa;IAAEC,GAAG;IAAGC,GAAG;IAAKC,GAAG;AAAI,CAAC,EACrCC,MAAM,EACNC,KAAK,EAKN,GACCjB,MAAM;QAAEkB,QAAQ;YAAEN;YAAYO,UAAU;YAAGH;YAAQC;QAAM;IAAE,GACxDG,GAAG,GACHd,QAAQ;AAEb;;;;CAIC,GACD,MAAMe,oBAAoB,OAAO,EAC/BL,MAAM,EACNM,SAAS,EACTL,KAAK,EAKN;IACC,MAAMM,MAAMf,OAAOgB,KAAK,CAACP,QAAQD,SAAS;IAE1C,IAAK,IAAIS,IAAI,GAAGA,IAAIT,QAAQS,IAAK;QAC/B,IAAK,IAAIC,IAAI,GAAGA,IAAIT,OAAOS,IAAK;YAC9B,MAAMC,MAAM,AAACF,CAAAA,IAAIR,QAAQS,CAAAA,IAAK;YAC9B,MAAME,cAAcN,cAAc,MAAMI,IAAIT,QAAQ,IAAIQ,IAAIT,SAAS;YAErE,IAAIY,aAAa;gBACfL,GAAG,CAACI,IAAI,GAAG,KAAI,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nC,IAAI,GAC1DgB,GAAG,GACHjB,QAAQ,CAAC;gBAAE6D,mBAAmB;YAAK;YACtCjE,OAAO6B,KAAKd,KAAK,EAAEgC,IAAI,CAAC;YACxB/C,OAAO6B,KAAKf,MAAM,EAAEiC,IAAI,CAAC;YACzB,KAAK,MAAM,EAAEvB,CAAC,EAAED,CAAC,EAAE,IAAIuC,QAAS;gBAC9B9D,OAAO2B,eAAe;oBAAEC;oBAAMC;oBAAML;oBAAGD;gBAAE,IAAI2C,OAAO,CAAC;oBAAEvD,GAAG;oBAAKC,GAAG;oBAAGC,GAAG;gBAAE;YAC5E;QACF;IAEJ;AACF"}
1
+ {"version":3,"sources":["../src/transformFile.spec.ts"],"sourcesContent":["import type { Document, PayloadRequest } from 'payload'\n\nimport sharp from 'sharp'\nimport { describe, expect, it } from 'vitest'\n\nimport type { SharpUploadTaskOptions } from './types.js'\n\nimport { createTransformFile } from './transformFile.js'\n\nconst makeReq = (): PayloadRequest => ({}) as PayloadRequest\n\nconst toBuffer = async (file: File): Promise<Buffer> => Buffer.from(await file.arrayBuffer())\n\nconst makeImageBuffer = async ({\n background = { b: 0, g: 128, r: 255 },\n height,\n width,\n}: {\n background?: { b: number; g: number; r: number }\n height: number\n width: number\n}): Promise<Buffer> =>\n sharp({ create: { background, channels: 3, height, width } })\n .png()\n .toBuffer()\n\n/**\n * A two-colour image split along `splitAxis` (red/blue halves) — proves the\n * focal-point extract region in `transformSize` lands where the math says,\n * not just that the output dimensions are right.\n */\nconst makeTwoColorImage = async ({\n height,\n splitAxis,\n width,\n}: {\n height: number\n splitAxis: 'x' | 'y'\n width: number\n}): Promise<Buffer> => {\n const raw = Buffer.alloc(width * height * 3)\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (y * width + x) * 3\n const isFirstHalf = splitAxis === 'x' ? x < width / 2 : y < height / 2\n\n if (isFirstHalf) {\n raw[idx] = 255 // red\n } else {\n raw[idx + 2] = 255 // blue\n }\n }\n }\n\n return sharp(raw, { raw: { channels: 3, height, width } })\n .png()\n .toBuffer()\n}\n\nconst sampleRawPixel = ({\n data,\n info,\n x,\n y,\n}: {\n data: Buffer\n info: { channels: number; width: number }\n x: number\n y: number\n}): { b: number; g: number; r: number } => {\n const idx = (y * info.width + x) * info.channels\n return { b: data[idx + 2]!, g: data[idx + 1]!, r: data[idx]! }\n}\n\ndescribe('createTransformFile', () => {\n describe('main (transformMain)', () => {\n it('should trim uniform-colour padding from the main file', async () => {\n const square = await makeImageBuffer({\n background: { b: 0, g: 0, r: 0 },\n height: 20,\n width: 20,\n })\n const framed = await sharp({\n create: { background: { b: 255, g: 255, r: 255 }, channels: 3, height: 60, width: 60 },\n })\n .composite([{ input: square, left: 20, top: 20 }])\n .png()\n .toBuffer()\n const file = new File([framed], 'photo.png', { type: 'image/png' })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n file,\n options: {\n collectionUpload: { trimOptions: {} },\n kind: 'main',\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const metadata = await sharp(await toBuffer(result.file!)).metadata()\n expect(metadata.width).toBe(20)\n expect(metadata.height).toBe(20)\n })\n\n it.each([\n // Re-applied by default, so the 40x40 crop is resized down to 20x20.\n { expectedSize: 20, resizeOptions: { fit: 'cover' as const, height: 20, width: 20 } },\n { expectedSize: 40, resizeOptions: { height: 20, width: 20, withoutEnlargement: true } },\n ])(\n 'should re-apply resizeOptions to the crop output unless withoutEnlargement is set (%#)',\n async ({ expectedSize, resizeOptions }) => {\n const buffer = await makeImageBuffer({ height: 100, width: 100 })\n const file = new File([buffer], 'photo.png', { type: 'image/png' })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n doc: { _transforms: { crop: { height: 40, width: 40, x: 25, y: 25 } } },\n file,\n options: {\n collectionUpload: { resizeOptions },\n kind: 'main',\n originalDimensions: { height: 100, width: 100 },\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const metadata = await sharp(await toBuffer(result.file!)).metadata()\n expect(metadata.width).toBe(expectedSize)\n expect(metadata.height).toBe(expectedSize)\n },\n )\n })\n\n describe('main crop', () => {\n const cropMain = async ({\n crop,\n cropSize,\n image,\n }: {\n crop?: { height: number; width: number; x: number; y: number }\n cropSize?: { height: number; width: number }\n image: Buffer\n }) => {\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n doc: crop ? { _transforms: { crop } } : {},\n file: new File([image], 'photo.png', { type: 'image/png' }),\n options: {\n collectionUpload: {},\n cropSize,\n kind: 'main',\n originalDimensions: { height: 10, width: 100 },\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n return sharp(await toBuffer(result.file!))\n }\n\n it('should start the crop at the saved pixel, not 1px before it', async () => {\n // Red columns 0-28, blue from column 29. The crop is read from `doc._transforms` in pixels,\n // so it starts on the first blue column.\n const blue = await makeImageBuffer({\n background: { b: 255, g: 0, r: 0 },\n height: 10,\n width: 71,\n })\n const image = await sharp({\n create: { background: { b: 0, g: 0, r: 255 }, channels: 3, height: 10, width: 100 },\n })\n .composite([{ input: blue, left: 29, top: 0 }])\n .png()\n .toBuffer()\n\n const cropped = await cropMain({ crop: { height: 10, width: 10, x: 29, y: 0 }, image })\n\n const raw = await cropped.raw().toBuffer({ resolveWithObject: true })\n expect(sampleRawPixel({ ...raw, x: 0, y: 0 })).toEqual({ b: 255, g: 0, r: 0 })\n })\n\n it('should keep a crop inside the image when the request crop size is larger than the saved crop', async () => {\n // The request's `widthInPixels` is 70, and 31 + 70 would pass the right edge of a 100px image.\n const cropped = await cropMain({\n crop: { height: 10, width: 69, x: 31, y: 0 },\n cropSize: { height: 10, width: 70 },\n image: await makeImageBuffer({ height: 10, width: 100 }),\n })\n\n expect((await cropped.metadata()).width).toBe(70)\n })\n\n it('should extract the request crop size from the top-left corner when no crop is saved', async () => {\n // A full-image selection saves no crop, but the request can still send a smaller\n // `widthInPixels`/`heightInPixels` to extract.\n const cropped = await cropMain({\n cropSize: { height: 5, width: 20 },\n image: await makeImageBuffer({ height: 10, width: 100 }),\n })\n\n expect(await cropped.metadata()).toMatchObject({ height: 5, width: 20 })\n })\n })\n\n describe('size (transformSize)', () => {\n // Each original forces one resize-priority branch, and a focal point at 80% pushes the\n // 50px extract window against the clamped far edge, so a correct crop is entirely blue.\n it.each<{\n doc: Document\n original: { height: number; splitAxis: 'x' | 'y'; width: number }\n samples: { x: number; y: number }[]\n }>([\n {\n doc: { _transforms: { focalPoint: { x: 79.6, y: 50 } } },\n original: { height: 100, splitAxis: 'x', width: 200 },\n samples: [\n { x: 10, y: 25 },\n { x: 40, y: 25 },\n ],\n },\n // A document saved before `_transforms` existed has only `focalX`/`focalY`.\n {\n doc: { focalX: 50, focalY: 80 },\n original: { height: 200, splitAxis: 'y', width: 100 },\n samples: [\n { x: 25, y: 10 },\n { x: 25, y: 40 },\n ],\n },\n ])(\n 'should extract the saved focal-point region along the $original.splitAxis axis',\n async ({ doc, original, samples }) => {\n const buffer = await makeTwoColorImage(original)\n const file = new File([buffer], 'photo.png', { type: 'image/png' })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n doc,\n file,\n options: {\n collectionUpload: {},\n imageResizeConfig: { name: 'thumb', height: 50, width: 50 },\n kind: 'size',\n canUseFocalPoint: true,\n originalDimensions: { height: original.height, width: original.width },\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const { data, info } = await sharp(await toBuffer(result.file!))\n .raw()\n .toBuffer({ resolveWithObject: true })\n expect(info.width).toBe(50)\n expect(info.height).toBe(50)\n for (const { x, y } of samples) {\n expect(sampleRawPixel({ data, info, x, y })).toEqual({ b: 255, g: 0, r: 0 })\n }\n },\n )\n\n // A focal point at the center is not saved, so it means \"no focal point\". The size then uses\n // its own `position`: a left-aligned 50px cut of the 100px resize is red. A cut around the\n // center would end on blue.\n it.each<{ doc: Document; name: string }>([\n { name: 'no saved focal point', doc: {} },\n { name: 'a legacy focal point at the center', doc: { focalX: 50, focalY: 50 } },\n ])('should resize with the size config when there is $name', async ({ doc }) => {\n const buffer = await makeTwoColorImage({ height: 100, splitAxis: 'x', width: 200 })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n doc,\n file: new File([buffer], 'photo.png', { type: 'image/png' }),\n options: {\n canUseFocalPoint: true,\n collectionUpload: {},\n imageResizeConfig: { name: 'thumb', height: 50, position: 'left', width: 50 },\n kind: 'size',\n originalDimensions: { height: 100, width: 200 },\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const raw = await sharp(await toBuffer(result.file!))\n .raw()\n .toBuffer({ resolveWithObject: true })\n expect(sampleRawPixel({ ...raw, x: 40, y: 25 })).toEqual({ b: 0, g: 0, r: 255 })\n })\n })\n})\n"],"names":["sharp","describe","expect","it","createTransformFile","makeReq","toBuffer","file","Buffer","from","arrayBuffer","makeImageBuffer","background","b","g","r","height","width","create","channels","png","makeTwoColorImage","splitAxis","raw","alloc","y","x","idx","isFirstHalf","sampleRawPixel","data","info","square","framed","composite","input","left","top","File","type","transformFile","sharpDependency","result","options","collectionUpload","trimOptions","kind","req","metadata","toBe","each","expectedSize","resizeOptions","fit","withoutEnlargement","buffer","doc","_transforms","crop","originalDimensions","cropMain","cropSize","image","blue","cropped","resolveWithObject","toEqual","toMatchObject","focalPoint","original","samples","focalX","focalY","imageResizeConfig","name","canUseFocalPoint","position"],"mappings":"AAEA,OAAOA,WAAW,QAAO;AACzB,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAI7C,SAASC,mBAAmB,QAAQ,qBAAoB;AAExD,MAAMC,UAAU,IAAuB,CAAA,CAAC,CAAA;AAExC,MAAMC,WAAW,OAAOC,OAAgCC,OAAOC,IAAI,CAAC,MAAMF,KAAKG,WAAW;AAE1F,MAAMC,kBAAkB,OAAO,EAC7BC,aAAa;IAAEC,GAAG;IAAGC,GAAG;IAAKC,GAAG;AAAI,CAAC,EACrCC,MA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MAAM;wBAAS1D,QAAQ;wBAAI4D,UAAU;wBAAQ3D,OAAO;oBAAG;oBAC5E6B,MAAM;oBACNa,oBAAoB;wBAAE3C,QAAQ;wBAAKC,OAAO;oBAAI;gBAChD;gBACA8B,KAAK1C;YACP;YAEA,MAAMkB,MAAM,MAAMvB,MAAM,MAAMM,SAASoC,OAAOnC,IAAI,GAC/CgB,GAAG,GACHjB,QAAQ,CAAC;gBAAE2D,mBAAmB;YAAK;YACtC/D,OAAO2B,eAAe;gBAAE,GAAGN,GAAG;gBAAEG,GAAG;gBAAID,GAAG;YAAG,IAAIyC,OAAO,CAAC;gBAAErD,GAAG;gBAAGC,GAAG;gBAAGC,GAAG;YAAI;QAChF;IACF;AACF"}
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { FocalPoint, ImageSize, PayloadRequest, ProbedImageSize, UploadCollectionSlug, UploadEdits } from 'payload';
1
+ import type { ImageSize, PayloadRequest, ProbedImageSize, UploadCollectionSlug } from 'payload';
2
2
  import type { FitEnum, ResizeOptions, Sharp, Metadata as SharpMetadata, SharpOptions } from 'sharp';
3
3
  /**
4
4
  * Params sent to the sharp `toFormat()` function
@@ -128,23 +128,33 @@ export type SharpTransformerOptions = {
128
128
  };
129
129
  /**
130
130
  * `options` for the one-file-in/one-file-out `transformFile` primitive, computed
131
- * by `prepareLegacyUpload` for each task it hands to the injected `transform`
132
- * callback: the main file (optionally a crop), or one named legacy image size.
131
+ * by `createTransformUpload` for each task it hands to the injected `transform`
132
+ * callback: the main file, or one named legacy image size. The crop and focal point
133
+ * are not options: `transformFile` reads them from `doc._transforms`.
133
134
  */
134
135
  export type SharpUploadTaskOptions = {
136
+ /**
137
+ * Whether this size may be cut around a focal point: the focal point is enabled, and the
138
+ * size's `fit` allows a cut. `transformFile` cuts around it only when one is saved, and
139
+ * otherwise resizes with the size's own config.
140
+ */
141
+ canUseFocalPoint?: boolean;
135
142
  collectionUpload: SharpCollectionConfig;
136
- crop?: {
137
- cropData: NonNullable<UploadEdits['crop']>;
138
- heightInPixels: number;
139
- originalDimensions: ProbedImageSize;
140
- widthInPixels: number;
141
- };
142
- kind: 'main';
143
- } | {
144
- collectionUpload: SharpCollectionConfig;
145
- focalPoint?: FocalPoint;
146
143
  imageResizeConfig: ImageSize;
147
144
  kind: 'size';
148
145
  originalDimensions: ProbedImageSize;
146
+ } | {
147
+ collectionUpload: SharpCollectionConfig;
148
+ /**
149
+ * The pixel size of a crop sent in the request (`uploadEdits.widthInPixels` and
150
+ * `heightInPixels`). It replaces the saved crop's size for this upload only.
151
+ */
152
+ cropSize?: {
153
+ height: number;
154
+ width: number;
155
+ };
156
+ kind: 'main';
157
+ /** The original's size. Without it, the saved crop cannot be applied. */
158
+ originalDimensions?: ProbedImageSize;
149
159
  };
150
160
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EACV,SAAS,EACT,cAAc,EACd,eAAe,EACf,oBAAoB,EACpB,WAAW,EACZ,MAAM,SAAS,CAAA;AAChB,OAAO,KAAK,EAAE,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,IAAI,aAAa,EAAE,YAAY,EAAE,MAAM,OAAO,CAAA;AAEnG;;;GAGG;AACH,MAAM,MAAM,wBAAwB,GAAG;IACrC,MAAM,EAAE,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACxC,OAAO,CAAC,EAAE,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;CAC3C,CAAA;AAED;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAAG,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAEjE,MAAM,MAAM,YAAY,GACpB,CAAC,CAAC,OAAO,EAAE;IAAE,QAAQ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ACE,gBAAgB,EAAE,qBAAqB,CAAA;IACvC;;;OAGG;IACH,QAAQ,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAA;IAC5C,IAAI,EAAE,MAAM,CAAA;IACZ,yEAAyE;IACzE,kBAAkB,CAAC,EAAE,eAAe,CAAA;CACrC,CAAA"}
package/dist/types.js CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * `options` for the one-file-in/one-file-out `transformFile` primitive, computed
3
- * by `prepareLegacyUpload` for each task it hands to the injected `transform`
4
- * callback: the main file (optionally a crop), or one named legacy image size.
3
+ * by `createTransformUpload` for each task it hands to the injected `transform`
4
+ * callback: the main file, or one named legacy image size. The crop and focal point
5
+ * are not options: `transformFile` reads them from `doc._transforms`.
5
6
  */ export { };
6
7
 
7
8
  //# sourceMappingURL=types.js.map
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n FocalPoint,\n ImageSize,\n PayloadRequest,\n ProbedImageSize,\n UploadCollectionSlug,\n UploadEdits,\n} from 'payload'\nimport type { FitEnum, ResizeOptions, Sharp, Metadata as SharpMetadata, SharpOptions } from 'sharp'\n\n/**\n * Params sent to the sharp `toFormat()` function\n * @link https://sharp.pixelplumbing.com/api-output#toformat\n */\nexport type ImageUploadFormatOptions = {\n format: Parameters<Sharp['toFormat']>[0]\n options?: Parameters<Sharp['toFormat']>[1]\n}\n\n/**\n * Params sent to the sharp trim() function\n * @link https://sharp.pixelplumbing.com/api-resize#trim\n */\nexport type ImageUploadTrimOptions = Parameters<Sharp['trim']>[0]\n\nexport type WithMetadata =\n | ((options: { metadata: SharpMetadata; req: PayloadRequest }) => Promise<boolean>)\n | boolean\n\n/**\n * Image size options implemented by Payload's default Sharp image processor.\n */\nexport type SharpImageSizeOptions = {\n /**\n * @deprecated prefer position\n */\n crop?: string // comes from sharp package\n formatOptions?: ImageUploadFormatOptions\n trimOptions?: ImageUploadTrimOptions\n /** Image sizes generated for each upload, stored under the document's `variants`. */\n variants?: ImageSize[]\n /**\n * When an uploaded image is smaller than the defined image size, we have 3 options:\n *\n * `undefined | false | true`\n *\n * 1. `undefined` [default]: uploading images with smaller width AND height than the image size will return null\n * 2. `false`: always enlarge images to the image size\n * 3. `true`: if the image is smaller than the image size, return the original image\n */\n withoutEnlargement?: ResizeOptions['withoutEnlargement']\n} & Omit<ResizeOptions, 'withoutEnlargement'>\n\ndeclare module 'payload' {\n interface RegisteredImageSizeOptions {\n sharp: SharpImageSizeOptions\n }\n}\n\n/**\n * A collection's Sharp-owned upload-time settings, authored via\n * `sharpTransformer({ collections: { <slug>: {...} } })`. `init()` writes a\n * narrowed, Sharp-agnostic projection of `variants`/`crop`/`focalPoint`\n * back onto the sanitized collection's `upload` config for core's own use (Admin UI,\n * field generation); this richer shape is what the transformer itself reads.\n */\nexport type SharpCollectionConfig = {\n constructorOptions?: SharpOptions\n crop?: boolean\n focalPoint?: boolean\n formatOptions?: ImageUploadFormatOptions\n resizeOptions?: ResizeOptions\n trimOptions?: ImageUploadTrimOptions\n /** Image sizes generated for each upload, stored under the document's `variants`. */\n variants?: ImageSize[]\n withMetadata?: WithMetadata\n}\n\n/**\n * Matches core's (soon-removed) `SharpDependency` shape, for advanced injection\n * of a compatible custom Sharp build or version via `sharpTransformer({ sharp })`.\n */\nexport type SharpDependency = (\n input?:\n | ArrayBuffer\n | Buffer\n | Float32Array\n | Float64Array\n | Int8Array\n | Int16Array\n | Int32Array\n | string\n | Uint8Array\n | Uint8ClampedArray\n | Uint16Array\n | Uint32Array,\n options?: SharpOptions,\n) => Sharp\n\nexport type SharpDynamicDefaults = {\n /** @default 'cover' */\n fit?: keyof FitEnum\n /** @default 4096 */\n maxHeight?: number\n /**\n * Total output pixels, counted across every frame of an animated image.\n * @default 16_777_216\n */\n maxPixels?: number\n /** @default 4096 */\n maxWidth?: number\n /** @default 'center' */\n position?: ResizeOptions['position']\n /** @default false */\n withoutEnlargement?: boolean\n}\n\n/**\n * Enables request-time resizing and tunes its limits. `collections` restricts it\n * to the listed upload collections; omit it to allow every upload collection.\n */\nexport type SharpDynamicOptions = {\n collections?: UploadCollectionSlug[]\n} & SharpDynamicDefaults\n\n/**\n * The result of parsing a request's dynamic resize query parameters.\n * `isRouted: false` means none of the recognized parameters were present at\n * all — an ordinary file read, not a dynamic transformation attempt.\n */\nexport type DynamicResizeParseResult =\n | {\n error: string\n isRouted: true\n valid: false\n }\n | {\n height?: number\n isRouted: true\n valid: true\n width?: number\n withoutEnlargement?: boolean\n }\n | {\n isRouted: false\n }\n\nexport type SharpTransformerOptions = {\n /** Per-collection upload-time image processing settings. */\n collections?: Partial<Record<UploadCollectionSlug, SharpCollectionConfig>>\n /**\n * Request-time resizing via `?width=`/`?height=` on the file endpoint. `true`\n * enables it with default limits for every upload collection; an object enables\n * it with custom limits, optionally restricted to specific collections.\n *\n * @default false\n */\n dynamic?: boolean | SharpDynamicOptions\n /** Inject a compatible custom Sharp build or version. Defaults to the bundled dependency. */\n sharp?: SharpDependency\n /** @default 'sharp' */\n slug?: string\n}\n\n/**\n * `options` for the one-file-in/one-file-out `transformFile` primitive, computed\n * by `prepareLegacyUpload` for each task it hands to the injected `transform`\n * callback: the main file (optionally a crop), or one named legacy image size.\n */\nexport type SharpUploadTaskOptions =\n | {\n collectionUpload: SharpCollectionConfig\n crop?: {\n cropData: NonNullable<UploadEdits['crop']>\n heightInPixels: number\n originalDimensions: ProbedImageSize\n widthInPixels: number\n }\n kind: 'main'\n }\n | {\n collectionUpload: SharpCollectionConfig\n focalPoint?: FocalPoint\n imageResizeConfig: ImageSize\n kind: 'size'\n originalDimensions: ProbedImageSize\n }\n"],"names":[],"mappings":"AAoKA;;;;CAIC,GACD,WAiBK"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { ImageSize, PayloadRequest, ProbedImageSize, UploadCollectionSlug } from 'payload'\nimport type { FitEnum, ResizeOptions, Sharp, Metadata as SharpMetadata, SharpOptions } from 'sharp'\n\n/**\n * Params sent to the sharp `toFormat()` function\n * @link https://sharp.pixelplumbing.com/api-output#toformat\n */\nexport type ImageUploadFormatOptions = {\n format: Parameters<Sharp['toFormat']>[0]\n options?: Parameters<Sharp['toFormat']>[1]\n}\n\n/**\n * Params sent to the sharp trim() function\n * @link https://sharp.pixelplumbing.com/api-resize#trim\n */\nexport type ImageUploadTrimOptions = Parameters<Sharp['trim']>[0]\n\nexport type WithMetadata =\n | ((options: { metadata: SharpMetadata; req: PayloadRequest }) => Promise<boolean>)\n | boolean\n\n/**\n * Image size options implemented by Payload's default Sharp image processor.\n */\nexport type SharpImageSizeOptions = {\n /**\n * @deprecated prefer position\n */\n crop?: string // comes from sharp package\n formatOptions?: ImageUploadFormatOptions\n trimOptions?: ImageUploadTrimOptions\n /** Image sizes generated for each upload, stored under the document's `variants`. */\n variants?: ImageSize[]\n /**\n * When an uploaded image is smaller than the defined image size, we have 3 options:\n *\n * `undefined | false | true`\n *\n * 1. `undefined` [default]: uploading images with smaller width AND height than the image size will return null\n * 2. `false`: always enlarge images to the image size\n * 3. `true`: if the image is smaller than the image size, return the original image\n */\n withoutEnlargement?: ResizeOptions['withoutEnlargement']\n} & Omit<ResizeOptions, 'withoutEnlargement'>\n\ndeclare module 'payload' {\n interface RegisteredImageSizeOptions {\n sharp: SharpImageSizeOptions\n }\n}\n\n/**\n * A collection's Sharp-owned upload-time settings, authored via\n * `sharpTransformer({ collections: { <slug>: {...} } })`. `init()` writes a\n * narrowed, Sharp-agnostic projection of `variants`/`crop`/`focalPoint`\n * back onto the sanitized collection's `upload` config for core's own use (Admin UI,\n * field generation); this richer shape is what the transformer itself reads.\n */\nexport type SharpCollectionConfig = {\n constructorOptions?: SharpOptions\n crop?: boolean\n focalPoint?: boolean\n formatOptions?: ImageUploadFormatOptions\n resizeOptions?: ResizeOptions\n trimOptions?: ImageUploadTrimOptions\n /** Image sizes generated for each upload, stored under the document's `variants`. */\n variants?: ImageSize[]\n withMetadata?: WithMetadata\n}\n\n/**\n * Matches core's (soon-removed) `SharpDependency` shape, for advanced injection\n * of a compatible custom Sharp build or version via `sharpTransformer({ sharp })`.\n */\nexport type SharpDependency = (\n input?:\n | ArrayBuffer\n | Buffer\n | Float32Array\n | Float64Array\n | Int8Array\n | Int16Array\n | Int32Array\n | string\n | Uint8Array\n | Uint8ClampedArray\n | Uint16Array\n | Uint32Array,\n options?: SharpOptions,\n) => Sharp\n\nexport type SharpDynamicDefaults = {\n /** @default 'cover' */\n fit?: keyof FitEnum\n /** @default 4096 */\n maxHeight?: number\n /**\n * Total output pixels, counted across every frame of an animated image.\n * @default 16_777_216\n */\n maxPixels?: number\n /** @default 4096 */\n maxWidth?: number\n /** @default 'center' */\n position?: ResizeOptions['position']\n /** @default false */\n withoutEnlargement?: boolean\n}\n\n/**\n * Enables request-time resizing and tunes its limits. `collections` restricts it\n * to the listed upload collections; omit it to allow every upload collection.\n */\nexport type SharpDynamicOptions = {\n collections?: UploadCollectionSlug[]\n} & SharpDynamicDefaults\n\n/**\n * The result of parsing a request's dynamic resize query parameters.\n * `isRouted: false` means none of the recognized parameters were present at\n * all — an ordinary file read, not a dynamic transformation attempt.\n */\nexport type DynamicResizeParseResult =\n | {\n error: string\n isRouted: true\n valid: false\n }\n | {\n height?: number\n isRouted: true\n valid: true\n width?: number\n withoutEnlargement?: boolean\n }\n | {\n isRouted: false\n }\n\nexport type SharpTransformerOptions = {\n /** Per-collection upload-time image processing settings. */\n collections?: Partial<Record<UploadCollectionSlug, SharpCollectionConfig>>\n /**\n * Request-time resizing via `?width=`/`?height=` on the file endpoint. `true`\n * enables it with default limits for every upload collection; an object enables\n * it with custom limits, optionally restricted to specific collections.\n *\n * @default false\n */\n dynamic?: boolean | SharpDynamicOptions\n /** Inject a compatible custom Sharp build or version. Defaults to the bundled dependency. */\n sharp?: SharpDependency\n /** @default 'sharp' */\n slug?: string\n}\n\n/**\n * `options` for the one-file-in/one-file-out `transformFile` primitive, computed\n * by `createTransformUpload` for each task it hands to the injected `transform`\n * callback: the main file, or one named legacy image size. The crop and focal point\n * are not options: `transformFile` reads them from `doc._transforms`.\n */\nexport type SharpUploadTaskOptions =\n | {\n /**\n * Whether this size may be cut around a focal point: the focal point is enabled, and the\n * size's `fit` allows a cut. `transformFile` cuts around it only when one is saved, and\n * otherwise resizes with the size's own config.\n */\n canUseFocalPoint?: boolean\n collectionUpload: SharpCollectionConfig\n imageResizeConfig: ImageSize\n kind: 'size'\n originalDimensions: ProbedImageSize\n }\n | {\n collectionUpload: SharpCollectionConfig\n /**\n * The pixel size of a crop sent in the request (`uploadEdits.widthInPixels` and\n * `heightInPixels`). It replaces the saved crop's size for this upload only.\n */\n cropSize?: { height: number; width: number }\n kind: 'main'\n /** The original's size. Without it, the saved crop cannot be applied. */\n originalDimensions?: ProbedImageSize\n }\n"],"names":[],"mappings":"AA6JA;;;;;CAKC,GACD,WAuBK"}
package/package.json CHANGED
@@ -1,13 +1,8 @@
1
1
  {
2
2
  "name": "@payloadcms/transformer-sharp",
3
- "version": "4.0.0-beta.0",
3
+ "version": "4.0.0-beta.10",
4
4
  "description": "Official Sharp-based file transformer for Payload: request-time image resizing and upload-time image processing",
5
5
  "homepage": "https://payloadcms.com",
6
- "repository": {
7
- "type": "git",
8
- "url": "https://github.com/payloadcms/payload.git",
9
- "directory": "packages/transformer-sharp"
10
- },
11
6
  "license": "MIT",
12
7
  "author": "Payload <dev@payloadcms.com> (https://payloadcms.com)",
13
8
  "maintainers": [
@@ -17,8 +12,18 @@
17
12
  "url": "https://payloadcms.com"
18
13
  }
19
14
  ],
20
- "sideEffects": false,
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/payloadcms/payload.git",
18
+ "directory": "packages/transformer-sharp"
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
21
23
  "type": "module",
24
+ "sideEffects": false,
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
22
27
  "exports": {
23
28
  ".": {
24
29
  "import": "./dist/index.js",
@@ -26,22 +31,17 @@
26
31
  "default": "./dist/index.js"
27
32
  }
28
33
  },
29
- "main": "./dist/index.js",
30
- "types": "./dist/index.d.ts",
31
- "files": [
32
- "dist"
33
- ],
34
34
  "dependencies": {
35
- "sharp": "0.35.4"
35
+ "sharp": "0.35.5"
36
36
  },
37
37
  "devDependencies": {
38
- "payload": "4.0.0-beta.0"
38
+ "payload": "4.0.0-beta.10"
39
39
  },
40
40
  "peerDependencies": {
41
- "payload": "4.0.0-beta.0"
41
+ "payload": "4.0.0-beta.10"
42
42
  },
43
43
  "engines": {
44
- "node": ">=24.15.0"
44
+ "node": "^24.22.3 || >=26.13.1"
45
45
  },
46
46
  "scripts": {
47
47
  "build": "pnpm build:types && pnpm build:swc",
@@ -49,8 +49,6 @@
49
49
  "build:debug": "pnpm build",
50
50
  "build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
51
51
  "build:types": "tsc --emitDeclarationOnly --outDir dist",
52
- "clean": "rimraf -g {dist,*.tsbuildinfo}",
53
- "lint": "eslint .",
54
- "lint:fix": "eslint . --fix"
52
+ "clean": "rimraf -g {dist,*.tsbuildinfo}"
55
53
  }
56
54
  }
@@ -1,14 +0,0 @@
1
- import type { UploadTransformerInternal } from 'payload/internal';
2
- import type { SharpCollectionConfig, SharpDependency } from './types.js';
3
- /**
4
- * Computes the legacy upload tasks (the main file, optionally cropped, and every
5
- * configured legacy image size) and hands each to the injected `transform` callback
6
- * exactly once. Reads the Sharp-owned config from `sharpTransformer({ collections })`
7
- * at factory-construction time — not from the sanitized collection, which only gets
8
- * the narrowed projection `init()` writes back.
9
- */
10
- export declare function createPrepareLegacyUpload({ collections, sharpDependency, }: {
11
- collections: Partial<Record<string, SharpCollectionConfig>>;
12
- sharpDependency: SharpDependency;
13
- }): NonNullable<UploadTransformerInternal['prepareUpload']>;
14
- //# sourceMappingURL=prepareLegacyUpload.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"prepareLegacyUpload.d.ts","sourceRoot":"","sources":["../src/prepareLegacyUpload.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAgC,yBAAyB,EAAE,MAAM,kBAAkB,CAAA;AAI/F,OAAO,KAAK,EAAE,qBAAqB,EAAE,eAAe,EAA0B,MAAM,YAAY,CAAA;AAsBhG;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,EACxC,WAAW,EACX,eAAe,GAChB,EAAE;IACD,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,qBAAqB,CAAC,CAAC,CAAA;IAC3D,eAAe,EAAE,eAAe,CAAA;CACjC,GAAG,WAAW,CAAC,yBAAyB,CAAC,eAAe,CAAC,CAAC,CAqG1D"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/prepareLegacyUpload.ts"],"sourcesContent":["import type { FocalPoint, ProbedImageSize } from 'payload'\nimport type { PreparedUploadTransformation, UploadTransformerInternal } from 'payload/internal'\n\nimport { isNumber } from 'payload/shared'\n\nimport type { SharpCollectionConfig, SharpDependency, SharpUploadTaskOptions } from './types.js'\n\nimport { canResizeImage } from './canResizeImage.js'\nimport { createSharpFromFile } from './createSharpFromFile.js'\nimport { getImageResizeAction } from './getImageResizeAction.js'\nimport { mapWithBoundedConcurrency } from './mapWithBoundedConcurrency.js'\nimport { sanitizeResizeConfig } from './sanitizeResizeConfig.js'\n\n/**\n * Sharp throws on truncated/header-only files. Returns `undefined` instead —\n * matching core's dependency-free probe — since unreadable dimensions shouldn't fail the upload.\n */\nasync function tryProbe(file: File, sharpDependency: SharpDependency) {\n try {\n const sharpFile = await createSharpFromFile({ file, sharpDependency })\n const metadata = await sharpFile.metadata()\n return metadata.width && metadata.height ? metadata : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Computes the legacy upload tasks (the main file, optionally cropped, and every\n * configured legacy image size) and hands each to the injected `transform` callback\n * exactly once. Reads the Sharp-owned config from `sharpTransformer({ collections })`\n * at factory-construction time — not from the sanitized collection, which only gets\n * the narrowed projection `init()` writes back.\n */\nexport function createPrepareLegacyUpload({\n collections,\n sharpDependency,\n}: {\n collections: Partial<Record<string, SharpCollectionConfig>>\n sharpDependency: SharpDependency\n}): NonNullable<UploadTransformerInternal['prepareUpload']> {\n return async ({ collectionSlug, file, req, transform, uploadEdits }) => {\n const collectionUpload = collections[collectionSlug] ?? {}\n\n const fileSupportsResize = canResizeImage(file.type)\n\n const cropData =\n uploadEdits && typeof uploadEdits === 'object' && 'crop' in uploadEdits\n ? uploadEdits.crop\n : undefined\n\n let originalDimensions: ProbedImageSize | undefined\n\n if (fileSupportsResize) {\n const originalMeta = await tryProbe(file, sharpDependency)\n if (originalMeta) {\n originalDimensions = { height: originalMeta.height, width: originalMeta.width }\n }\n }\n\n // Unreadable dimensions can't be cropped/resized — treat as non-resizable rather than failing the upload.\n const canProcessAsImage = fileSupportsResize && originalDimensions !== undefined\n\n const crop =\n cropData && originalDimensions\n ? {\n cropData,\n heightInPixels: uploadEdits.heightInPixels!,\n originalDimensions,\n widthInPixels: uploadEdits.widthInPixels!,\n }\n : undefined\n\n const mainResultFile = await transform({\n fieldPath: 'filename',\n options: { collectionUpload, crop, kind: 'main' } satisfies SharpUploadTaskOptions,\n })\n\n const mainResult = await describeResult({\n fieldPath: 'filename',\n fileSupportsResize: canProcessAsImage,\n resultFile: mainResultFile,\n sharpDependency,\n })\n\n const results: PreparedUploadTransformation[] = [mainResult]\n\n // Same precedence `init()` applies: Sharp's setting, else the collection's own `focalPoint`.\n const effectiveFocalPoint =\n collectionUpload.focalPoint ??\n req.payload.collections[collectionSlug]?.config.upload?.focalPoint\n const focalPointEnabled = effectiveFocalPoint !== false\n const variants = collectionUpload.variants\n\n if (canProcessAsImage && Array.isArray(variants) && originalDimensions) {\n const focalPoint: FocalPoint | undefined =\n focalPointEnabled && uploadEdits?.focalPoint\n ? {\n x: isNumber(uploadEdits.focalPoint.x) ? Math.round(uploadEdits.focalPoint.x) : 50,\n y: isNumber(uploadEdits.focalPoint.y) ? Math.round(uploadEdits.focalPoint.y) : 50,\n }\n : undefined\n\n const sizeResults = await mapWithBoundedConcurrency(variants, async (rawConfig) => {\n const imageResizeConfig = sanitizeResizeConfig(rawConfig)\n const fieldPath = `variants.${imageResizeConfig.name}` as const\n\n const resizeAction = getImageResizeAction({\n dimensions: originalDimensions,\n hasFocalPoint: Boolean(focalPoint),\n imageResizeConfig,\n })\n\n if (resizeAction === 'omit') {\n return { fieldPath } satisfies PreparedUploadTransformation\n }\n\n const sizeResultFile = await transform({\n fieldPath,\n options: {\n collectionUpload,\n focalPoint: resizeAction === 'resizeWithFocalPoint' ? focalPoint : undefined,\n imageResizeConfig,\n kind: 'size',\n originalDimensions,\n } satisfies SharpUploadTaskOptions,\n })\n\n return describeResult({\n fieldPath,\n fileSupportsResize: true,\n resultFile: sizeResultFile,\n sharpDependency,\n })\n })\n\n results.push(...sizeResults)\n }\n\n return results\n }\n}\n\nasync function describeResult({\n fieldPath,\n fileSupportsResize,\n resultFile,\n sharpDependency,\n}: {\n fieldPath: PreparedUploadTransformation['fieldPath']\n fileSupportsResize: boolean\n resultFile: File\n sharpDependency: SharpDependency\n}): Promise<PreparedUploadTransformation> {\n if (!fileSupportsResize) {\n return { fieldPath, file: resultFile, mimeType: resultFile.type }\n }\n\n const meta = await tryProbe(resultFile, sharpDependency)\n\n if (!meta) {\n return { fieldPath, file: resultFile, mimeType: resultFile.type }\n }\n\n // `tryProbe` never sets `animated: true`, so `meta.height` is already the\n // single-frame height — do not divide by page count here.\n return {\n fieldPath,\n file: resultFile,\n height: meta.height,\n mimeType: resultFile.type,\n width: meta.width,\n }\n}\n"],"names":["isNumber","canResizeImage","createSharpFromFile","getImageResizeAction","mapWithBoundedConcurrency","sanitizeResizeConfig","tryProbe","file","sharpDependency","sharpFile","metadata","width","height","undefined","createPrepareLegacyUpload","collections","collectionSlug","req","transform","uploadEdits","collectionUpload","fileSupportsResize","type","cropData","crop","originalDimensions","originalMeta","canProcessAsImage","heightInPixels","widthInPixels","mainResultFile","fieldPath","options","kind","mainResult","describeResult","resultFile","results","effectiveFocalPoint","focalPoint","payload","config","upload","focalPointEnabled","variants","Array","isArray","x","Math","round","y","sizeResults","rawConfig","imageResizeConfig","name","resizeAction","dimensions","hasFocalPoint","Boolean","sizeResultFile","push","mimeType","meta"],"mappings":"AAGA,SAASA,QAAQ,QAAQ,iBAAgB;AAIzC,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhE;;;CAGC,GACD,eAAeC,SAASC,IAAU,EAAEC,eAAgC;IAClE,IAAI;QACF,MAAMC,YAAY,MAAMP,oBAAoB;YAAEK;YAAMC;QAAgB;QACpE,MAAME,WAAW,MAAMD,UAAUC,QAAQ;QACzC,OAAOA,SAASC,KAAK,IAAID,SAASE,MAAM,GAAGF,WAAWG;IACxD,EAAE,OAAM;QACN,OAAOA;IACT;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,0BAA0B,EACxCC,WAAW,EACXP,eAAe,EAIhB;IACC,OAAO,OAAO,EAAEQ,cAAc,EAAET,IAAI,EAAEU,GAAG,EAAEC,SAAS,EAAEC,WAAW,EAAE;QACjE,MAAMC,mBAAmBL,WAAW,CAACC,eAAe,IAAI,CAAC;QAEzD,MAAMK,qBAAqBpB,eAAeM,KAAKe,IAAI;QAEnD,MAAMC,WACJJ,eAAe,OAAOA,gBAAgB,YAAY,UAAUA,cACxDA,YAAYK,IAAI,GAChBX;QAEN,IAAIY;QAEJ,IAAIJ,oBAAoB;YACtB,MAAMK,eAAe,MAAMpB,SAASC,MAAMC;YAC1C,IAAIkB,cAAc;gBAChBD,qBAAqB;oBAAEb,QAAQc,aAAad,MAAM;oBAAED,OAAOe,aAAaf,KAAK;gBAAC;YAChF;QACF;QAEA,0GAA0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BAAExB;oBAAU;gBACrB;gBAEA,MAAM4B,iBAAiB,MAAMzC,UAAU;oBACrCa;oBACAC,SAAS;wBACPZ;wBACAmB,YAAYgB,iBAAiB,yBAAyBhB,aAAa1B;wBACnEwC;wBACApB,MAAM;wBACNR;oBACF;gBACF;gBAEA,OAAOU,eAAe;oBACpBJ;oBACAV,oBAAoB;oBACpBe,YAAYuB;oBACZnD;gBACF;YACF;YAEA6B,QAAQuB,IAAI,IAAIT;QAClB;QAEA,OAAOd;IACT;AACF;AAEA,eAAeF,eAAe,EAC5BJ,SAAS,EACTV,kBAAkB,EAClBe,UAAU,EACV5B,eAAe,EAMhB;IACC,IAAI,CAACa,oBAAoB;QACvB,OAAO;YAAEU;YAAWxB,MAAM6B;YAAYyB,UAAUzB,WAAWd,IAAI;QAAC;IAClE;IAEA,MAAMwC,OAAO,MAAMxD,SAAS8B,YAAY5B;IAExC,IAAI,CAACsD,MAAM;QACT,OAAO;YAAE/B;YAAWxB,MAAM6B;YAAYyB,UAAUzB,WAAWd,IAAI;QAAC;IAClE;IAEA,0EAA0E;IAC1E,0DAA0D;IAC1D,OAAO;QACLS;QACAxB,MAAM6B;QACNxB,QAAQkD,KAAKlD,MAAM;QACnBiD,UAAUzB,WAAWd,IAAI;QACzBX,OAAOmD,KAAKnD,KAAK;IACnB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/prepareLegacyUpload.spec.ts"],"sourcesContent":["import type { PayloadRequest, UploadEdits } from 'payload'\nimport type { UploadTransformTask } from 'payload/internal'\n\nimport { describe, expect, it, vi } from 'vitest'\n\nimport type { SharpCollectionConfig, SharpDependency, SharpUploadTaskOptions } from './types.js'\n\nimport { createPrepareLegacyUpload } from './prepareLegacyUpload.js'\n\nconst sharpDependency = (() => ({\n metadata: async () => ({ height: 1000, width: 1000 }),\n})) as unknown as SharpDependency\n\nconst makeReq = ({ focalPoint }: { focalPoint?: boolean }): PayloadRequest =>\n ({\n payload: { collections: { media: { config: { upload: { focalPoint } } } } },\n }) as unknown as PayloadRequest\n\nconst runPrepareUpload = async ({\n collectionFocalPoint,\n sharpConfig,\n}: {\n collectionFocalPoint?: boolean\n sharpConfig: SharpCollectionConfig\n}) => {\n const transform = vi.fn(\n async (_task: UploadTransformTask) => new File(['x'], 'image.png', { type: 'image/png' }),\n )\n\n await createPrepareLegacyUpload({ collections: { media: sharpConfig }, sharpDependency })({\n collectionSlug: 'media',\n file: new File(['x'], 'image.png', { type: 'image/png' }),\n req: makeReq({ focalPoint: collectionFocalPoint }),\n transform,\n uploadEdits: { focalPoint: { x: 10, y: 90 } } as UploadEdits,\n })\n\n const sizeTask = transform.mock.calls\n .map(([task]) => task.options as SharpUploadTaskOptions)\n .find((options) => options.kind === 'size')\n\n return sizeTask?.kind === 'size' ? sizeTask.focalPoint : undefined\n}\n\nconst variants = [{ name: 'card', height: 200, width: 400 }]\n\ndescribe('createPrepareLegacyUpload', () => {\n it.each([\n { collectionFocalPoint: false, expected: undefined, sharpFocalPoint: undefined },\n { collectionFocalPoint: false, expected: { x: 10, y: 90 }, sharpFocalPoint: true },\n { collectionFocalPoint: undefined, expected: { x: 10, y: 90 }, sharpFocalPoint: undefined },\n ])(\n 'should resolve the size focal point from Sharp ($sharpFocalPoint) over the collection ($collectionFocalPoint)',\n async ({ collectionFocalPoint, expected, sharpFocalPoint }) => {\n expect(\n await runPrepareUpload({\n collectionFocalPoint,\n sharpConfig: { focalPoint: sharpFocalPoint, variants },\n }),\n ).toEqual(expected)\n },\n )\n})\n"],"names":["describe","expect","it","vi","createPrepareLegacyUpload","sharpDependency","metadata","height","width","makeReq","focalPoint","payload","collections","media","config","upload","runPrepareUpload","collectionFocalPoint","sharpConfig","transform","fn","_task","File","type","collectionSlug","file","req","uploadEdits","x","y","sizeTask","mock","calls","map","task","options","find","kind","undefined","variants","name","each","expected","sharpFocalPoint","toEqual"],"mappings":"AAGA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,EAAEC,EAAE,QAAQ,SAAQ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