@softistx/image 0.0.0-stage → 0.6.1

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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +551 -2
  3. package/dist/chunks/index-b71y3faz.js +20 -0
  4. package/dist/chunks/index-b71y3faz.js.map +10 -0
  5. package/dist/chunks/index-pj79f6q4.js +732 -0
  6. package/dist/chunks/index-pj79f6q4.js.map +23 -0
  7. package/dist/chunks/index-wfsrqqk2.js +16 -0
  8. package/dist/chunks/index-wfsrqqk2.js.map +10 -0
  9. package/dist/crop/crop-png.d.ts +39 -0
  10. package/dist/crop/crop-png.d.ts.map +1 -0
  11. package/dist/crop/from-query.d.ts +11 -0
  12. package/dist/crop/from-query.d.ts.map +1 -0
  13. package/dist/crop/png-chunks.d.ts +29 -0
  14. package/dist/crop/png-chunks.d.ts.map +1 -0
  15. package/dist/crop/png.d.ts +24 -0
  16. package/dist/crop/png.d.ts.map +1 -0
  17. package/dist/crop/row-assembler.d.ts +17 -0
  18. package/dist/crop/row-assembler.d.ts.map +1 -0
  19. package/dist/crop/unfilter.d.ts +10 -0
  20. package/dist/crop/unfilter.d.ts.map +1 -0
  21. package/dist/errors/image-error.d.ts +49 -0
  22. package/dist/errors/image-error.d.ts.map +1 -0
  23. package/dist/index.d.ts +10 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +42 -0
  26. package/dist/index.js.map +11 -0
  27. package/dist/input/read-input.d.ts +10 -0
  28. package/dist/input/read-input.d.ts.map +1 -0
  29. package/dist/input/sniff.d.ts +9 -0
  30. package/dist/input/sniff.d.ts.map +1 -0
  31. package/dist/pdf/index.d.ts +3 -0
  32. package/dist/pdf/index.d.ts.map +1 -0
  33. package/dist/pdf/index.js +166 -0
  34. package/dist/pdf/index.js.map +10 -0
  35. package/dist/pdf/render-pdf-page.d.ts +56 -0
  36. package/dist/pdf/render-pdf-page.d.ts.map +1 -0
  37. package/dist/process/bun-errors.d.ts +8 -0
  38. package/dist/process/bun-errors.d.ts.map +1 -0
  39. package/dist/process/geometry.d.ts +49 -0
  40. package/dist/process/geometry.d.ts.map +1 -0
  41. package/dist/process/process.d.ts +23 -0
  42. package/dist/process/process.d.ts.map +1 -0
  43. package/dist/render/render-image.d.ts +61 -0
  44. package/dist/render/render-image.d.ts.map +1 -0
  45. package/dist/s3/bind-image-store.d.ts +27 -0
  46. package/dist/s3/bind-image-store.d.ts.map +1 -0
  47. package/dist/s3/index.d.ts +4 -0
  48. package/dist/s3/index.d.ts.map +1 -0
  49. package/dist/s3/index.js +73 -0
  50. package/dist/s3/index.js.map +11 -0
  51. package/dist/s3/types.d.ts +61 -0
  52. package/dist/s3/types.d.ts.map +1 -0
  53. package/dist/s3/upload-image.d.ts +23 -0
  54. package/dist/s3/upload-image.d.ts.map +1 -0
  55. package/dist/set/define-image-set.d.ts +25 -0
  56. package/dist/set/define-image-set.d.ts.map +1 -0
  57. package/dist/set/limit.d.ts +7 -0
  58. package/dist/set/limit.d.ts.map +1 -0
  59. package/dist/set/options.d.ts +104 -0
  60. package/dist/set/options.d.ts.map +1 -0
  61. package/dist/set/runtime.d.ts +7 -0
  62. package/dist/set/runtime.d.ts.map +1 -0
  63. package/dist/set/types.d.ts +60 -0
  64. package/dist/set/types.d.ts.map +1 -0
  65. package/dist/set/whole.d.ts +3 -0
  66. package/dist/set/whole.d.ts.map +1 -0
  67. package/docs/README.md +13 -0
  68. package/docs/guide/pdf.md +60 -0
  69. package/docs/guide/processing.md +313 -0
  70. package/docs/guide/rendering.md +88 -0
  71. package/docs/guide/storing.md +219 -0
  72. package/docs/roadmap.md +71 -0
  73. package/docs/troubleshooting.md +724 -0
  74. package/package.json +90 -5
@@ -0,0 +1,88 @@
1
+ # Rendering one picture
2
+
3
+ `defineImageSet(...).process` makes squares in WebP or PNG. `renderImage` makes
4
+ **one** picture of any ratio, from a rectangle of the upload if you want, as
5
+ JPEG, WebP or PNG.
6
+
7
+ ```ts
8
+ import { renderImage } from '@softistx/image';
9
+
10
+ const hero = await renderImage(await request.blob(), {
11
+ crop: { x: 0, y: 120, width: 1600, height: 900 },
12
+ width: 800,
13
+ height: 450,
14
+ format: 'jpeg',
15
+ quality: 85,
16
+ });
17
+ await Bun.write('hero.jpg', hero.bytes); // hero.contentType is image/jpeg
18
+ ```
19
+
20
+ ## What it shares with a set
21
+
22
+ Same input types (`Uint8Array`, `ArrayBuffer`, `Blob`, `ReadableStream`), same
23
+ sniffing by first bytes, same `maxBytes` (default 5 MiB) and `maxPixels`
24
+ (default 25 000 000) checked before and during decoding, same JPEG EXIF
25
+ orientation, same stripping of ICC, EXIF, XMP and every other metadata. Calls
26
+ decode two at a time, in order; the wait is not bounded (see
27
+ [Processing](processing.md#memory-and-concurrency)).
28
+
29
+ ## The crop
30
+
31
+ `crop` is `{ x, y, width, height }` in pixels of the **upright** picture (after
32
+ EXIF rotation, JPEG only), `(x, y)` being the top-left corner. All four are whole
33
+ numbers, `width` and `height` of 1 or more, and the rectangle must fit the
34
+ picture: otherwise `ImageError` `INVALID_CROP`. Without `crop`, or with a crop
35
+ that is the whole picture, nothing is cropped.
36
+
37
+ The picture is first shrunk (never enlarged) so that the crop keeps twice the
38
+ output size, then the rectangle is read out of it while it inflates, so the
39
+ full-size pixels are never held; this is the square crop's path, for any
40
+ rectangle. A focal point is just an offset: to keep a 16:9 window around a point
41
+ `(fx, fy)`, centre it and clamp inside the picture.
42
+
43
+ `bytes` is the upload and `source` comes from a first call (or the client's preview); `fx`, `fy` is the focal point in upright pixels.
44
+
45
+ ```ts
46
+ const { source } = await renderImage(bytes, { width: 16, height: 9, format: 'png' });
47
+ const width = 1600;
48
+ const height = 900;
49
+ const x = Math.min(Math.max(0, Math.round(fx - width / 2)), source.width - width);
50
+ const y = Math.min(Math.max(0, Math.round(fy - height / 2)), source.height - height);
51
+ await renderImage(bytes, { crop: { x, y, width, height }, width: 800, height: 450, format: 'webp' });
52
+ ```
53
+
54
+ ## Size: fill, never enlarge
55
+
56
+ The crop is resized to exactly `width` x `height` with `fit: 'fill'`, which
57
+ stretches: give it the crop's ratio. A crop smaller than `width` or `height` on
58
+ either side is `TOO_SMALL` (`dimensions`), because a picture is never enlarged;
59
+ the caller clamps its target (see
60
+ [troubleshooting](../troubleshooting.md#renderimage)). Both are 1 to 8192.
61
+
62
+ ## Formats
63
+
64
+ | `format` | `contentType` | `quality` |
65
+ | --- | --- | --- |
66
+ | `'jpeg'` | `image/jpeg` | 1 to 100, default 80 |
67
+ | `'webp'` | `image/webp` | 1 to 100, default 80 |
68
+ | `'png'` | `image/png` | not allowed (`TypeError`) |
69
+
70
+ The result is `{ source, bytes, width, height, contentType }`; `source` is the
71
+ upload as read (its format and upright size), so a client can learn the size to
72
+ clamp the next crop.
73
+
74
+ ## Aborting
75
+
76
+ Pass `signal`. It is checked before the bytes are read, when the call gets its
77
+ decode slot, and between the steps, and the call rejects with `signal.reason`.
78
+ A Bun step already running is not interrupted: it finishes, its result dropped.
79
+
80
+ ## Refusals
81
+
82
+ The same `ImageError`s as a set (`TOO_LARGE`, `UNSUPPORTED_TYPE`, `UNDECODABLE`),
83
+ plus `INVALID_CROP` for the rectangle and `TOO_SMALL` for the target. A bad
84
+ option is a `TypeError`. See [troubleshooting](../troubleshooting.md#renderimage).
85
+
86
+ ## Memory and concurrency of `renderImage`
87
+
88
+ Without a crop (or with a crop that covers the whole image), `renderImage` hands the upload to `Bun.Image`, which decodes the full frame, up to `maxPixels` (25 million pixels, roughly 100 MB as RGBA) per call. With a crop, the image is first shrunk and streamed, so the held memory is much smaller. These figures are estimates, not measurements. `renderImage` has its own limit of two simultaneous decodes, separate from the one of an image set and not configurable. `signal` is checked between steps, not in the middle of a decode. With `fit: 'fill'`, give a crop of the same ratio as `width` by `height`, or the picture is stretched.
@@ -0,0 +1,219 @@
1
+ # Storing the variants
2
+
3
+ `bindImageStore` from `@softistx/image/s3` processes an upload and puts every size
4
+ into a `@softistx/s3` bucket in one call. It needs the optional peer: `bun add
5
+ @softistx/s3`. For the processing itself, see [processing](processing.md).
6
+
7
+ ```ts
8
+ import { randomUUID } from 'node:crypto';
9
+ import { defineImageSet } from '@softistx/image';
10
+ import { bindImageStore } from '@softistx/image/s3';
11
+ import { bindBucket, defineBucket } from '@softistx/s3';
12
+
13
+ const bucket = defineBucket({
14
+ bucket: 'avatars',
15
+ key: (p: { imageId: string; size: number }) =>
16
+ `avatars/${p.imageId}/${p.size}.webp`,
17
+ });
18
+
19
+ const avatarSet = defineImageSet({ sizes: [256, 64] });
20
+ const avatars = bindImageStore(
21
+ avatarSet,
22
+ bindBucket(bucket, {
23
+ endpoint: 'https://s3.example.com', // your own, from the environment
24
+ accessKeyId: 'access-key',
25
+ secretAccessKey: 'secret-key',
26
+ }),
27
+ );
28
+
29
+ const imageId = randomUUID();
30
+ const stored = await avatars.replace({ imageId }, await request.blob());
31
+ // { version: '3f9c2a41b7d0e856', variants: [{ size: 256, key, width, height, contentType, byteLength }, ...] }
32
+ ```
33
+
34
+ ## The key takes a `size`
35
+
36
+ The bucket's key function must take a `size: number` beside its other params,
37
+ and use it: two sizes under one key would overwrite each other. The store's
38
+ params are the bucket's **minus `size`**; it adds the size itself.
39
+
40
+ ```ts
41
+ bindImageStore<P extends { size: number }, F extends ImageFormat = ImageFormat>(
42
+ set: ImageSet<F>, // F, the set's format, carries to the stored content type
43
+ bucket: BoundBucket<P>,
44
+ ): ImageStore<Omit<P, 'size'>, F>;
45
+ ```
46
+
47
+ ## The store
48
+
49
+ ```ts
50
+ type ImageStore<P, F extends ImageFormat = ImageFormat> = {
51
+ replace(params: P, input: ImageInput, options?: ProcessOptions): Promise<StoredImage<F>>;
52
+ remove(params: P): Promise<void>;
53
+ presignGet(params: P, size: number, options?: PresignGetOptions): string;
54
+ bytes(params: P, size: number): Promise<Uint8Array | undefined>;
55
+ keyFor(params: P, size: number): string;
56
+ };
57
+
58
+ type StoredImage<F extends ImageFormat = ImageFormat> = { version: string; variants: StoredVariant<F>[] };
59
+ type StoredVariant<F extends ImageFormat = ImageFormat> = {
60
+ size: number;
61
+ key: string;
62
+ width: number;
63
+ height: number;
64
+ contentType: ImageContentType<F>; // the set's
65
+ byteLength: number;
66
+ };
67
+ ```
68
+
69
+ | Method | Does |
70
+ | --- | --- |
71
+ | `replace(params, input, { crop })` | processes the upload, then puts every size with the set's `contentType` (`image/webp` by default); returns `{ version, variants }` |
72
+ | `remove(params)` | deletes every size; a missing object is not an error |
73
+ | `presignGet(params, size, options)` | a signed URL for one size |
74
+ | `bytes(params, size)` | the bytes of one size, `undefined` when missing |
75
+ | `keyFor(params, size)` | the key of one size |
76
+
77
+ A `size` outside the set's `sizes` is a `RangeError` that names the call:
78
+ `presignGet: size 128 is not one of the set's sizes (256, 64)`. `ImageSet.sizes` is public,
79
+ so a caller can list them.
80
+
81
+ A refused upload (an `ImageError`, a bad crop included) comes out
82
+ **before anything is written**. S3 errors are rethrown unchanged.
83
+
84
+ ## PNG variants
85
+
86
+ A `format: 'png'` set stores `image/png` objects. The key is the caller's, so
87
+ put the set's `format` in it as the extension:
88
+
89
+ ```ts
90
+ import { defineImageSet } from '@softistx/image';
91
+ import { bindImageStore } from '@softistx/image/s3';
92
+ import { bindBucket, defineBucket } from '@softistx/s3';
93
+
94
+ const logoSet = defineImageSet({ sizes: [512], format: 'png' });
95
+ const logoBucket = defineBucket({
96
+ bucket: 'logos',
97
+ contentType: logoSet.contentType, // 'image/png'
98
+ key: (p: { imageId: string; size: number }) =>
99
+ `logos/${p.imageId}/${p.size}.${logoSet.format}`, // .png
100
+ });
101
+ const logos = bindImageStore(
102
+ logoSet,
103
+ bindBucket(logoBucket, {
104
+ endpoint: 'https://s3.example.com', // your own, from the environment
105
+ accessKeyId: 'access-key',
106
+ secretAccessKey: 'secret-key',
107
+ }),
108
+ );
109
+ ```
110
+
111
+ ## What the bucket must accept
112
+
113
+ `replace` puts the set's `contentType` (`image/webp`, or `image/png` for a
114
+ `format: 'png'` set), so the bucket's `contentType` (if the definition
115
+ names one) must include it, and its `maxSize` must be at least the largest
116
+ variant. Otherwise every put is refused before it is sent and `replace` throws
117
+ that refusal; nothing is deleted, since nothing was written.
118
+
119
+ Bind the bucket **without a public default `acl`**: the store passes none, so
120
+ Bun would send the bucket's on every put. Some services (AWS buckets with ACLs
121
+ disabled, the default) refuse an ACL header outright. A bucket policy can still
122
+ make objects public if you want that.
123
+
124
+ ## Use a fresh id per upload
125
+
126
+ Put an id that changes on every upload in the key, store it, and remove the
127
+ former id's images afterwards:
128
+
129
+ ```ts
130
+ const imageId = randomUUID();
131
+ const { version } = await avatars.replace({ imageId }, await request.blob());
132
+
133
+ const former = user.avatar?.imageId;
134
+ user.avatar = { imageId, version };
135
+ await user.save();
136
+
137
+ if (former) await avatars.remove({ imageId: former });
138
+ ```
139
+
140
+ In an HTTP route, `uploadImage(store, owner, request)` does the first step for
141
+ you: it checks the request is `image/*` (`UNSUPPORTED_TYPE` otherwise),
142
+ generates the fresh id, reads the optional `?x=&y=&size=` crop with
143
+ `cropFromQuery`, streams the body into `replace` (so the byte limit is
144
+ `TOO_LARGE` mid-stream) and returns `{ id, version, variants }`:
145
+
146
+ ```ts
147
+ import { uploadImage } from '@softistx/image/s3';
148
+
149
+ const { id, version } = await uploadImage(avatars, { userId }, request);
150
+ ```
151
+
152
+ `owner` is the store's params without `imageId`, so the key must take an
153
+ `imageId` string. A blank or non-numeric crop value is refused as
154
+ `INVALID_CROP`, an error to answer with a 4xx.
155
+
156
+ Why not a fixed key such as `{ userId }`? Because the replacing upload would
157
+ land on the same keys as the image it replaces, and the cleanup that follows
158
+ ("remove the former image") would then delete the **new** one. A fixed key
159
+ also has a failure mode of its own: a failed `replace` may have overwritten
160
+ some sizes before another failed, and the cleanup removes those. With a fresh
161
+ id, a failed `replace` touches only objects nobody references yet.
162
+
163
+ Keep this order: save the id, then remove the former image, and never inside a
164
+ transaction that may roll back (the bytes would be gone while the row points at
165
+ them). `remove` on a service that answers 404 to a delete of a missing object
166
+ (for example GCS) throws `NoSuchKey`; a versioned bucket keeps the bytes behind
167
+ delete markers, so expire old versions with a lifecycle rule.
168
+
169
+ If the process dies between `replace` and `remove`, the former image stays as
170
+ an unreferenced object: sweep for those with a lifecycle rule or a job.
171
+
172
+ ## A failed put
173
+
174
+ `replace` puts every size at once. If one put fails, it deletes the keys whose
175
+ put succeeded (best effort), never the key whose put was refused, and rethrows
176
+ the first put error, first meaning first in the order of `sizes`, not first in
177
+ time. A put that failed after sending (a network error) may still land on the
178
+ server after the delete; under a fresh id that leaves at worst one unreferenced
179
+ object.
180
+
181
+ ## Serving
182
+
183
+ Objects are **never public**: the store passes no `acl` (bind the bucket without
184
+ a public one). Serve them through a signed URL or through your own route.
185
+
186
+ ```ts
187
+ // a signed URL, valid for 5 minutes
188
+ const url = avatars.presignGet({ imageId }, 64, { expiresIn: 300 });
189
+
190
+ // or stream it from a route
191
+ app.get('/avatars/:imageId/:size', async (c) => {
192
+ const size = Number(c.req.param('size'));
193
+ if (!avatarSet.sizes.includes(size)) return c.notFound();
194
+ const bytes = await avatars.bytes({ imageId: c.req.param('imageId') }, size);
195
+ if (!bytes) return c.notFound();
196
+ return c.body(bytes, 200, {
197
+ 'Content-Type': avatarSet.contentType, // image/webp, or image/png for a png set
198
+ 'Cache-Control': 'private, max-age=86400',
199
+ });
200
+ });
201
+ ```
202
+
203
+ A size that is not in the set throws a `RangeError` before any request is
204
+ made: it is the caller's bug, so the route checks the URL parameter against
205
+ `set.sizes` first and answers 404, as above (`avatarSet` is the set passed to
206
+ `bindImageStore`).
207
+
208
+ ## `version`
209
+
210
+ `version` is 16 hex characters of the SHA-256 over the variants' bytes, in the
211
+ order of `sizes`. The same picture processed again gives the same version, so
212
+ it works as a cache-busting query or an ETag:
213
+
214
+ ```ts
215
+ const etag = `"${stored.version}"`;
216
+ const src = `/avatars/${imageId}/256?v=${stored.version}`;
217
+ ```
218
+
219
+ Store it beside the id: it changes whenever the image does.
@@ -0,0 +1,71 @@
1
+ # Roadmap
2
+
3
+ Where `@softistx/image` is going. A direction, not a commitment: the version an
4
+ item shipped in is the only number on this page.
5
+
6
+ ## Now
7
+
8
+ - **PNG or lossless WebP variants** — built, released with the next minor.
9
+ `format: 'png'` makes `image/png` squares, each encoded once from the
10
+ decoded upload, for a consumer that does not read WebP (a PDF renderer);
11
+ `lossless: true` makes lossless WebP. The set's `format` and `contentType`
12
+ give the key's extension and the type `bindImageStore` puts, and the set's
13
+ type follows its format. The default stays lossy WebP.
14
+
15
+ - **A thumbnail of a PDF** — built, released with the next minor.
16
+ `@softistx/image/pdf` `renderPdfFirstPage` draws page 1 of a PDF as JPEG,
17
+ WebP or PNG on pdf.js and `@napi-rs/canvas` (optional peers), encoded by
18
+ `Bun.Image`. Other pages and a text layer are not planned yet.
19
+
20
+ ## Next
21
+
22
+ _Nothing queued._
23
+
24
+ ## Later
25
+
26
+ - **HEIC on Linux** — an iPhone photo decodes on a Linux server too, once Bun
27
+ can decode HEIC there. Until then such an upload is refused with
28
+ `UNSUPPORTED_TYPE` and the reason `heic-unavailable`.
29
+ - **A crop done by Bun itself** — the same square for less memory, if Bun
30
+ adds a crop of its own.
31
+ - **Cancel a queued call (`AbortSignal`)** — a call that waits for a free
32
+ decoding slot gives up when its caller does, instead of holding its bytes.
33
+ - **Colour conversion to sRGB** — a wide-gamut photo keeps its colours instead
34
+ of losing its profile, if Bun supports the conversion.
35
+ - **A low-quality placeholder per image** — a tiny blurred preview to show
36
+ while the real one loads, from `Bun.Image.placeholder()`.
37
+
38
+ ## Not planned
39
+
40
+ - **A third-party image library (sharp)** — the package runs on Bun's own
41
+ `Bun.Image` and has no required dependency (`@softistx/s3` is an optional peer).
42
+ That is the point of it, and a feature Bun lacks waits for Bun, as the
43
+ entries under Later do.
44
+ - **Public URLs** — a stored image is never public: no `acl` is ever passed,
45
+ and a link comes from `presignGet`, which expires.
46
+
47
+ ## Shipped
48
+
49
+ - **Processing an upload into square WebP variants** —
50
+ `defineImageSet().process` takes bytes, a buffer, a `Blob` or a stream and
51
+ returns one square `image/webp` per size. JPEG, PNG, WebP and HEIC are
52
+ recognised by their first bytes, not the name or the declared type; a size
53
+ cap and a pixel cap refuse an oversized upload before it is decoded; the
54
+ crop is centred unless the caller gives one; every piece of metadata (EXIF
55
+ with its GPS, and the ICC profile) is stripped; `concurrency` bounds how
56
+ many uploads decode at once, and is not a hard memory ceiling. Every refusal is an `ImageError`
57
+ with a `code` to switch on — 0.1.0.
58
+ - **Storing the variants in a bucket** — `@softistx/image/s3` `bindImageStore`
59
+ gives `replace`, `remove`, `presignGet` and `bytes` over a `@softistx/s3`
60
+ bucket. `replace` returns a `version` that changes with the content, a
61
+ refused upload writes nothing, and objects are never public — 0.1.0.
62
+ - **Upload route helpers** — `cropFromQuery` reads an optional crop from
63
+ `?x=&y=&size=`, and `@softistx/image/s3` `uploadImage` turns an `image/*` request
64
+ into a stored image under a fresh id, returning `{ id, version, variants }`.
65
+ - **Rectangle crops and JPEG output** — `renderImage` renders one picture
66
+ of any ratio from a `{ x, y, width, height }` crop of the upright picture, as
67
+ JPEG, WebP or PNG, never enlarging, with the set's limits and metadata
68
+ stripping.
69
+
70
+ Everything released is in [`CHANGELOG.md`](https://github.com/softistx/nxgt-data/blob/develop/packages/image/CHANGELOG.md) — it is not in
71
+ the published package, only in the repository.